auditmysite 1.7.3

Resource-efficient WCAG 2.2 AA 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
//! Finding renderers for PDF reports.

use crate::output::localized::is_english;
use renderreport::components::advanced::{
    Divider, KeyValueList, List, MetricStrip, MetricStripItem, WrongRightBlock,
};
use renderreport::components::text::Label;
use renderreport::prelude::*;

use crate::i18n::I18n;
use crate::output::report_model::*;
use crate::util::truncate_url;
use crate::wcag::Evidence;

use super::helpers::{
    effort_label_i18n, manual_recheck_instruction, priority_label_i18n, role_label_i18n,
};

/// Extract the first sentence from a text (up to first period + space, or full text).
/// Skips common German abbreviations like "z. B.", "d. h.", "u. a.".
/// Compact an HTML/selector evidence string for table cells: collapse
/// whitespace and replace `data:` URI bodies (huge unbreakable tokens that blow
/// up row heights) with `data:…`, then length-truncate. Keeps the meaningful
/// markup (tag, classes) while dropping the inline-asset noise.
pub(super) fn compact_html(s: &str, max: usize) -> String {
    let collapsed = s.split_whitespace().collect::<Vec<_>>().join(" ");
    let mut result = String::with_capacity(collapsed.len());
    let mut rest = collapsed.as_str();
    while let Some(pos) = rest.find("data:") {
        result.push_str(&rest[..pos]);
        result.push_str("data:…");
        rest = &rest[pos + "data:".len()..];
        // Skip the URI body up to the closing attribute quote.
        if let Some(q) = rest.find(['"', '\'']) {
            rest = &rest[q..];
        } else {
            rest = "";
        }
    }
    result.push_str(rest);
    truncate_url(&result, max)
}

pub(super) fn first_sentence(text: &str) -> &str {
    let mut search_from = 0;
    while let Some(rel) = text[search_from..].find(". ") {
        let pos = search_from + rel;
        // Check for single-letter abbreviation pattern: " X. " (e.g. "z. B.", "d. h.")
        if pos >= 2 {
            let bytes = text.as_bytes();
            let b0 = bytes[pos - 2];
            let b1 = bytes[pos - 1];
            if b0 == b' ' && b1.is_ascii_alphabetic() {
                search_from = pos + 2;
                continue;
            }
        }
        return &text[..pos + 1];
    }
    text
}

#[cfg(test)]
fn customer_perspective_title(group: &FindingGroup, en: bool) -> &'static str {
    let rule = group.rule_id.as_str();
    let dimension = group.dimension.as_deref().unwrap_or_default();
    let subcategory = group.subcategory.as_deref().unwrap_or_default();
    let haystack = format!(
        "{} {} {} {}",
        rule,
        dimension,
        subcategory,
        group.title.to_lowercase()
    );

    if haystack.contains("name_role")
        || haystack.contains("focus")
        || haystack.contains("keyboard")
        || haystack.contains("button")
        || haystack.contains("link_purpose")
        || haystack.contains("target")
        || haystack.contains("form")
    {
        if en {
            "Operability"
        } else {
            "Bedienbarkeit"
        }
    } else if haystack.contains("structure")
        || haystack.contains("heading")
        || haystack.contains("landmark")
        || haystack.contains("region")
        || haystack.contains("bypass")
        || haystack.contains("parsing")
        || haystack.contains("semant")
    {
        if en {
            "Orientation and structure"
        } else {
            "Orientierung und Struktur"
        }
    } else if haystack.contains("contrast")
        || haystack.contains("color")
        || haystack.contains("image")
        || haystack.contains("alt")
        || haystack.contains("visibility")
    {
        if en {
            "Perception and readability"
        } else {
            "Wahrnehmbarkeit und Lesbarkeit"
        }
    } else if dimension == "SEO"
        || haystack.contains("seo")
        || haystack.contains("schema")
        || haystack.contains("meta")
        || haystack.contains("ai")
    {
        if en {
            "Discoverability and AI understanding"
        } else {
            "Auffindbarkeit und KI-Verständnis"
        }
    } else if dimension == "Security" || haystack.contains("security") {
        if en {
            "Trust and technical quality"
        } else {
            "Vertrauen und technische Qualität"
        }
    } else if dimension == "Performance" || dimension == "Mobile" {
        if en {
            "Loading and mobile experience"
        } else {
            "Lade- und Mobile-Erlebnis"
        }
    } else if en {
        "Customer impact"
    } else {
        "Kundenauswirkung"
    }
}

