auditmysite 0.26.0

Resource-efficient WCAG 2.1 Accessibility Checker in Rust
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
use renderreport::components::advanced::{
    ChecklistPanel, ChecklistRow, KeyValueList, List, PageBreak, SectionHeaderSplit,
    TableOfContents,
};
use renderreport::components::text::{Label, TextBlock};
use renderreport::components::{AuditTable, BenchmarkRow, BenchmarkTable, TableColumn};
use renderreport::prelude::Image;
use renderreport::prelude::*;

use crate::audit::BatchReport;
use crate::cli::ReportLevel;
use crate::i18n::I18n;
use crate::output::builder::build_batch_presentation;
use crate::output::report_model::*;
use crate::util::truncate_url;

use super::batch::build_batch_overview_grid;
use super::cover::{batch_certificate_label, build_batch_cover_score_row, certificate_badge_path};
use super::findings::first_sentence;
use super::helpers::{priority_label_i18n, role_label_i18n, severity_label_i18n};

// ─── Helper: Batch Report Assessment & Key Points ──────────────────────────

/// Clear batch assessment — no score, just interpretation
pub(super) fn build_batch_assessment(
    summary: &crate::output::report_model::PortfolioSummary,
    dist: &SeverityDistribution,
    i18n: &I18n,
) -> String {
    let en = i18n.locale() == "en";
    let score = summary.average_score.round() as u32;
    if dist.critical > 0 && score < 50 {
        if en {
            "Critical barriers — not WCAG conformant".to_string()
        } else {
            "Kritische Barrieren — nicht WCAG-konform".to_string()
        }
    } else if dist.critical > 0 {
        if en {
            "Technically solid, but legally risky".to_string()
        } else {
            "Technisch solide, aber rechtlich riskant".to_string()
        }
    } else if dist.high > 0 {
        if en {
            "Good foundation, but not accessible".to_string()
        } else {
            "Gute Basis, aber nicht barrierefrei".to_string()
        }
    } else if score >= 85 {
        if en {
            "Largely accessible — polish".to_string()
        } else {
            "Weitgehend barrierefrei — Feinschliff".to_string()
        }
    } else if en {
        "Solid foundation with room to optimize".to_string()
    } else {
        "Solide Grundlage mit Optimierungspotenzial".to_string()
    }
}

/// 3 key takeaways for batch report
pub(super) fn build_batch_key_points(
    pres: &BatchPresentation,
    dist: &SeverityDistribution,
    i18n: &I18n,
) -> Vec<String> {
    let en = i18n.locale() == "en";
    let mut points = Vec::with_capacity(3);

    // Point 1: Critical/high count across all URLs
    let ch = dist.critical + dist.high;
    if ch > 0 {
        if en {
            points.push(format!(
                "{} critical/high violations across {} URLs",
                ch, pres.portfolio_summary.total_urls
            ));
        } else {
            points.push(format!(
                "{} kritische/hohe Verstöße über {} URLs hinweg",
                ch, pres.portfolio_summary.total_urls
            ));
        }
    }

    // Point 2: Dominant/recurring issue
    if let Some(top) = pres.top_issues.first() {
        if en {
            points.push(format!(
                "Main issue: {} ({} occurrences on {} URLs)",
                top.title,
                top.occurrence_count,
                top.affected_urls.len()
            ));
        } else {
            points.push(format!(
                "Hauptproblem: {} ({} Vorkommen auf {} URLs)",
                top.title,
                top.occurrence_count,
                top.affected_urls.len()
            ));
        }
    }

    // Point 3: Legal status
    if dist.critical > 0 {
        if en {
            points.push(
                "WCAG Level A violations detected automatically — manual review needed for a defensible BFSG classification".to_string(),
            );
        } else {
            points.push(
                "WCAG-Level-A-Verstöße automatisiert erkannt — manuelle Prüfung für belastbare BFSG-Einordnung nötig".to_string(),
            );
        }
    } else if dist.high > 0 {
        if en {
            points.push(
                "No Level A violations, but structural weaknesses on multiple pages".to_string(),
            );
        } else {
            points.push(
                "Keine Level-A-Verstöße, aber strukturelle Schwächen auf mehreren Seiten"
                    .to_string(),
            );
        }
    } else if en {
        points.push(
            "No automatically detectable critical barriers — manual review recommended."
                .to_string(),
        );
    } else {
        points.push(
            "Keine automatisiert erkennbaren kritischen Barrieren — manuelle Prüfung empfohlen."
                .to_string(),
        );
    }

    points
}

/// Concrete quick actions for batch report
pub(super) fn build_batch_quick_actions(pres: &BatchPresentation, _i18n: &I18n) -> Vec<String> {
    let mut actions: Vec<String> = Vec::new();

    for item in &pres.action_plan.quick_wins {
        if actions.len() >= 3 {
            break;
        }
        let action_lower = item.action.to_lowercase();
        let scope = if action_lower.contains("alle") || action_lower.contains("global") {
            " (global)"
        } else {
            ""
        };
        actions.push(format!("{}{}", item.action, scope));
    }

    // Fallback from top issues
    if actions.is_empty() {
        for group in pres.top_issues.iter().take(3) {
            let rec = first_sentence(&group.recommendation);
            if !rec.is_empty() {
                actions.push(rec.to_string());
            }
        }
    }

    actions
}

/// Enhanced action plan with effort + scope columns
pub(super) fn render_batch_action_plan_enhanced(
    mut builder: renderreport::engine::ReportBuilder,
    plan: &ActionPlan,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let effort_col = if en { "Effort" } else { "Aufwand" };
    let role_col = if en { "Role" } else { "Rolle" };
    let scope_global = "global";
    let scope_content = "Content";
    let scope_component = if en { "Component" } else { "Komponente" };

    let render_section = |mut b: renderreport::engine::ReportBuilder,
                          title: String,
                          items: &[crate::output::report_model::ActionItem],
                          i18n: &I18n|
     -> renderreport::engine::ReportBuilder {
        if items.is_empty() {
            return b;
        }
        b = b.add_component(Section::new(title).with_level(2));
        let mut table = AuditTable::new(vec![
            TableColumn::new(i18n.t("column-action")),
            TableColumn::new(effort_col),
            TableColumn::new(if en { "Scope" } else { "Reichweite" }),
            TableColumn::new(role_col),
            TableColumn::new(i18n.t("column-priority")),
        ]);
        for item in items {
            let action_lower = item.action.to_lowercase();
            let scope = if action_lower.contains("alle")
                || action_lower.contains("global")
                || action_lower.contains("designsystem")
                || action_lower.contains("design system")
                || action_lower.contains("seitenübergreifend")
                || action_lower.contains("site-wide")
            {
                scope_global
            } else if action_lower.contains("content")
                || action_lower.contains("text")
                || action_lower.contains("bild")
                || action_lower.contains("image")
            {
                scope_content
            } else {
                scope_component
            };
            table = table.add_row(vec![
                item.action.clone(),
                item.effort.label().to_string(),
                scope.to_string(),
                role_label_i18n(item.role, i18n),
                priority_label_i18n(item.priority, i18n),
            ]);
        }
        b.add_component(table)
    };

    builder = render_section(
        builder,
        i18n.t("section-quick-wins"),
        &plan.quick_wins,
        i18n,
    );
    builder = render_section(
        builder,
        i18n.t("section-medium-actions"),
        &plan.medium_term,
        i18n,
    );
    builder = render_section(
        builder,
        i18n.t("section-structural-actions"),
        &plan.structural,
        i18n,
    );
    builder
}

/// Render cross-page consistency analysis (issues #44/#45/#46).
/// Shows navigation, heading, and canonical consistency stats with any
/// findings as warning rows.
pub(super) fn render_batch_consistency(
    mut builder: renderreport::engine::ReportBuilder,
    consistency: &crate::audit::batch_consistency::BatchConsistencyAnalysis,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let title = if en {
        "Cross-page consistency"
    } else {
        "Seitenübergreifende Konsistenz"
    };
    let intro = if en {
        "Checks that shared structural elements (navigation, headings, canonical URLs) are consistent across all audited pages. WCAG 3.2.3 / 3.2.4."
    } else {
        "Prüft, ob geteilte strukturelle Elemente (Navigation, Überschriften, Canonical-URLs) auf allen geprüften Seiten konsistent sind. WCAG 3.2.3 / 3.2.4."
    };
    builder = builder.add_component(SectionHeaderSplit::new(title, intro).with_level(2));

    let nav = &consistency.navigation;
    let nav_title = if en {
        format!(
            "Navigation ({}/{} with main nav, {}/{} with skip link)",
            nav.pages_with_main_nav, nav.total_pages, nav.pages_with_skip_link, nav.total_pages
        )
    } else {
        format!(
            "Navigation ({}/{} mit Hauptnav, {}/{} mit Skip-Link)",
            nav.pages_with_main_nav, nav.total_pages, nav.pages_with_skip_link, nav.total_pages
        )
    };
    let nav_rows: Vec<ChecklistRow> = if nav.findings.is_empty() {
        vec![ChecklistRow::new(
            if en { "Consistent" } else { "Konsistent" },
            if en {
                "No navigation inconsistencies detected."
            } else {
                "Keine Navigation-Inkonsistenzen erkannt."
            },
        )
        .with_status("good")]
    } else {
        nav.findings
            .iter()
            .map(|f| {
                ChecklistRow::new(if en { "Issue" } else { "Befund" }, f.as_str())
                    .with_status("warn")
            })
            .collect()
    };
    builder = builder.add_component(ChecklistPanel::new(nav_rows).with_title(&nav_title));

    let h = &consistency.headings;
    let head_title = if en {
        format!(
            "Headings ({}/{} with single H1, {} missing, {} multiple)",
            h.pages_with_single_h1, h.total_pages, h.pages_with_no_h1, h.pages_with_multiple_h1
        )
    } else {
        format!(
            "Überschriften ({}/{} mit einem H1, {} ohne H1, {} mit mehreren)",
            h.pages_with_single_h1, h.total_pages, h.pages_with_no_h1, h.pages_with_multiple_h1
        )
    };
    let head_rows: Vec<ChecklistRow> = if h.findings.is_empty() {
        vec![ChecklistRow::new(
            if en { "Consistent" } else { "Konsistent" },
            if en {
                "Every page starts with exactly one H1."
            } else {
                "Jede Seite beginnt mit genau einem H1."
            },
        )
        .with_status("good")]
    } else {
        h.findings
            .iter()
            .map(|f| {
                ChecklistRow::new(if en { "Issue" } else { "Befund" }, f.as_str())
                    .with_status("warn")
            })
            .collect()
    };
    builder = builder.add_component(ChecklistPanel::new(head_rows).with_title(&head_title));

    let c = &consistency.canonical;
    let canon_title = if en {
        format!(
            "Canonical URLs (www: {}, non-www: {}, missing: {} of {})",
            c.www_count, c.non_www_count, c.missing_count, c.total_pages
        )
    } else {
        format!(
            "Canonical-URLs (www: {}, ohne www: {}, fehlend: {} von {})",
            c.www_count, c.non_www_count, c.missing_count, c.total_pages
        )
    };
    let canon_rows: Vec<ChecklistRow> = if c.findings.is_empty() {
        vec![ChecklistRow::new(
            if en { "Consistent" } else { "Konsistent" },
            if en {
                "All pages canonicalize to the same domain variant."
            } else {
                "Alle Seiten kanonisieren auf dieselbe Domain-Variante."
            },
        )
        .with_status("good")]
    } else {
        c.findings
            .iter()
            .map(|f| {
                ChecklistRow::new(if en { "Issue" } else { "Befund" }, f.as_str())
                    .with_status("warn")
            })
            .collect()
    };
    builder.add_component(ChecklistPanel::new(canon_rows).with_title(&canon_title))
}