/// Label for the "BFSG/EAA relevance" meta row. Both acronyms are spelled out
/// once, at their first appearance in the report, then abbreviated on every
/// later card — readers who start at Chapter 02's first finding get the
/// expansion, later cards stay compact (Rule B, plain-language report plan).
fn bfsg_eaa_label(i18n: &I18n, acronyms_expanded: &mut bool) -> &'static str {
    let en = is_english(i18n);
    if !*acronyms_expanded {
        *acronyms_expanded = true;
        return if en {
            "BFSG/EAA relevance (German Accessibility Strengthening Act / European Accessibility Act)"
        } else {
            "BFSG-/EAA-Relevanz (Barrierefreiheitsstärkungsgesetz / European Accessibility Act)"
        };
    }
    if en {
        "BFSG/EAA relevance"
    } else {
        "BFSG-/EAA-Relevanz"
    }
}

fn report_code_label(value: &str, i18n: &I18n) -> &'static str {
    let en = is_english(i18n);
    match (value, en) {
        ("very_high", true) => "Very high",
        ("very_high", false) => "Sehr hoch",
        ("high", true) => "High",
        ("high", false) => "Hoch",
        ("medium", true) => "Medium",
        ("medium", false) => "Mittel",
        ("low", true) => "Low",
        ("low", false) => "Niedrig",
        ("very_low", true) => "Very low",
        ("very_low", false) => "Sehr niedrig",
        ("immediate", true) => "Immediate",
        ("immediate", false) => "Sofort",
        ("quick_win", true) => "Quick win",
        ("quick_win", false) => "Quick Win",
        ("normal", true) => "Normal",
        ("normal", false) => "Normal",
        ("manual_review_recommended", true) => "Manual review recommended",
        ("manual_review_recommended", false) => "Manuelle Prüfung empfohlen",
        ("automatically_confirmed", true) => "Automatically confirmed",
        ("automatically_confirmed", false) => "Automatisch bestätigt",
        _ => "n/a",
    }
}

/// Small tracked-caps section caption inside a finding card — the same
/// visual language as the report's chapter eyebrows, scaled down. Used to
/// separate the finding card's secondary blocks (QA metadata, action
/// assessment) from each other without wrapping each one in its own frame.
fn section_caption(text: &str) -> Label {
    Label::new(text.to_uppercase())
        .bold()
        .with_size("8.5pt")
        .with_color(super::design::tokens::NEUTRAL)
}

/// Find a specific `computed`/`ax_tree` evidence value by field name.
fn evidence_value<'a>(evidence: &'a [Evidence], source: &str, field: &str) -> Option<&'a str> {
    evidence
        .iter()
        .find(|e| e.source == source && e.field.as_deref() == Some(field))
        .and_then(|e| e.value.as_deref())
        .filter(|v| !v.is_empty())
}

/// "Contrast 2.70:1 (required 4.5:1)" — combines the contrast rule's
/// `computed` evidence into one localized measured-value line. `None` when
/// the occurrence carries no computed contrast evidence (i.e. every rule
/// other than 1.4.3).
fn contrast_measured_text(evidence: &[Evidence], en: bool) -> Option<String> {
    let ratio = evidence_value(evidence, "computed", "contrast_ratio")?;
    let required = evidence_value(evidence, "computed", "required_ratio");
    Some(match (required, en) {
        (Some(req), true) => format!("Contrast {} (required {})", ratio, req),
        (Some(req), false) => format!("Kontrast {} (erforderlich {})", ratio, req),
        (None, true) => format!("Contrast {}", ratio),
        (None, false) => format!("Kontrast {}", ratio),
    })
}