/// Closing section for batch report
pub(super) fn render_next_steps_batch(
    mut builder: renderreport::engine::ReportBuilder,
    pres: &BatchPresentation,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let intro = if en {
        "Concrete recommendation for implementation."
    } else {
        "Konkrete Handlungsempfehlung für die Umsetzung."
    };
    builder = builder.add_component(
        SectionHeaderSplit::new(i18n.t("section-next-steps-recommended"), intro).with_level(1),
    );

    let mut steps: Vec<(String, &str)> = Vec::new();

    let scope_global = "global";
    let scope_component = if en {
        "component-based"
    } else {
        "komponentenbasiert"
    };

    // From quick wins
    for item in &pres.action_plan.quick_wins {
        if steps.len() >= 3 {
            break;
        }
        let action_lower = item.action.to_lowercase();
        let scope = if action_lower.contains("alle")
            || action_lower.contains("designsystem")
            || action_lower.contains("design system")
            || action_lower.contains("global")
        {
            scope_global
        } else {
            scope_component
        };
        steps.push((item.action.clone(), scope));
    }

    // Fallback from medium_term
    if steps.len() < 3 {
        for item in &pres.action_plan.medium_term {
            if steps.len() >= 3 {
                break;
            }
            steps.push((item.action.clone(), scope_component));
        }
    }

    if !steps.is_empty() {
        let mut table = AuditTable::new(vec![
            TableColumn::new(i18n.t("column-priority")),
            TableColumn::new(i18n.t("column-action")),
            TableColumn::new(if en { "Scope" } else { "Reichweite" }),
        ]);
        for (i, (action, scope)) in steps.iter().enumerate() {
            table = table.add_row(vec![
                format!("{}", i + 1),
                action.clone(),
                scope.to_string(),
            ]);
        }
        builder = builder.add_component(table);
    }

    let callout_body = if en {
        "For a complete WCAG conformance check we additionally recommend a manual audit with assistive technologies (screen reader, keyboard navigation). This automated audit covers about 30–40% of WCAG criteria."
    } else {
        "Für eine vollständige WCAG-Konformitätsprüfung empfehlen wir ergänzend einen manuellen Audit mit assistiven Technologien (Screenreader, Tastaturnavigation). Dieser automatisierte Audit deckt ca. 30–40% der WCAG-Kriterien ab."
    };
    builder = builder
        .add_component(Callout::info(callout_body).with_title(i18n.t("section-next-steps-block")));

    builder
}

// ─── Batch Report ───────────────────────────────────────────────────────────

pub fn generate_batch_pdf(batch: &BatchReport, config: &ReportConfig) -> anyhow::Result<Vec<u8>> {
    let (engine, built_report) = build_batch_report(batch, config)?;
    Ok(engine.render_pdf(&built_report)?)
}

/// Render the intermediate Typst source for a batch report (hidden `--debug-typ`).
pub fn generate_batch_typ(batch: &BatchReport, config: &ReportConfig) -> anyhow::Result<String> {
    let (engine, built_report) = build_batch_report(batch, config)?;
    Ok(engine.render_typ(&built_report)?)
}