pub(super) fn render_finding_technical(
    mut builder: renderreport::engine::ReportBuilder,
    group: &FindingGroup,
    i18n: &I18n,
    report_ts: i64,
    evidence_seq: &mut usize,
    acronyms_expanded: &mut bool,
) -> renderreport::engine::ReportBuilder {
    let en = is_english(i18n);
    let severity_prefix = match group.severity {
        crate::wcag::Severity::Critical => {
            if en {
                "[Critical] "
            } else {
                "[Kritisch] "
            }
        }
        crate::wcag::Severity::High => {
            if en {
                "[High] "
            } else {
                "[Hoch] "
            }
        }
        crate::wcag::Severity::Medium => {
            if en {
                "[Medium] "
            } else {
                "[Mittel] "
            }
        }
        crate::wcag::Severity::Low => {
            if en {
                "[Low] "
            } else {
                "[Gering] "
            }
        }
    };
    let color = super::design::severity_color(group.severity);

    let header = if !group.wcag_criterion.is_empty() {
        // Flag criteria WCAG 2.2 added (e.g. 2.5.8) inline — they are inside
        // this report's audit-scope ratio but outside EN 301 549 V3.2.1, which
        // the BFSG references and which is built on WCAG 2.1. A finding tagged
        // just "AA" would misrepresent that (#572, plan 54 §1).
        let wcag22_suffix = if crate::wcag::coverage::is_wcag22_only(&group.wcag_criterion) {
            ", WCAG 2.2"
        } else {
            ""
        };
        format!(
            "{}{} — WCAG {} ({}{})",
            severity_prefix, group.title, group.wcag_criterion, group.wcag_level, wcag22_suffix
        )
    } else if group.title.is_empty() {
        // Raw internal rule ids (e.g. "seo.headings.multiple_h1") are never
        // customer-facing prose — only fall back to one when there's truly no
        // title to show at all, and even then, don't also glue it onto a
        // perfectly good title as an unexplained suffix (#QA-039 report review).
        format!("{}{}", severity_prefix, group.rule_id)
    } else {
        format!("{}{}", severity_prefix, group.title)
    };
    builder = builder.add_component(
        Label::new(&header)
            .bold()
            .with_size("14pt")
            .with_color(color),
    );

    // Plain-language lead-in: what this means and who it affects, in customer
    // language — shown BEFORE the QA-meta block so every reader sees impact
    // first, not detection-confidence/false-positive statistics (Rule A/B,
    // plain-language report plan). `customer_description`/`user_impact` are
    // already locale-correct here (#406 + the Rule-C fallback fix below).
    let mut lead_in = String::new();
    if !group.customer_description.is_empty() {
        lead_in.push_str(&group.customer_description);
    }
    if !group.user_impact.is_empty() {
        if !lead_in.is_empty() {
            lead_in.push(' ');
        }
        lead_in.push_str(&group.user_impact);
    }
    if !lead_in.is_empty() {
        builder = builder.add_component(Label::new(lead_in).with_size("10.5pt"));
    }

    // Primary tier: the four things a developer scans first (who/how urgent/
    // how much work), as a compact single-row strip instead of stacked
    // label:value lines — matches the severity-counter strip elsewhere.
    builder = builder.add_component(
        MetricStrip::new(vec![
            MetricStripItem::new(
                i18n.t("label-priority"),
                priority_label_i18n(group.priority, i18n),
            )
            .with_accent(color),
            MetricStripItem::new(
                i18n.t("label-owner"),
                role_label_i18n(group.responsible_role, i18n),
            )
            .with_accent(super::design::tokens::INK),
            MetricStripItem::new(
                i18n.t("label-effort"),
                effort_label_i18n(group.effort, i18n),
            )
            .with_accent(super::design::tokens::INK),
            MetricStripItem::new(
                if is_english(i18n) {
                    "Implementation priority"
                } else {
                    "Umsetzungspriorität"
                },
                report_code_label(&group.remediation_priority, i18n),
            )
            .with_accent(super::design::tokens::INK),
        ])
        .compact(),
    );

    // Secondary tier: audit-methodology metadata a developer doesn't need to
    // read on every finding — kept compact and visually subordinate (a small
    // caption, not a titled card) rather than continuing the primary strip's
    // weight.
    builder = builder.add_component(section_caption(if is_english(i18n) {
        "QA metadata"
    } else {
        "Prüfmetadaten"
    }));
    let mut meta_kv = KeyValueList::new()
        .add(
            if is_english(i18n) {
                "Detection confidence"
            } else {
                "Erkennungssicherheit"
            },
            report_code_label(&group.confidence, i18n),
        )
        .add(
            if is_english(i18n) {
                "False-positive risk"
            } else {
                "Falschpositiv-Risiko"
            },
            report_code_label(&group.false_positive_risk, i18n),
        )
        .add(
            bfsg_eaa_label(i18n, acronyms_expanded),
            report_code_label(&group.bfsg_relevance, i18n),
        )
        .add(
            i18n.t("finding-elements"),
            group.affected_elements.to_string(),
        )
        .add(
            i18n.t("finding-occurrences"),
            group.occurrence_count.to_string(),
        );
    if let Some(url) = group
        .help_url
        .as_deref()
        .map(str::trim)
        .filter(|u| !u.is_empty())
    {
        meta_kv = meta_kv.add(i18n.t("finding-reference"), url);
    }
    builder = builder.add_component(meta_kv);

    // `expected_impact`/`complexity_reason` are re-derived here from the
    // stable `..._kind` in the run language rather than printed from the
    // `FindingGroup` string fields verbatim — those stay canonical English
    // (mirroring the JSON), so printing them directly leaked raw English
    // prose into otherwise fully German reports (#406).
    let expected_impact =
        crate::audit::normalized::expected_impact_text(&group.expected_impact_kind, en);
    let complexity_reason = crate::audit::normalized::complexity_text(group.complexity_kind, en);
    let recheck_instruction = manual_recheck_instruction(&group.wcag_criterion, en);
    if !expected_impact.is_empty() || !complexity_reason.is_empty() || recheck_instruction.is_some()
    {
        builder = builder.add_component(section_caption(if is_english(i18n) {
            "Action assessment"
        } else {
            "Maßnahmenbewertung"
        }));
        let mut assessment = KeyValueList::new();
        if !expected_impact.is_empty() {
            assessment = assessment.add(
                if is_english(i18n) {
                    "Expected effect"
                } else {
                    "Erwartete Wirkung"
                },
                &expected_impact,
            );
        }
        if !complexity_reason.is_empty() {
            assessment = assessment.add(
                if is_english(i18n) {
                    "Complexity reason"
                } else {
                    "Komplexitätsgrund"
                },
                &complexity_reason,
            );
        }
        if group.verification == "manual_review_recommended" {
            assessment = assessment.add(
                if is_english(i18n) {
                    "Verification"
                } else {
                    "Prüfung"
                },
                if is_english(i18n) {
                    "Manual review recommended"
                } else {
                    "Manuelle Prüfung empfohlen"
                },
            );
        }
        if let Some(instruction) = recheck_instruction {
            assessment = assessment.add(
                if is_english(i18n) {
                    "Self-test"
                } else {
                    "Selbsttest"
                },
                instruction,
            );
        }
        builder = builder.add_component(assessment);
    }

    // Findings with no real DOM evidence (e.g. SEO heading findings, whose
    // `OccurrenceDetail` has no selector at all — see `aggregate_seo_findings`)
    // fall back to using the internal issue-type token as both `node_id` and
    // `selector`, which is how `build_location_hints`'s fallback resolves it.
    // Applying DOM-evidence components (element-type extraction, a "location"
    // table/snapshot, selector-pattern clustering) to that token produces
    // nonsense like "Element-Typen: 1× multiple" or "Fundstelle: multiple_h1" —
    // skip all of them when no occurrence actually has real location data.
    let has_real_location = group
        .representative_occurrences
        .iter()
        .any(|occ| occ.selector != occ.node_id);

    // AffectedElements: element-type summary + deduplicated selector list
    if has_real_location {
        // Count occurrences per element type
        let mut type_counts: std::collections::BTreeMap<&str, usize> =
            std::collections::BTreeMap::new();
        for occ in &group.representative_occurrences {
            let tag = extract_element_type(&occ.selector);
            if !tag.is_empty() {
                *type_counts.entry(tag).or_insert(0) += 1;
            }
        }
        if !type_counts.is_empty() {
            let summary = type_counts
                .iter()
                .map(|(tag, count)| format!("{}× {}", count, tag))
                .collect::<Vec<_>>()
                .join("  ·  ");
            builder = builder
                .add_component(KeyValueList::new().add(i18n.t("finding-element-types"), summary));
        }
    }

    if !group.recommendation.is_empty() {
        builder = builder.add_component(
            Callout::success(&group.recommendation).with_title(i18n.t("finding-recommendation")),
        );
    }

    for example in &group.examples {
        builder = builder.add_component(
            WrongRightBlock::new(&example.bad, &example.good)
                .code()
                .with_labels(i18n.t("finding-wrong"), i18n.t("finding-right")),
        );
        if let Some(ref dec) = example.decorative {
            builder =
                builder.add_component(Callout::info(dec).with_title(i18n.t("label-decorative")));
        }
    }

    if !group.affected_urls.is_empty() && group.affected_urls.len() <= 10 {
        let mut url_list = List::new().with_title(i18n.t("label-affected-urls"));
        for url in &group.affected_urls {
            url_list = url_list.add_item(truncate_url(url, 70));
        }
        builder = builder.add_component(url_list);
    }

    if has_real_location {
        let mut table = renderreport::components::AuditTable::new(vec![
            renderreport::components::TableColumn::new(i18n.t("finding-location"))
                .with_width("26%"),
            renderreport::components::TableColumn::new(i18n.t("finding-note")).with_width("74%"),
        ])
        .with_title(i18n.t("finding-representative-occurrences"));

        for occ in &group.representative_occurrences {
            table = table.add_row(vec![
                compact_html(&occ.selector, 48),
                first_sentence(&occ.message).to_string(),
            ]);
        }
        builder = builder.add_component(table);

        let en = is_english(i18n);
        let hidden = group.representative_occurrences.len().saturating_sub(3);
        for occ in group.representative_occurrences.iter().take(3) {
            let mut snapshot = SummaryBox::new(format!(
                "{}: {}",
                i18n.t("finding-occurrence"),
                compact_html(&occ.selector, 60)
            ))
            .add_item("Node", truncate_url(&occ.node_id, 75))
            .add_item(i18n.t("finding-note"), first_sentence(&occ.message));

            if let Some(html) = occ
                .html_snippet
                .as_deref()
                .map(str::trim)
                .filter(|value| !value.is_empty())
            {
                snapshot = snapshot.add_item("HTML", compact_html(html, 110));
            }

            if let Some(path) = evidence_value(&occ.evidence, "ax_tree", "dom_path") {
                snapshot = snapshot.add_item(
                    if en { "DOM path" } else { "DOM-Pfad" },
                    compact_html(path, 90),
                );
            }

            if let Some(measured) = contrast_measured_text(&occ.evidence, en) {
                snapshot =
                    snapshot.add_item(if en { "Measured value" } else { "Messwert" }, measured);
            }

            builder = builder.add_component(snapshot);

            // Evidence-grade findings: a cropped, highlighted screenshot of
            // the element behind this occurrence, if one was captured during
            // the audit (single-URL PDF only, capped at MAX_ELEMENT_CROPS
            // report-wide — see `PipelineConfig.capture_element_evidence`).
            if let Some(bytes) = &occ.evidence_screenshot {
                let temp_path = std::env::temp_dir()
                    .join(format!("ams-evidence-{}-{}.png", report_ts, evidence_seq));
                if std::fs::write(&temp_path, bytes).is_ok() {
                    let asset_name = format!("/auditmysite-evidence-{}.png", evidence_seq);
                    builder = builder.asset(asset_name.clone(), temp_path);
                    let caption = match (occ.evidence_viewport, en) {
                        (Some("mobile"), true) => "Element on page (mobile viewport)",
                        (Some("mobile"), false) => "Element auf der Seite (Mobile-Ansicht)",
                        (_, true) => "Element on page (desktop viewport)",
                        (_, false) => "Element auf der Seite (Desktop-Ansicht)",
                    };
                    builder = builder.add_component(
                        Image::new(asset_name)
                            .with_width("55%")
                            .with_caption(caption),
                    );
                }
                *evidence_seq += 1;
            }

            if let Some(code) = occ
                .suggested_code
                .as_deref()
                .map(str::trim)
                .filter(|value| !value.is_empty())
            {
                builder = builder.add_component(
                    Callout::info(compact_html(code, 180))
                        .with_title(i18n.t("finding-suggested-fix")),
                );
            }
        }
        if hidden > 0 {
            let msg = if en {
                format!(
                    "{hidden} more {} documented in the technical appendix.",
                    if hidden == 1 {
                        "occurrence"
                    } else {
                        "occurrences"
                    }
                )
            } else {
                format!(
                    "{hidden} {} im technischen Anhang dokumentiert.",
                    if hidden == 1 {
                        "weiteres Vorkommen"
                    } else {
                        "weitere Vorkommen"
                    }
                )
            };
            builder = builder.add_component(Callout::info(&msg));
        }
    }

    if has_real_location && !group.pattern_clusters.is_empty() {
        let mut table = renderreport::components::AuditTable::new(vec![
            renderreport::components::TableColumn::new(i18n.t("finding-pattern")).with_width("70%"),
            renderreport::components::TableColumn::new(i18n.t("finding-occurrences"))
                .with_width("30%"),
        ])
        .with_title(i18n.t("finding-frequent-patterns"));

        for cluster in &group.pattern_clusters {
            table = table.add_row(vec![
                truncate_url(&cluster.label, 72),
                cluster.occurrences.to_string(),
            ]);
        }
        builder = builder.add_component(table);
        builder = builder.add_component(Callout::info(i18n.t("finding-frequent-patterns-note")));
    }

    if let Some(ref cause) = group.structural_cause {
        // plan/4-root-cause-confidence-wording.md: a single-URL audit sees
        // only one page, so a shared-component pattern is at best a strong
        // probability, never a confirmed fact — the label (previously the
        // hardcoded English "Root Cause", unlocalized even in German
        // reports) and the callout text (`finding-structural-cause-*` in
        // report.ftl) must both read as a likelihood, not a certainty.
        let en = is_english(i18n);
        let label = if group.is_component_issue {
            if en {
                "Likely root cause"
            } else {
                "Wahrscheinliche Ursache"
            }
        } else if en {
            "Structural cause"
        } else {
            "Strukturelle Ursache"
        };
        let callout = if group.is_component_issue {
            Callout::warning(cause).with_title(label)
        } else {
            Callout::info(cause).with_title(label)
        };
        builder = builder.add_component(callout);
    }

    builder = builder.add_component(Divider {
        style: "solid".to_string(),
        thickness: "0pt".to_string(),
        color: Some("#ffffff".to_string()),
        spacing_above: "15pt".to_string(),
        spacing_below: "0pt".to_string(),
    });

    builder
}

/// Extract the HTML element type from a CSS selector path.
/// Examples: "div.main > img" → "img", "a#skip-link" → "a", "button" → "button"
fn extract_element_type(selector: &str) -> &str {
    let last_segment = selector.split('>').next_back().unwrap_or(selector).trim();
    let last_token = last_segment
        .split_whitespace()
        .last()
        .unwrap_or(last_segment);
    let end = last_token
        .find(|c: char| !c.is_ascii_alphanumeric() && c != '-')
        .unwrap_or(last_token.len());
    &last_token[..end]
}

#[cfg(test)]
mod tests {
    use super::customer_perspective_title;
    use crate::output::report_model::{
        CriticalityTier, Effort, FindingGroup, FindingPatternCluster, NarrativeArc, Priority, Role,
    };
    use crate::wcag::Severity;

    fn group(rule_id: &str, title: &str, dimension: &str) -> FindingGroup {
        FindingGroup {
            title: title.to_string(),
            rule_id: rule_id.to_string(),
            wcag_criterion: String::new(),
            wcag_level: String::new(),
            help_url: None,
            dimension: Some(dimension.to_string()),
            subcategory: None,
            issue_class: None,
            severity: Severity::High,
            priority: Priority::High,
            customer_description: String::new(),
            user_impact: "Nutzer können die betroffene Funktion nicht zuverlässig verwenden."
                .to_string(),
            business_impact: String::new(),
            typical_cause: String::new(),
            recommendation: String::new(),
            technical_note: String::new(),
            confidence: String::new(),
            false_positive_risk: String::new(),
            verification: String::new(),
            complexity: String::new(),
            complexity_reason: String::new(),
            complexity_kind: crate::audit::normalized::ComplexityKind::LowScope,
            expected_impact: String::new(),
            expected_impact_kind: crate::audit::normalized::ExpectedImpactKind::Other {
                occurrence_count: 1,
                score_effect: crate::audit::normalized::ScoreEffect::Low,
            },
            bfsg_relevance: String::new(),
            remediation_priority: String::new(),
            occurrence_count: 1,
            affected_urls: vec![],
            affected_elements: 1,
            additional_occurrences: 0,
            pattern_clusters: Vec::<FindingPatternCluster>::new(),
            location_hints: vec![],
            representative_occurrences: vec![],
            responsible_role: Role::Development,
            effort: Effort::Medium,
            execution_priority: crate::output::report_model::ExecutionPriority::Important,
            examples: vec![],
            structural_cause: None,
            is_component_issue: false,
            criticality_tier: CriticalityTier::Mandatory,
            narrative: NarrativeArc {
                diagnose: String::new(),
                ursache: String::new(),
                wirkung: String::new(),
                umsetzung: String::new(),
            },
        }
    }

    #[test]
    fn finding_customer_perspective_maps_common_audit_topics() {
        assert_eq!(
            customer_perspective_title(
                &group(
                    "a11y.name_role.missing",
                    "Fehlende Name/Rolle",
                    "Accessibility"
                ),
                false,
            ),
            "Bedienbarkeit"
        );
        assert_eq!(
            customer_perspective_title(
                &group(
                    "a11y.structure.missing",
                    "Fehlende semantische Struktur",
                    "Accessibility"
                ),
                false,
            ),
            "Orientierung und Struktur"
        );
        assert_eq!(
            customer_perspective_title(
                &group(
                    "a11y.contrast.weak",
                    "Unzureichender Farbkontrast",
                    "Accessibility"
                ),
                false,
            ),
            "Wahrnehmbarkeit und Lesbarkeit"
        );
        assert_eq!(
            customer_perspective_title(
                &group("seo.headings.empty_heading", "Leere Überschrift", "SEO"),
                false,
            ),
            "Orientierung und Struktur"
        );
    }
}