fn build_batch_report(
    batch: &BatchReport,
    config: &ReportConfig,
) -> anyhow::Result<(renderreport::Engine, renderreport::RenderRequest)> {
    let engine = super::helpers::create_engine()?;
    let i18n = I18n::new(&config.locale)?;
    let pres = build_batch_presentation(batch);

    let domain = &pres.portfolio_summary.domain;
    let score = pres.portfolio_summary.average_score.round() as u32;

    let mut builder = engine
        .report("wcag-batch-audit")
        .title(&pres.cover.title)
        .subtitle(&pres.cover.url)
        .metadata("date", &pres.cover.date)
        .metadata("version", &pres.cover.version)
        .metadata("author", domain)
        .metadata("footer_prefix", "Audit:")
        .metadata("footer_link_url", "")
        .metadata(
            "footer_tagline",
            "A technical auditing platform by casoon.de",
        );

    let cover_logo_asset = super::cover_logo_asset(config);
    builder = super::register_cover_logo_asset(builder, config, cover_logo_asset);

    // ── Cover Page with Audit-Rahmen ────────────────────────────────
    builder = builder
        .add_component(Image::new(cover_logo_asset).with_width("120pt"))
        .add_component(
            Label::new(i18n.t("batch-cover-eyebrow"))
                .with_size("11pt")
                .bold()
                .with_color("#0f766e"),
        )
        .add_component(
            Label::new(i18n.t("batch-cover-title"))
                .with_size("28pt")
                .bold(),
        )
        .add_component(
            Label::new(i18n.t("batch-cover-kicker"))
                .with_size("12pt")
                .with_color("#475569"),
        );

    // Audit-Rahmen box (matching single report style)
    {
        let modules_str = pres.portfolio_summary.active_modules.join(", ");

        let mut cover_meta = KeyValueList::new().with_title(i18n.t("batch-cover-frame-title"));
        cover_meta = cover_meta
            .add(i18n.t("batch-cover-frame-domain"), domain)
            .add(i18n.t("batch-cover-frame-date"), &pres.cover.date)
            .add(
                i18n.t("batch-cover-frame-urls"),
                format!("{}", pres.portfolio_summary.total_urls),
            )
            .add(
                i18n.t("batch-cover-frame-certificate"),
                &pres.portfolio_summary.certificate,
            )
            .add(i18n.t("batch-cover-frame-modules"), &modules_str)
            .add(
                i18n.t("batch-cover-frame-version"),
                format!("auditmysite v{}", pres.cover.version),
            );
        builder = builder.add_component(cover_meta);
    }

    let batch_badge_asset = "/certificate-badge-batch.svg";
    let batch_badge_enabled =
        if let Ok(path) = certificate_badge_path(batch_certificate_label(score)) {
            builder = builder.asset(batch_badge_asset, path);
            true
        } else {
            false
        };

    builder = builder
        .add_component(build_batch_cover_score_row(
            score,
            pres.portfolio_summary.total_urls as u32,
            pres.portfolio_summary.total_violations as u32,
            batch_badge_enabled.then_some(batch_badge_asset),
            &i18n,
        )?)
        .add_component(
            TextBlock::new(&pres.portfolio_summary.verdict_text)
                .with_size("11pt")
                .with_line_height("1.4em")
                .with_max_width("100%"),
        )
        .add_component(super::output_scope_callout(&i18n))
        .add_component(PageBreak::new());
    if config.level != ReportLevel::Executive {
        builder = builder.add_component(TableOfContents::new().with_depth(1));
    }

    let dist = &pres.portfolio_summary.severity_distribution;

    // ── 1. Status der Website ───────────────────────────────────────
    {
        // Block 1: Bewertung — klare Einordnung, Risiko primär
        let assessment = build_batch_assessment(&pres.portfolio_summary, dist, &i18n);
        let risk_title = assessment;
        let callout = match pres.portfolio_summary.risk_level.as_str() {
            "Kritisch" | "Hoch" | "Critical" | "High" => {
                Callout::warning(&pres.portfolio_summary.risk_summary).with_title(&risk_title)
            }
            "Mittel" | "Medium" => {
                Callout::info(&pres.portfolio_summary.risk_summary).with_title(&risk_title)
            }
            _ => Callout::success(&pres.portfolio_summary.risk_summary).with_title(&risk_title),
        };
        builder = builder
            .add_component(Section::new(i18n.t("batch-section-status")).with_level(1))
            .add_component(callout);
    }

    // Score overview cards (sekundär)
    builder = builder.add_component(build_batch_overview_grid(
        pres.portfolio_summary.total_urls as u32,
        score,
        pres.portfolio_summary.total_violations as u32,
        (dist.critical + dist.high) as u32,
        pres.portfolio_summary.crawl_links.as_ref().map(|links| {
            (links.broken_internal_links.len() + links.broken_external_links.len()) as u32
        }),
    ));

    // Block 2: Kernaussagen (max 3 Punkte)
    {
        let key_points = build_batch_key_points(&pres, dist, &i18n);
        let mut kp_list = List::new().with_title(i18n.t("narrative-key-points-title"));
        for point in &key_points {
            kp_list = kp_list.add_item(point);
        }
        builder = builder.add_component(kp_list);
    }

    // Auswirkungen
    {
        let en = i18n.locale() == "en";
        let a11y_avg = pres.portfolio_summary.average_score.round() as u32;
        let user_impact = match (a11y_avg, en) {
            (s, true) if s < 50 => "Critical — core functions are unreachable for users with disabilities",
            (s, false) if s < 50 => "Kritisch — zentrale Funktionen sind für Nutzer mit Einschränkungen nicht erreichbar",
            (s, true) if s < 70 => "Limited — structural issues impede users with assistive technologies",
            (s, false) if s < 70 => "Eingeschränkt — strukturelle Probleme behindern Nutzer mit Hilfstechnologien",
            (s, true) if s < 85 => "Good — individual barriers for assistive technologies on several pages",
            (s, false) if s < 85 => "Gut — einzelne Barrieren für Hilfstechnologien auf mehreren Seiten",
            (_, true) => "Very good — assistive technologies are largely supported",
            (_, false) => "Sehr gut — Hilfstechnologien werden weitgehend unterstützt",
        };
        let business_impact = if dist.critical > 0 {
            if en {
                "Large parts of the website are unusable or barely usable for certain user groups."
            } else {
                "Weite Teile der Website sind für bestimmte Nutzergruppen nicht oder kaum nutzbar."
            }
        } else if dist.high > 0 {
            if en {
                "Individual functional areas are problematic for users with disabilities."
            } else {
                "Einzelne Funktionsbereiche sind für Nutzer mit Einschränkungen problematisch."
            }
        } else if en {
            "Low impact — users can fundamentally use the website."
        } else {
            "Geringe Auswirkung — Nutzer können die Website grundsätzlich verwenden."
        };
        let legal_impact = if dist.critical > 0 {
            if en {
                "WCAG Level A violations detected automatically — manual review required for a defensible BFSG classification."
            } else {
                "WCAG-Level-A-Verstöße automatisiert erkannt — für belastbare BFSG-Einordnung ist manuelle Prüfung nötig."
            }
        } else if en {
            "No critical violations detected automatically — manual review recommended for full classification."
        } else {
            "Automatisiert keine kritischen Verstöße erkannt — manuelle Prüfung für vollständige Einordnung empfohlen."
        };

        let (user_label, business_label, risk_label) = if en {
            ("User", "Business", "Risk")
        } else {
            ("Nutzer", "Business", "Risiko")
        };
        let mut impact_kv = KeyValueList::new().with_title(i18n.t("narrative-impact-title"));
        impact_kv = impact_kv
            .add(user_label, user_impact)
            .add(business_label, business_impact)
            .add(risk_label, legal_impact);
        builder = builder.add_component(impact_kv);
    }

    // Block 3: Handlungsempfehlung
    {
        let actions = build_batch_quick_actions(&pres, &i18n);
        if !actions.is_empty() {
            let rows: Vec<ChecklistRow> = actions
                .iter()
                .map(|action| ChecklistRow::new(action, "").with_status("warn"))
                .collect();
            builder = builder.add_component(
                ChecklistPanel::new(rows).with_title(i18n.t("narrative-quick-actions-title")),
            );
        }
    }

    // Module overview
    if !pres.portfolio_summary.module_averages.is_empty() {
        let mut module_kv = KeyValueList::new().with_title(i18n.t("batch-panel-module-averages"));
        for (name, score) in &pres.portfolio_summary.module_averages {
            module_kv = module_kv.add(name, format!("{}/100", score));
        }
        builder = builder.add_component(module_kv);
    }

    // ── 2. URL-Ranking ──────────────────────────────────────────────
    let rows: Vec<BenchmarkRow> = pres
        .url_ranking
        .iter()
        .enumerate()
        .map(|(i, u)| {
            let mut row = BenchmarkRow::new(
                (i + 1) as u32,
                &truncate_url(&u.url, 35),
                u.overall_score,
                u.score as u32,
                u.critical_violations as u32,
            );
            if let Some(detail) = pres.url_details.iter().find(|detail| detail.url == u.url) {
                if let Some((_, score)) = detail
                    .module_scores
                    .iter()
                    .find(|(module, _)| module == "SEO")
                {
                    row = row.with_seo(*score);
                }
                if let Some((_, score)) = detail
                    .module_scores
                    .iter()
                    .find(|(module, _)| module == "Performance")
                {
                    row = row.with_performance(*score);
                }
                if let Some((_, score)) = detail
                    .module_scores
                    .iter()
                    .find(|(module, _)| module == "Security")
                {
                    row = row.with_security(*score);
                }
            }
            row
        })
        .collect();

    let (ranking_title, ranking_intro) = if i18n.locale() == "en" {
        (
            "URL ranking",
            "All audited URLs, sorted by score. Lower-scoring URLs need attention first.",
        )
    } else {
        (
            "URL-Ranking",
            "Übersicht aller geprüften URLs, sortiert nach Score. \
             URLs mit niedrigerem Score haben höheren Handlungsbedarf.",
        )
    };
    builder = builder
        .add_component(SectionHeaderSplit::new(ranking_title, ranking_intro).with_level(1))
        .add_component(BenchmarkTable::new(rows));

    // ── 3. Top-Probleme (vereinheitlicht) ─────────────────────────
    let en_top = i18n.locale() == "en";
    let top_intro = if en_top {
        "The following problem groups occur across multiple URLs. \
         Fixing them yields the largest improvement because they affect many pages simultaneously."
    } else {
        "Die folgenden Problemgruppen treten über mehrere URLs hinweg auf. \
         Durch Behebung dieser Probleme wird die größte Verbesserung erzielt, \
         da sie viele Seiten gleichzeitig betreffen."
    };
    builder = builder.add_component(
        SectionHeaderSplit::new(i18n.t("batch-section-most-frequent"), top_intro).with_level(1),
    );

    // Übersichtstabelle mit Aufwand
    if !pres.issue_frequency.is_empty() {
        let affected_col = if en_top {
            "Affected URLs"
        } else {
            "Betr. URLs"
        };
        let mut freq_table = AuditTable::new(vec![
            TableColumn::new(i18n.t("batch-col-problem")),
            TableColumn::new("WCAG"),
            TableColumn::new(i18n.t("batch-col-occurrences")),
            TableColumn::new(affected_col),
            TableColumn::new(i18n.t("batch-col-priority")),
        ])
        .with_title(i18n.t("batch-section-most-frequent-violations"));

        for issue in &pres.issue_frequency {
            freq_table = freq_table.add_row(vec![
                issue.problem.clone(),
                issue.wcag.clone(),
                issue.occurrences.to_string(),
                issue.affected_urls.to_string(),
                super::helpers::priority_label_i18n(issue.priority, &i18n),
            ]);
        }
        builder = builder.add_component(freq_table);
    }

    // Unified problem blocks — 1 Problem = 1 kompakter Block
    // (keine doppelten Cards + Details mehr)
    let scope_global_word = if en_top {
        "Global — affects all pages"
    } else {
        "Global — betrifft alle Seiten"
    };
    let scope_individual = if en_top {
        "Specific pages — isolated content"
    } else {
        "Einzelne Seiten — isolierter Inhalt"
    };
    let occurrences_word_top = if en_top { "occurrences" } else { "Vorkommen" };
    let affected_urls_word = if en_top {
        "affected URLs"
    } else {
        "betroffene URLs"
    };
    let effort_word = if en_top { "Effort" } else { "Aufwand" };
    let scope_word = if en_top { "Scope" } else { "Reichweite" };
    let impact_user_label = if en_top {
        "Impact (user)"
    } else {
        "Auswirkung (Nutzer)"
    };
    let impact_business_label = if en_top {
        "Impact (business)"
    } else {
        "Auswirkung (Business)"
    };
    let fix_label = if en_top { "Fix" } else { "Empfehlung" };
    let meta_label = if en_top { "Meta" } else { "Einordnung" };

    for group in pres.top_issues.iter().take(5) {
        let scope = if group.affected_urls.len() >= pres.portfolio_summary.total_urls {
            scope_global_word
        } else {
            scope_individual
        };
        let effort_label = group.effort.label();
        let meta_line = format!(
            "{} {} · {} {} · {}: {} · {}: {}",
            group.occurrence_count,
            occurrences_word_top,
            group.affected_urls.len(),
            affected_urls_word,
            effort_word,
            effort_label,
            scope_word,
            scope
        );

        let mut kv = KeyValueList::new()
            .with_title(&group.title)
            .add(
                i18n.t("findings-card-key-problem"),
                &group.customer_description,
            )
            .add(impact_user_label, &group.user_impact)
            .add(impact_business_label, &group.business_impact);
        if !group.typical_cause.is_empty() {
            kv = kv.add(i18n.t("findings-card-key-cause"), &group.typical_cause);
        }
        if !group.recommendation.is_empty() {
            kv = kv.add(fix_label, &group.recommendation);
        }
        kv = kv.add(meta_label, meta_line);
        builder = builder.add_component(kv);
    }

    // ── 4. Maßnahmenplan (mit Aufwand + Scope) ─────────────────────
    let action_intro = if en_top {
        "The following actions are prioritized by effort and impact. \
         Actions that improve many pages simultaneously take precedence."
    } else {
        "Die folgenden Maßnahmen sind nach Aufwand und Wirkung priorisiert. \
         Maßnahmen, die viele Seiten gleichzeitig verbessern, haben Vorrang."
    };
    builder = builder.add_component(
        SectionHeaderSplit::new(i18n.t("batch-action-plan-title"), action_intro).with_level(1),
    );
    builder = render_batch_action_plan_enhanced(builder, &pres.action_plan, &i18n);

    // ── 5a. Render Blocking (Batch) ─────────────────────────────────
    if !pres.portfolio_summary.render_blocking_summary.is_empty() {
        let en_rb = i18n.locale() == "en";
        let (rb_section, rb_kv_title, rb_intro) = if en_rb {
            (
                "Render blocking & assets",
                "Render-blocking overview (domain-wide)",
                "Render-blocking resources and third-party traffic, aggregated across all audited pages.",
            )
        } else {
            (
                "Render-Blocking & Assets",
                "Render-Blocking-Übersicht (domainweit)",
                "Render-blockierende Ressourcen und Third-Party-Traffic, aggregiert über alle geprüften Seiten.",
            )
        };
        let mut kv = KeyValueList::new().with_title(rb_kv_title);
        for (label, value) in &pres.portfolio_summary.render_blocking_summary {
            kv = kv.add(label, value);
        }
        builder = builder
            .add_component(Section::new(rb_section).with_level(1))
            .add_component(TextBlock::new(rb_intro))
            .add_component(kv);
    }

    // ── 5b. Performance Budgets (Batch) ─────────────────────────────
    let en_pdf = i18n.locale() == "en";
    if !pres.portfolio_summary.budget_summary.is_empty() {
        let pages_col = if en_pdf {
            "Affected pages"
        } else {
            "Betr. Seiten"
        };
        let budget_table_title = if en_pdf {
            "Performance budget violations (domain-wide)"
        } else {
            "Performance-Budget-Verstöße (domainweit)"
        };
        let mut table = AuditTable::new(vec![
            TableColumn::new(i18n.t("batch-col-metric")),
            TableColumn::new(i18n.t("batch-col-budget")),
            TableColumn::new(pages_col),
            TableColumn::new(i18n.t("batch-col-severity")),
        ])
        .with_title(budget_table_title);
        for (metric, budget, count, sev) in &pres.portfolio_summary.budget_summary {
            table = table.add_row(vec![
                metric.clone(),
                budget.clone(),
                count.to_string(),
                sev.clone(),
            ]);
        }
        let budgets_intro = if en_pdf {
            "On how many pages each performance budget was exceeded."
        } else {
            "Auf wie vielen Seiten welche Performance-Budgets überschritten wurden."
        };
        builder = builder
            .add_component(Section::new(i18n.t("batch-section-performance-budgets")).with_level(1))
            .add_component(TextBlock::new(budgets_intro))
            .add_component(table);
    }

    // ── 5. Technische URL-Matrix ───────────────────────────────────
    builder = builder.add_component(
        SectionHeaderSplit::new(
            i18n.t("batch-section-tech-url-matrix"),
            i18n.t("batch-section-tech-url-matrix-intro"),
        )
        .with_level(1),
    );

    if let Some(ref crawl_links) = pres.portfolio_summary.crawl_links {
        let target_col = if en_pdf { "Target" } else { "Ziel" };
        let type_col = if en_pdf { "Type" } else { "Typ" };
        let direct_label = if en_pdf { "direct" } else { "direkt" };
        let hops_label = if en_pdf { "hops" } else { "Hops" };
        let internal_intro = if en_pdf {
            format!(
                "For the crawl starting at {} we checked {} internal link targets. {} broken internal links detected.",
                crawl_links.seed_url,
                crawl_links.checked_internal_links,
                crawl_links.broken_internal_links.len()
            )
        } else {
            format!(
                "Für den Crawl ab {} wurden {} interne Linkziele geprüft. {} kaputte interne Verlinkungen wurden erkannt.",
                crawl_links.seed_url,
                crawl_links.checked_internal_links,
                crawl_links.broken_internal_links.len()
            )
        };
        builder = builder
            .add_component(
                Section::new(i18n.t("batch-section-broken-links-internal")).with_level(1),
            )
            .add_component(TextBlock::new(internal_intro));

        if crawl_links.broken_internal_links.is_empty() {
            builder = builder.add_component(Callout::info(if en_pdf {
                "No broken internal links detected in the audited crawl set."
            } else {
                "Keine kaputten internen Links im geprüften Crawl-Set erkannt."
            }));
        } else {
            let mut table = AuditTable::new(vec![
                TableColumn::new(i18n.t("batch-col-source")),
                TableColumn::new(target_col),
                TableColumn::new(i18n.t("batch-col-status-code")),
                TableColumn::new(type_col),
            ])
            .with_title(i18n.t("batch-table-broken-internal"));

            for row in &crawl_links.broken_internal_links {
                let severity_color = match row.severity.as_str() {
                    "high" => "#dc2626",
                    "medium" => "#ea580c",
                    _ => "#ca8a04",
                };
                let typ_label = if row.redirect_hops > 0 {
                    format!("→{} {}", row.redirect_hops, hops_label)
                } else {
                    direct_label.to_string()
                };
                table = table.add_row(vec![
                    truncate_url(&row.source_url, 30),
                    truncate_url(&row.target_url, 38),
                    format!("\x1b[{}m{}\x1b[0m", severity_color, row.status),
                    typ_label,
                ]);
            }

            builder = builder.add_component(table);
        }

        // External broken links
        if !crawl_links.broken_external_links.is_empty() {
            let ext_intro = if en_pdf {
                format!(
                    "{} external link targets checked. {} broken external links detected.",
                    crawl_links.checked_external_links,
                    crawl_links.broken_external_links.len()
                )
            } else {
                format!(
                    "{} externe Linkziele geprüft. {} kaputte externe Verlinkungen erkannt.",
                    crawl_links.checked_external_links,
                    crawl_links.broken_external_links.len()
                )
            };
            builder = builder
                .add_component(
                    Section::new(i18n.t("batch-section-broken-links-external")).with_level(2),
                )
                .add_component(TextBlock::new(ext_intro));

            let mut ext_table = AuditTable::new(vec![
                TableColumn::new(i18n.t("batch-col-source")),
                TableColumn::new(target_col),
                TableColumn::new(i18n.t("batch-col-status-code")),
                TableColumn::new(type_col),
            ])
            .with_title(i18n.t("batch-table-broken-external"));

            for row in &crawl_links.broken_external_links {
                let typ_label = if row.redirect_hops > 0 {
                    format!("→{} {}", row.redirect_hops, hops_label)
                } else {
                    direct_label.to_string()
                };
                ext_table = ext_table.add_row(vec![
                    truncate_url(&row.source_url, 30),
                    truncate_url(&row.target_url, 38),
                    row.status.clone(),
                    typ_label,
                ]);
            }

            builder = builder.add_component(ext_table);
        } else if crawl_links.checked_external_links > 0 {
            let ext_clean_msg = if en_pdf {
                format!(
                    "{} external link targets checked — no broken external links detected.",
                    crawl_links.checked_external_links
                )
            } else {
                format!(
                    "{} externe Linkziele geprüft — keine kaputten externen Links erkannt.",
                    crawl_links.checked_external_links
                )
            };
            builder = builder
                .add_component(Section::new(i18n.t("batch-section-external-links")).with_level(2))
                .add_component(Callout::info(ext_clean_msg));
        }

        // Redirect chains
        if !crawl_links.redirect_chains.is_empty() {
            let chain_intro = if en_pdf {
                format!(
                    "{} links with more than one redirect hop detected.",
                    crawl_links.redirect_chains.len()
                )
            } else {
                format!(
                    "{} Links mit mehr als einem Redirect-Hop erkannt.",
                    crawl_links.redirect_chains.len()
                )
            };
            builder = builder
                .add_component(Section::new(i18n.t("batch-section-redirect-chains")).with_level(2))
                .add_component(TextBlock::new(chain_intro));

            let mut chain_table = AuditTable::new(vec![
                TableColumn::new(i18n.t("batch-col-source")),
                TableColumn::new(if en_pdf { "Target" } else { "Ziel" }),
                TableColumn::new("Hops"),
                TableColumn::new(if en_pdf { "Final URL" } else { "Final-URL" }),
            ])
            .with_title(if en_pdf {
                "Redirect chains (> 1 hop)"
            } else {
                "Redirect-Ketten (> 1 Hop)"
            });

            for chain in &crawl_links.redirect_chains {
                chain_table = chain_table.add_row(vec![
                    truncate_url(&chain.source_url, 28),
                    truncate_url(&chain.target_url, 28),
                    chain.hops.to_string(),
                    truncate_url(&chain.final_url, 32),
                ]);
            }

            builder = builder.add_component(chain_table);
        }
    }

    let page_col = if en_pdf { "Page" } else { "Seite" };
    let title_col = if en_pdf { "Title" } else { "Titel" };
    let mut matrix = AuditTable::new(vec![
        TableColumn::new("#").with_width("4%"),
        TableColumn::new(page_col).with_width("26%"),
        TableColumn::new(title_col).with_width("28%"),
        TableColumn::new(i18n.t("batch-col-links-to")).with_width("10%"),
        TableColumn::new(i18n.t("batch-col-links-from")).with_width("10%"),
        TableColumn::new(i18n.t("batch-col-words")).with_width("10%"),
        TableColumn::new("Score").with_width("12%"),
    ])
    .with_title(i18n.t("batch-table-pages-overview"));

    for row in &pres.url_matrix {
        let score_str = pres
            .url_details
            .iter()
            .find(|d| d.url == row.url)
            .map(|d| format!("{}/100", d.score.round() as u32))
            .unwrap_or_else(|| "—".to_string());
        matrix = matrix.add_row(vec![
            row.rank.to_string(),
            truncate_url(&row.url, 34),
            row.title
                .as_deref()
                .map(|t| truncate_url(t, 36))
                .unwrap_or_else(|| "—".to_string()),
            row.inbound_links.to_string(),
            row.outbound_links.to_string(),
            super::format_word_count(row.word_count),
            score_str,
        ]);
    }
    builder = builder.add_component(matrix);

    if config.level != ReportLevel::Executive {
        let mut focus_table = AuditTable::new(vec![
            TableColumn::new("URL"),
            TableColumn::new(i18n.t("batch-col-page-type")),
            TableColumn::new(i18n.t("batch-col-attributes")),
            TableColumn::new(i18n.t("batch-col-top-issues")),
        ])
        .with_title(i18n.t("batch-table-focus-pages"));

        for detail in pres.url_details.iter().take(10) {
            focus_table = focus_table.add_row(vec![
                truncate_url(&detail.url, 38),
                detail.page_type.clone().unwrap_or_else(|| "—".to_string()),
                if detail.page_attributes.is_empty() {
                    "—".to_string()
                } else {
                    truncate_url(&detail.page_attributes.join(", "), 40)
                },
                if detail.top_issues.is_empty() {
                    "—".to_string()
                } else {
                    truncate_url(&detail.top_issues.join(", "), 52)
                },
            ]);
        }
        builder = builder.add_component(focus_table);
    }

    // ── 6. Content & SEO — integriert mit Business-Impact ─────────
    let en_batch = i18n.locale() == "en";
    let (content_seo_title, content_seo_intro) = if en_batch {
        (
            "Content & SEO potential",
            "Content strengths and weaknesses with direct relevance to rankings, visibility and conversion. \
             Each finding is tied to a concrete action.",
        )
    } else {
        (
            "Content & SEO-Potenzial",
            "Content-Stärken und -Schwächen mit direktem Bezug zu Rankings, Sichtbarkeit und Conversion. \
             Jede Auffälligkeit ist an eine konkrete Handlung geknüpft.",
        )
    };
    builder = builder
        .add_component(SectionHeaderSplit::new(content_seo_title, content_seo_intro).with_level(1));

    // Schwache Seiten zuerst — mit Business-Impact
    if !pres.portfolio_summary.weakest_content_pages.is_empty() {
        let issues_title = if en_batch {
            "Content issues needing action"
        } else {
            "Content-Probleme mit Handlungsbedarf"
        };
        let high_marker = if en_batch { "high" } else { "hoch" };
        let mut issues_kv = KeyValueList::new().with_title(issues_title);
        for (url, page_type, score) in &pres.portfolio_summary.weakest_content_pages {
            let relevance = super::business_relevance(Some(page_type.as_str()), url, i18n.locale());
            let impact = if relevance == high_marker {
                if en_batch {
                    "Likely ranking loss + lower conversion"
                } else {
                    "Rankingverlust + geringere Conversion wahrscheinlich"
                }
            } else if *score < 30 {
                if en_batch {
                    "Weak organic visibility"
                } else {
                    "Schwache organische Sichtbarkeit"
                }
            } else if en_batch {
                "Optimization potential for SEO"
            } else {
                "Optimierungspotenzial für SEO"
            };
            let value = if en_batch {
                format!(
                    "{} — {} → +300–800 words of structured content recommended",
                    page_type, impact
                )
            } else {
                format!(
                    "{} — {} → +300–800 Wörter strukturierter Inhalt empfohlen",
                    page_type, impact
                )
            };
            let key_str = if en_batch {
                format!("{} (profile: {}/100)", truncate_url(url, 35), score)
            } else {
                format!("{} (Profil: {}/100)", truncate_url(url, 35), score)
            };
            issues_kv = issues_kv.add(key_str, value);
        }
        builder = builder.add_component(issues_kv);
    }

    // Content-Auffälligkeiten als Business-Relevanz
    if !pres.portfolio_summary.distribution_insights.is_empty() {
        let action_label = if en_batch {
            "Action needed"
        } else {
            "Handlungsbedarf"
        };
        let panel_title = if en_batch {
            "Content patterns → business impact"
        } else {
            "Content-Auffälligkeiten → Business-Impact"
        };
        let rows: Vec<ChecklistRow> = pres
            .portfolio_summary
            .distribution_insights
            .iter()
            .map(|insight| {
                let impact = if insight.contains("Thin") || insight.contains("dünn") {
                    if en_batch {
                        format!("{} → weaker rankings, lower dwell time", insight)
                    } else {
                        format!("{} → schwächere Rankings, geringere Verweildauer", insight)
                    }
                } else if insight.contains("Duplikat") || insight.contains("duplicate") {
                    if en_batch {
                        format!(
                            "{} → keyword cannibalization, split ranking signals",
                            insight
                        )
                    } else {
                        format!(
                            "{} → Keyword-Kannibalisierung, Split der Ranking-Signale",
                            insight
                        )
                    }
                } else {
                    insight.clone()
                };
                ChecklistRow::new(action_label, &impact).with_status("warn")
            })
            .collect();
        builder = builder.add_component(ChecklistPanel::new(rows).with_title(panel_title));
    }

    // Near-duplicates mit Business-Kontext
    if !pres.portfolio_summary.near_duplicates.is_empty() {
        let near_dup_title = if en_batch {
            "Near-duplicate content → keyword cannibalization"
        } else {
            "Near-Duplicate-Content → Keyword-Kannibalisierung"
        };
        let mut table = AuditTable::new(vec![
            TableColumn::new(i18n.t("batch-col-page-a")),
            TableColumn::new(i18n.t("batch-col-page-b")),
            TableColumn::new(i18n.t("batch-col-similarity")),
            TableColumn::new(i18n.t("batch-col-risk")),
        ])
        .with_title(near_dup_title);

        for (url_a, url_b, sim) in &pres.portfolio_summary.near_duplicates {
            let risk = if *sim >= 95 {
                if en_batch {
                    "High — consolidate"
                } else {
                    "Hoch — konsolidieren"
                }
            } else if en_batch {
                "Medium — differentiate"
            } else {
                "Mittel — differenzieren"
            };
            table = table.add_row(vec![
                truncate_url(url_a, 35),
                truncate_url(url_b, 35),
                format!("{sim}%"),
                risk.to_string(),
            ]);
        }
        builder = builder.add_component(table);
    }

    // Seitentyp-Verteilung (kompakt)
    if !pres.portfolio_summary.page_type_distribution.is_empty() {
        let high_label = if en_batch { "high" } else { "hoch" };
        let medium_label = if en_batch { "medium" } else { "mittel" };
        let low_label = if en_batch { "low" } else { "niedrig" };
        let mut type_table = AuditTable::new(vec![
            TableColumn::new(i18n.t("batch-col-page-type")),
            TableColumn::new(i18n.t("batch-col-pages-list")),
            TableColumn::new(i18n.t("batch-col-share")),
            TableColumn::new(i18n.t("batch-col-relevance")),
        ])
        .with_title(i18n.t("batch-table-page-type-distribution"));

        for (label, count, pct) in &pres.portfolio_summary.page_type_distribution {
            let relevance = match label.as_str() {
                "Marketing / Landing Page"
                | "Transaktional / Utility"
                | "Transactional / Utility" => high_label,
                "Editorial / Artikel"
                | "Editorial / Article"
                | "Strukturierter Wissensinhalt"
                | "Structured knowledge content" => medium_label,
                "Thin / Minimal Content" => low_label,
                _ => medium_label,
            };
            type_table = type_table.add_row(vec![
                label.clone(),
                count.to_string(),
                format!("{pct}%"),
                relevance.to_string(),
            ]);
        }
        builder = builder.add_component(type_table);
    }

    // Schema-Typ-Verteilung
    if !pres.portfolio_summary.schema_distribution.is_empty() {
        let total = pres.portfolio_summary.total_urls;
        let without = pres.portfolio_summary.pages_without_schema;
        let summary = if without == 0 {
            if en_batch {
                format!("All {} pages have structured data.", total)
            } else {
                format!("Alle {} Seiten haben strukturierte Daten.", total)
            }
        } else if en_batch {
            format!("{} of {} pages without structured data.", without, total)
        } else {
            format!("{} von {} Seiten ohne strukturierte Daten.", without, total)
        };
        let schema_callout_title = if en_batch {
            "Structured data (Schema.org)"
        } else {
            "Strukturierte Daten (Schema.org)"
        };
        builder = builder.add_component(Callout::info(&summary).with_title(schema_callout_title));
        let mut schema_table = AuditTable::new(vec![
            TableColumn::new(i18n.t("batch-col-schema-type")).with_width("55%"),
            TableColumn::new(i18n.t("batch-col-pages-list")).with_width("20%"),
            TableColumn::new(i18n.t("batch-col-share")).with_width("25%"),
        ])
        .with_title(i18n.t("batch-table-schema-distribution"));
        for (schema_type, count) in &pres.portfolio_summary.schema_distribution {
            let pct = (*count * 100).checked_div(total).unwrap_or(0);
            schema_table = schema_table.add_row(vec![
                schema_type.clone(),
                count.to_string(),
                format!("{pct}%"),
            ]);
        }
        builder = builder.add_component(schema_table);
    }

    // Stärkste Seiten (kurz)
    if !pres.portfolio_summary.strongest_content_pages.is_empty() {
        let mut strengths = AuditTable::new(vec![
            TableColumn::new("URL"),
            TableColumn::new(i18n.t("batch-col-page-type")),
            TableColumn::new(i18n.t("batch-col-profile")),
        ])
        .with_title(i18n.t("batch-table-top-pages"));

        for (url, page_type, score) in &pres.portfolio_summary.strongest_content_pages {
            strengths = strengths.add_row(vec![
                truncate_url(url, 42),
                page_type.clone(),
                format!("{score}/100"),
            ]);
        }
        builder = builder.add_component(strengths);
    }

    // ── Cross-page consistency (issues #44/#45/#46) ─────────────────
    if let Some(ref consistency) = batch.consistency {
        builder = render_batch_consistency(builder, consistency, &i18n);
    }

    // ── Empfohlene nächste Schritte ───────────────────────────────
    builder = render_next_steps_batch(builder, &pres, &i18n);

    // ── 7. Anhang ───────────────────────────────────────────────────
    if config.level == ReportLevel::Technical && !pres.appendix.per_url.is_empty() {
        let appendix_intro = if en_pdf {
            "Complete listing of all detected violations per URL with technical details for implementation."
        } else {
            "Vollständige Auflistung aller erkannten Verstöße pro URL \
             mit technischen Details für die Umsetzung."
        };
        builder = builder.add_component(
            SectionHeaderSplit::new(i18n.t("section-appendix"), appendix_intro).with_level(1),
        );

        let rule_col = if en_pdf { "Rule" } else { "Regel" };
        let elements_col = if en_pdf {
            "Affected elements"
        } else {
            "Betr. Elemente"
        };
        for url_appendix in &pres.appendix.per_url {
            if url_appendix.violations.is_empty() {
                continue;
            }

            builder = builder
                .add_component(Section::new(truncate_url(&url_appendix.url, 70)).with_level(2));

            let mut table = AuditTable::new(vec![
                TableColumn::new(rule_col),
                TableColumn::new(i18n.t("batch-col-severity")),
                TableColumn::new(i18n.t("batch-col-description")),
                TableColumn::new(elements_col),
            ]);

            for v in &url_appendix.violations {
                let elements = v
                    .affected_elements
                    .iter()
                    .map(|e| e.selector.clone())
                    .collect::<Vec<_>>()
                    .join("; ");
                table = table.add_row(vec![
                    format!(
                        "{} — {} ({}×)",
                        v.rule,
                        v.rule_name,
                        v.affected_elements.len()
                    ),
                    severity_label_i18n(v.severity, &i18n),
                    v.message.clone(),
                    elements,
                ]);
            }
            builder = builder.add_component(table);
        }
    }

    let built_report = builder.build();
    Ok((engine, built_report))
}