auditmysite 1.5.1

Resource-efficient WCAG 2.1 AA (+ select 2.2 criteria) 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
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
//! Journey Analysis — user-flow evaluation from AXTree data
//!
//! Evaluates how well a page supports a typical user journey:
//! Entry → Orientation → Navigation → Interaction → Conversion.

use serde::{Deserialize, Serialize};
use tracing::info;

use crate::accessibility::AXTree;
use crate::journey::page_intent::{detect_page_intent, PageIntent};
use crate::journey::scoring::{journey_dimension_score, weighted_average_with_intent};
use crate::ux::saturating_penalty;

// ── Generic / CTA keyword lists (shared with UX but scoped here) ───

const GENERIC_LINK_LABELS: &[&str] = &[
    // English
    "more",
    "click here",
    "read more",
    "learn more",
    "details",
    "info",
    "link",
    "here",
    "view",
    "see more",
    "see all",
    // German
    "mehr",
    "hier",
    "klicken",
    "weiter",
    "hier klicken",
    "mehr erfahren",
    "weiterlesen",
    "alle anzeigen",
    "ansehen",
    "jetzt lesen",
    "öffnen",
    // French
    "ici",
    "cliquez ici",
    "en savoir plus",
    "lire la suite",
    "lire plus",
    "voir plus",
    "voir tout",
    "télécharger",
    // Spanish
    "aquí",
    "haz clic aquí",
    "leer más",
    "saber más",
    "ver más",
    "ver todo",
    // Italian
    "qui",
    "clicca qui",
    "leggi di più",
    "scopri di più",
    "vedi di più",
    "vedi tutto",
    // Portuguese
    "aqui",
    "clique aqui",
    "leia mais",
    "saiba mais",
    "ver mais",
    // Dutch
    "hier",
    "klik hier",
    "meer lezen",
    "lees meer",
    "bekijk meer",
    "volgende",
    // Swedish
    "här",
    "klicka här",
    "läs mer",
    // Norwegian
    "her",
    "klikk her",
    "les mer",
    // Polish
    "tutaj",
    "kliknij tutaj",
    "czytaj więcej",
    "więcej",
    // Turkish
    "devamını oku",
    "daha fazla",
];

const CTA_KEYWORDS: &[&str] = &[
    // English
    "buy",
    "order",
    "contact",
    "start",
    "register",
    "sign up",
    "book",
    "free",
    "trial",
    "get started",
    "subscribe",
    "cart",
    "checkout",
    "download",
    "demo",
    "newsletter",
    // German
    "kaufen",
    "bestellen",
    "kontakt",
    "anfrage",
    "starten",
    "registrieren",
    "anmelden",
    "buchen",
    "jetzt",
    "kostenlos",
    "testen",
    "termin",
    "beratung",
    "angebot",
    "warenkorb",
    "kasse",
    "herunterladen",
    // French
    "acheter",
    "commander",
    "contacter",
    "commencer",
    "s'inscrire",
    "réserver",
    "gratuit",
    "essai",
    "télécharger",
    "abonner",
    "panier",
    // Spanish
    "comprar",
    "pedir",
    "contactar",
    "empezar",
    "registrarse",
    "reservar",
    "gratis",
    "prueba",
    "descargar",
    "suscribirse",
    "carrito",
    // Italian
    "acquistare",
    "ordinare",
    "contattare",
    "iniziare",
    "registrarsi",
    "prenotare",
    "gratuito",
    "prova",
    "scaricare",
    "iscriversi",
    "carrello",
    // Portuguese
    "comprar",
    "pedir",
    "contactar",
    "começar",
    "registrar",
    "reservar",
    "grátis",
    "baixar",
    "assinar",
    "carrinho",
    // Dutch
    "kopen",
    "bestellen",
    "contact",
    "starten",
    "registreren",
    "boeken",
    "gratis",
    "proberen",
    "downloaden",
    "abonneren",
    "winkelwagen",
    // Swedish
    "köpa",
    "beställa",
    "kontakta",
    "starta",
    "registrera",
    "boka",
    "gratis",
    "ladda ner",
    "prenumerera",
    // Polish
    "kupić",
    "zamówić",
    "kontakt",
    "zarejestrować",
    "zarezerwować",
    "bezpłatny",
    "pobierz",
    "subskrybować",
    // Turkish
    "satın al",
    "sipariş ver",
    "iletişim",
    "başla",
    "kayıt ol",
    "rezervasyon",
    "ücretsiz",
    "indir",
    "abone ol",
];

// ── Public types ────────────────────────────────────────────────────

/// Complete journey analysis result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JourneyAnalysis {
    /// Overall journey score (0–100)
    pub score: u32,
    /// Grade (A–F)
    pub grade: String,
    /// Detected page intent
    pub page_intent: PageIntent,
    /// Per-dimension results
    pub entry_clarity: JourneyDimension,
    pub orientation: JourneyDimension,
    pub navigation: JourneyDimension,
    pub interaction: JourneyDimension,
    pub conversion: JourneyDimension,
    /// Friction points found along the journey
    pub friction_points: Vec<FrictionPoint>,
}

/// Stable identifier for which journey dimension a [`JourneyDimension`] is.
///
/// Lets the PDF layer re-derive a localized `name`/`summary` without parsing
/// the canonical-English text fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum JourneyDimensionKind {
    EntryClarity,
    Orientation,
    Navigation,
    Interaction,
    Conversion,
}

/// A scored journey dimension
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JourneyDimension {
    /// Which dimension this is (for localized re-derivation)
    pub kind: JourneyDimensionKind,
    /// Dimension name (canonical English)
    pub name: String,
    pub score: u32,
    pub weight: f64,
    /// Score-band summary (canonical English; derived from `kind` + `score`)
    pub summary: String,
}

/// Stable identifier for a concrete friction point.
///
/// One variant per distinct problem/impact/recommendation shape. Together with
/// the raw values stored on [`FrictionPoint`] this fully reproduces the
/// human-readable strings in any language.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FrictionKind {
    // Entry
    NoH1,
    MultipleH1,
    VagueH1,
    NoPageTitle,
    LittleEarlyText,
    // Orientation
    NavigationMissing,
    MainHiddenFromAx,
    MainMissing,
    FewSubheadings,
    NoBreadcrumb,
    NoFooter,
    // Navigation
    GenericLinks,
    EmptyLinks,
    DuplicateLinks,
    TooManyLinks,
    // Interaction
    UnnamedButtons,
    UnlabeledForms,
    GenericButtons,
    // Conversion
    NoCallToAction,
    CompetingCtas,
    BlockingDialog,
    ComplexForm,
}

/// The interpolated values a friction text may reference.
///
/// Stored on every [`FrictionPoint`] so that [`journey_friction_text`] can
/// reproduce the strings in any locale. Only the field relevant to the
/// friction's `kind` is populated.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FrictionValues {
    /// A generic count (MultipleH1, GenericLinks, EmptyLinks, DuplicateLinks,
    /// UnnamedButtons, UnlabeledForms, GenericButtons, ComplexForm).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<u32>,
}

/// A point of friction in the user journey
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrictionPoint {
    /// Stable friction identifier (for localized re-derivation)
    pub kind: FrictionKind,
    pub step: String,
    pub severity: String,
    /// Problem statement (canonical English)
    pub problem: String,
    /// Impact statement (canonical English)
    pub impact: String,
    /// Recommendation (canonical English)
    pub recommendation: String,
    /// Interpolated values needed to reproduce the text in another language
    #[serde(default)]
    pub values: FrictionValues,
}

impl FrictionPoint {
    /// Build a friction point, baking canonical-English `problem`/`impact`/
    /// `recommendation` from its kind + values via [`journey_friction_text`].
    fn new(kind: FrictionKind, values: FrictionValues) -> Self {
        let (problem, impact, recommendation) = journey_friction_text(kind, &values, true);
        FrictionPoint {
            kind,
            step: friction_step(kind).to_string(),
            severity: friction_severity(kind).to_string(),
            problem,
            impact,
            recommendation,
            values,
        }
    }
}

// ── Localized text (single source of truth) ─────────────────────────

/// Journey step the friction belongs to (stable, locale-independent).
fn friction_step(kind: FrictionKind) -> &'static str {
    use FrictionKind::*;
    match kind {
        NoH1 | MultipleH1 | VagueH1 | NoPageTitle | LittleEarlyText => "Entry",
        NavigationMissing | MainHiddenFromAx | MainMissing | FewSubheadings | NoBreadcrumb
        | NoFooter => "Orientation",
        GenericLinks | EmptyLinks | DuplicateLinks | TooManyLinks => "Navigation",
        UnnamedButtons | UnlabeledForms | GenericButtons => "Interaction",
        NoCallToAction | CompetingCtas | BlockingDialog | ComplexForm => "Conversion",
    }
}

/// Severity of a friction point (stable, locale-independent).
fn friction_severity(kind: FrictionKind) -> &'static str {
    use FrictionKind::*;
    match kind {
        NoH1 | NavigationMissing | EmptyLinks | UnnamedButtons | UnlabeledForms
        | NoCallToAction => "high",
        MultipleH1 | NoPageTitle | LittleEarlyText | MainMissing | BlockingDialog | ComplexForm => {
            "medium"
        }
        VagueH1 | CompetingCtas => "medium",
        MainHiddenFromAx | FewSubheadings | DuplicateLinks | GenericLinks | GenericButtons
        | NoBreadcrumb | NoFooter | TooManyLinks => "low",
    }
}

/// Localized dimension name for a [`JourneyDimensionKind`].
pub fn journey_dimension_name(kind: JourneyDimensionKind, en: bool) -> &'static str {
    match (kind, en) {
        (JourneyDimensionKind::EntryClarity, _) => "Entry Clarity",
        (JourneyDimensionKind::Orientation, _) => "Orientation",
        (JourneyDimensionKind::Navigation, _) => "Navigation",
        (JourneyDimensionKind::Interaction, _) => "Interaction",
        (JourneyDimensionKind::Conversion, _) => "Conversion",
    }
}

/// Localized score-band summary for a journey dimension.
///
/// The single source of truth for dimension `summary` text. Analysis calls it
/// with `en = true` to bake canonical English; the PDF layer re-derives in the
/// run language.
pub fn journey_dimension_summary(kind: JourneyDimensionKind, score: u32, en: bool) -> String {
    use JourneyDimensionKind::*;
    let high = score >= 85;
    let mid = score >= 60;
    match kind {
        EntryClarity => {
            if high {
                if en {
                    "The page purpose is immediately clear"
                } else {
                    "Seitenzweck ist sofort klar erkennbar"
                }
            } else if mid {
                if en {
                    "The entry point is broadly understandable, but could be improved"
                } else {
                    "Einstieg grundsätzlich verständlich, aber verbesserungswürdig"
                }
            } else if en {
                "The page purpose is not recognizable at first glance"
            } else {
                "Seitenzweck ist nicht auf den ersten Blick erkennbar"
            }
        }
        Orientation => {
            if high {
                if en {
                    "Good orientation through navigation, landmarks and structure"
                } else {
                    "Gute Orientierung durch Navigation, Landmarks und Struktur"
                }
            } else if mid {
                if en {
                    "Basic orientation present, structure could be expanded"
                } else {
                    "Grundlegende Orientierung vorhanden, Struktur ausbaufähig"
                }
            } else if en {
                "Insufficient orientation — navigation or landmarks are missing"
            } else {
                "Mangelnde Orientierung — Navigation oder Landmarks fehlen"
            }
        }
        Navigation => {
            if high {
                if en {
                    "Links are understandable, unambiguous and well structured"
                } else {
                    "Links sind verständlich, eindeutig und gut strukturiert"
                }
            } else if mid {
                if en {
                    "Navigation is usable, but some links are unclear or redundant"
                } else {
                    "Navigation nutzbar, aber einige Links sind unklar oder redundant"
                }
            } else if en {
                "Navigation problems: unclear, empty or redundant links"
            } else {
                "Navigationsprobleme: unklare, leere oder redundante Links"
            }
        }
        Interaction => {
            if high {
                if en {
                    "Interactive elements are clearly labeled and operable"
                } else {
                    "Interaktive Elemente sind klar beschriftet und bedienbar"
                }
            } else if mid {
                if en {
                    "Basic interaction is possible, but some labels are unclear"
                } else {
                    "Grundlegende Interaktion möglich, aber Beschriftungen teilweise unklar"
                }
            } else if en {
                "Significant interaction problems: unlabeled buttons or form fields"
            } else {
                "Erhebliche Interaktionsprobleme: unbeschriftete Buttons oder Formularfelder"
            }
        }
        Conversion => {
            if high {
                if en {
                    "Clear conversion path with a reachable CTA"
                } else {
                    "Klarer Conversion-Pfad mit erreichbarem CTA"
                }
            } else if mid {
                if en {
                    "Conversion path present, but impaired by obstacles"
                } else {
                    "Conversion-Pfad vorhanden, aber durch Hindernisse beeinträchtigt"
                }
            } else if en {
                "No clear conversion path detectable"
            } else {
                "Kein klarer Conversion-Pfad erkennbar"
            }
        }
    }
    .to_string()
}

/// The single source of truth for friction `problem`/`impact`/`recommendation`.
///
/// Returns `(problem, impact, recommendation)` in German or English for the
/// given `kind` and interpolated `values`. Analysis calls it with `en = true`
/// to bake canonical English; the PDF layer re-derives in the run language.
pub fn journey_friction_text(
    kind: FrictionKind,
    values: &FrictionValues,
    en: bool,
) -> (String, String, String) {
    use FrictionKind::*;
    let count = values.count.unwrap_or(0);

    let (problem, impact, recommendation): (String, String, String) = match kind {
        NoH1 => (
            if en {
                "No H1 heading — the page purpose is not immediately recognizable".into()
            } else {
                "Keine H1-Überschrift — Seitenzweck nicht sofort erkennbar".into()
            },
            if en {
                "Users do not understand what this page is about".into()
            } else {
                "Nutzer verstehen nicht, worum es auf dieser Seite geht".into()
            },
            if en {
                "Set a meaningful H1 heading".into()
            } else {
                "Eine aussagekräftige H1-Überschrift setzen".into()
            },
        ),
        MultipleH1 => (
            if en {
                format!("{} H1 headings — unclear page focus", count)
            } else {
                format!("{} H1-Überschriften — unklarer Seitenfokus", count)
            },
            if en {
                "Users cannot tell what the main content is".into()
            } else {
                "Nutzer wissen nicht, was der Hauptinhalt ist".into()
            },
            if en {
                "Use exactly one H1 heading per page".into()
            } else {
                "Genau eine H1-Überschrift pro Seite verwenden".into()
            },
        ),
        NoPageTitle => (
            if en {
                "No page title detected".into()
            } else {
                "Kein Seitentitel erkannt".into()
            },
            if en {
                "The tab title is empty — users lose context when switching tabs".into()
            } else {
                "Tab-Titel ist leer — Nutzer verlieren den Kontext beim Tabwechsel".into()
            },
            if en {
                "Set a meaningful <title>".into()
            } else {
                "Aussagekräftigen <title> setzen".into()
            },
        ),
        LittleEarlyText => (
            if en {
                "Little visible text in the upper area of the page".into()
            } else {
                "Wenig sichtbarer Text im oberen Seitenbereich".into()
            },
            if en {
                "Users get no immediate orientation".into()
            } else {
                "Nutzer erhalten keine sofortige Orientierung".into()
            },
            if en {
                "Place relevant introductory text above the fold".into()
            } else {
                "Relevanten Einleitungstext above-the-fold platzieren".into()
            },
        ),
        NavigationMissing => (
            if en {
                "Navigation landmark not reachable in the accessibility tree".into()
            } else {
                "Navigation-Landmark nicht im Accessibility-Tree erreichbar".into()
            },
            if en {
                "Screen reader users cannot recognize the main navigation as such or jump to it directly — often caused by aria-hidden on the <nav> element or an ancestor.".into()
            } else {
                "Screenreader-Nutzer können die Hauptnavigation nicht als solche erkennen oder gezielt ansteuern — häufig durch aria-hidden auf dem <nav>-Element oder einem Vorfahren verursacht.".into()
            },
            if en {
                "Check whether aria-hidden=\"true\" is set on or above the <nav> element. The navigation landmark must be visible in the accessibility tree (role=\"navigation\").".into()
            } else {
                "Prüfen, ob aria-hidden=\"true\" auf oder oberhalb des <nav>-Elements gesetzt ist. Das Navigation-Landmark muss im Accessibility-Tree sichtbar sein (role=\"navigation\").".into()
            },
        ),
        MainHiddenFromAx => (
            if en {
                "<main> element present, but not visible in the accessibility tree".into()
            } else {
                "<main>-Element vorhanden, aber im Accessibility-Tree nicht sichtbar".into()
            },
            if en {
                "Screen reader users may not be able to jump to the main content directly on this viewport".into()
            } else {
                "Screenreader-Nutzer können den Hauptinhalt auf diesem Viewport möglicherweise nicht direkt anspringen".into()
            },
            if en {
                "Check whether an overlay or aria-hidden hides the <main> area on this viewport"
                    .into()
            } else {
                "Prüfen, ob ein Overlay oder aria-hidden den <main>-Bereich auf diesem Viewport verbirgt".into()
            },
        ),
        MainMissing => (
            if en {
                "No main content area (<main>) detected".into()
            } else {
                "Kein Hauptinhaltsbereich (<main>) erkannt".into()
            },
            if en {
                "Screen reader users cannot jump to the main content directly".into()
            } else {
                "Screenreader-Nutzer können den Hauptinhalt nicht direkt anspringen".into()
            },
            if en {
                "Wrap the main content in a <main> element".into()
            } else {
                "Hauptinhalt in ein <main>-Element einschließen".into()
            },
        ),
        FewSubheadings => (
            if en {
                "Hardly any subheadings for orientation".into()
            } else {
                "Kaum Zwischenüberschriften zur Orientierung".into()
            },
            if en {
                "Users cannot scan the content".into()
            } else {
                "Nutzer können Inhalte nicht scannen".into()
            },
            if en {
                "Structure the content with H2/H3 headings".into()
            } else {
                "Inhalte mit H2/H3-Überschriften gliedern".into()
            },
        ),
        GenericLinks => (
            if en {
                format!("{} links with generic text (\"more\", \"here\")", count)
            } else {
                format!(
                    "{} Links mit generischen Texten (\"mehr\", \"hier\")",
                    count
                )
            },
            if en {
                "Users cannot distinguish where links lead".into()
            } else {
                "Nutzer können nicht unterscheiden, wohin Links führen".into()
            },
            if en {
                "Write descriptive link text that names the destination".into()
            } else {
                "Linktexte beschreibend formulieren, die das Ziel benennen".into()
            },
        ),
        EmptyLinks => (
            if en {
                format!("{} links without recognizable text", count)
            } else {
                format!("{} Links ohne erkennbaren Text", count)
            },
            if en {
                "Screen reader users do not learn what the link does".into()
            } else {
                "Screenreader-Nutzer erfahren nicht, was der Link tut".into()
            },
            if en {
                "Give every link descriptive text or an aria-label".into()
            } else {
                "Alle Links mit beschreibendem Text oder aria-label versehen".into()
            },
        ),
        DuplicateLinks => (
            if en {
                format!("{} duplicate link texts on the page", count)
            } else {
                format!("{} doppelte Linktexte auf der Seite", count)
            },
            if en {
                "The same label for different destinations confuses users".into()
            } else {
                "Gleiche Beschriftung für unterschiedliche Ziele verwirrt Nutzer".into()
            },
            if en {
                "Make link texts unambiguous or differentiate them with aria-label".into()
            } else {
                "Linktexte eindeutig formulieren oder mit aria-label differenzieren".into()
            },
        ),
        UnnamedButtons => (
            if en {
                format!("{} buttons without a recognizable label", count)
            } else {
                format!("{} Buttons ohne erkennbare Beschriftung", count)
            },
            if en {
                "Users do not know what a button triggers".into()
            } else {
                "Nutzer wissen nicht, was ein Button auslöst".into()
            },
            if en {
                "Give every button descriptive text or an aria-label".into()
            } else {
                "Alle Buttons mit beschreibendem Text oder aria-label versehen".into()
            },
        ),
        UnlabeledForms => (
            if en {
                format!("{} form fields without a label", count)
            } else {
                format!("{} Formularfelder ohne Label", count)
            },
            if en {
                "Users do not know what input is expected".into()
            } else {
                "Nutzer wissen nicht, welche Eingabe erwartet wird".into()
            },
            if en {
                "Connect every form field to a visible <label> or aria-label".into()
            } else {
                "Jedes Formularfeld mit sichtbarem <label> oder aria-label verbinden".into()
            },
        ),
        GenericButtons => (
            if en {
                format!("{} buttons with generic labels (\"OK\", \"Submit\")", count)
            } else {
                format!(
                    "{} Buttons mit generischen Labels (\"OK\", \"Submit\")",
                    count
                )
            },
            if en {
                "The context of the action is unclear".into()
            } else {
                "Kontext der Aktion ist nicht klar".into()
            },
            if en {
                "Label buttons with action-describing text (e.g. \"Send message\")".into()
            } else {
                "Buttons mit handlungsbeschreibenden Texten benennen (z. B. \"Nachricht senden\")"
                    .into()
            },
        ),
        VagueH1 => (
            if en {
                "The H1 heading is too short to say what the page is about".into()
            } else {
                "Die H1-Überschrift ist zu kurz, um den Seitenzweck zu benennen".into()
            },
            if en {
                "Visitors cannot tell from the heading whether they are in the right place".into()
            } else {
                "Besucher erkennen an der Überschrift nicht, ob sie richtig sind".into()
            },
            if en {
                "Name the subject of the page in the H1".into()
            } else {
                "Den Gegenstand der Seite in der H1 benennen".into()
            },
        ),
        NoBreadcrumb => (
            if en {
                "No breadcrumb trail".into()
            } else {
                "Keine Brotkrumen-Navigation".into()
            },
            if en {
                "Visitors arriving from search cannot see where this page sits in the site".into()
            } else {
                "Wer aus der Suche kommt, sieht nicht, wo die Seite im Aufbau steht".into()
            },
            if en {
                "Add a breadcrumb trail on pages below the top level".into()
            } else {
                "Auf Unterseiten eine Brotkrumen-Navigation ergänzen".into()
            },
        ),
        NoFooter => (
            if en {
                "No footer region recognizable".into()
            } else {
                "Kein Footer-Bereich erkennbar".into()
            },
            if en {
                "The usual place for contact, legal and secondary links is missing".into()
            } else {
                "Der übliche Ort für Kontakt, Rechtliches und Zweitnavigation fehlt".into()
            },
            if en {
                "Mark up the page footer with <footer> or role=\"contentinfo\"".into()
            } else {
                "Den Seitenfuß mit <footer> oder role=\"contentinfo\" auszeichnen".into()
            },
        ),
        TooManyLinks => (
            if en {
                format!("{count} links compete for attention")
            } else {
                format!("{count} Links konkurrieren um Aufmerksamkeit")
            },
            if en {
                "The next step is harder to find the more equally weighted links surround it".into()
            } else {
                "Der nächste Schritt ist schwerer zu finden, je mehr gleichrangige Links ihn umgeben".into()
            },
            if en {
                "Group secondary links and give the primary path visual weight".into()
            } else {
                "Zweitrangige Links gruppieren und dem Hauptweg visuelles Gewicht geben".into()
            },
        ),
        CompetingCtas => (
            if en {
                format!("{count} calls to action on one page")
            } else {
                format!("{count} Handlungsaufrufe auf einer Seite")
            },
            if en {
                "Several equally prominent actions leave unclear which one is intended".into()
            } else {
                "Mehrere gleich prominente Aktionen lassen offen, welche gemeint ist".into()
            },
            if en {
                "Choose one primary action per page and subordinate the rest".into()
            } else {
                "Pro Seite eine Hauptaktion wählen und die übrigen unterordnen".into()
            },
        ),
        NoCallToAction => (
            if en {
                "No recognizable call-to-action on the page".into()
            } else {
                "Kein erkennbarer Call-to-Action auf der Seite".into()
            },
            if en {
                "Users have no clear prompt to act".into()
            } else {
                "Nutzer haben keine klare Handlungsaufforderung".into()
            },
            if en {
                "Define a primary CTA and place it prominently".into()
            } else {
                "Einen primären CTA definieren und prominent platzieren".into()
            },
        ),
        BlockingDialog => (
            if en {
                "Dialog/overlay detected that can interrupt the user path".into()
            } else {
                "Dialog/Overlay erkannt, der den Nutzerpfad unterbrechen kann".into()
            },
            if en {
                "Cookie banners or modals can obscure the CTA".into()
            } else {
                "Cookie-Banner oder Modals können den CTA verdecken".into()
            },
            if en {
                "Ensure overlays are easy to close and do not block the CTA".into()
            } else {
                "Sicherstellen, dass Overlays einfach schließbar sind und den CTA nicht blockieren"
                    .into()
            },
        ),
        ComplexForm => (
            if en {
                format!("{} form fields — high input barrier", count)
            } else {
                format!("{} Formularfelder — hohe Eingabehürde", count)
            },
            if en {
                "Complex forms reduce the completion rate".into()
            } else {
                "Komplexe Formulare reduzieren die Abschlussrate".into()
            },
            if en {
                "Reduce the form to essential fields or split it into steps".into()
            } else {
                "Formular auf wesentliche Felder reduzieren oder in Schritte aufteilen".into()
            },
        ),
    };

    (problem, impact, recommendation)
}

// ── Analysis entry point ────────────────────────────────────────────

/// Analyze user journey quality from the Accessibility Tree.
/// Runs purely on already-extracted AXTree data — no CDP calls needed.
///
/// Produces canonical-English text in the struct (and thus JSON).
pub fn analyze_journey(tree: &AXTree) -> JourneyAnalysis {
    analyze_journey_inner(tree, false, None)
}

/// Like [`analyze_journey`] but accepts a DOM-level hint for whether a `<main>`
/// element exists in the HTML source. Pass `true` when a JS `querySelector`
/// confirms `<main>` is present but hidden from the AX tree (e.g. by an overlay
/// on mobile viewport), so the severity is downgraded instead of flagged as
/// missing structure.
///
/// Produces canonical-English text in the struct (and thus JSON).
pub fn analyze_journey_with_dom_check(tree: &AXTree, dom_has_main: bool) -> JourneyAnalysis {
    analyze_journey_inner(tree, dom_has_main, None)
}

/// Like [`analyze_journey_with_dom_check`], plus the length of the visible text
/// in the first viewport height as measured in the rendered page.
///
/// Pass `None` when no page is available; the analysis then falls back to a
/// document-order window over the tree, which is a weaker proxy — see
/// `analyze_entry_clarity` (plan 51).
pub fn analyze_journey_with_page_context(
    tree: &AXTree,
    dom_has_main: bool,
    measured_early_text: Option<usize>,
) -> JourneyAnalysis {
    analyze_journey_inner(tree, dom_has_main, measured_early_text)
}

fn analyze_journey_inner(
    tree: &AXTree,
    dom_has_main: bool,
    measured_early_text: Option<usize>,
) -> JourneyAnalysis {
    info!("Analyzing user journey...");

    let page_intent = detect_page_intent(tree);
    let (w_entry, w_orient, w_nav, w_interact, w_convert) = page_intent.weights();

    let mut friction_points = Vec::new();

    let entry_clarity = analyze_entry_clarity(tree, measured_early_text, &mut friction_points);
    let orientation = analyze_orientation(tree, &mut friction_points, dom_has_main);
    let navigation = analyze_navigation(tree, &mut friction_points);
    let interaction = analyze_interaction(tree, &mut friction_points);
    let conversion = analyze_conversion(tree, &mut friction_points);

    let score = weighted_average_with_intent(&[
        (entry_clarity.score, w_entry),
        (orientation.score, w_orient),
        (navigation.score, w_nav),
        (interaction.score, w_interact),
        (conversion.score, w_convert),
    ]);

    let grade = crate::registry::LETTER_GRADE
        .label(score as f32, false)
        .to_string();

    info!(
        "Journey analysis: score={}, intent={:?}, friction_points={}",
        score,
        page_intent,
        friction_points.len()
    );

    // Update dimensions with intent-adjusted weights for display
    let mut entry_clarity = entry_clarity;
    entry_clarity.weight = w_entry;
    let mut orientation = orientation;
    orientation.weight = w_orient;
    let mut navigation = navigation;
    navigation.weight = w_nav;
    let mut interaction = interaction;
    interaction.weight = w_interact;
    let mut conversion = conversion;
    conversion.weight = w_convert;

    JourneyAnalysis {
        score,
        grade,
        page_intent,
        entry_clarity,
        orientation,
        navigation,
        interaction,
        conversion,
        friction_points,
    }
}

// ── Dimension analyzers ─────────────────────────────────────────────

/// Entry Clarity: Is the purpose of this page immediately clear?
fn analyze_entry_clarity(
    tree: &AXTree,
    measured_early_text: Option<usize>,
    friction: &mut Vec<FrictionPoint>,
) -> JourneyDimension {
    use FrictionKind::*;
    let headings = tree.headings();
    let mut penalties = Vec::new();

    // H1 presence and clarity
    let h1s: Vec<_> = headings
        .iter()
        .filter(|h| h.heading_level() == Some(1))
        .collect();

    if h1s.is_empty() {
        penalties.push(45.0);
        friction.push(FrictionPoint::new(NoH1, FrictionValues::default()));
    } else if h1s.len() > 1 {
        penalties.push(15.0);
        friction.push(FrictionPoint::new(
            MultipleH1,
            FrictionValues {
                count: Some(h1s.len() as u32),
            },
        ));
    } else {
        // Check H1 quality: very short or generic?
        if let Some(name) = h1s[0].name.as_deref() {
            if name.len() < 5 {
                penalties.push(20.0);
                friction.push(FrictionPoint::new(VagueH1, FrictionValues::default()));
            }
        }
    }

    // Page title (check for title-like node in tree)
    let has_title = tree
        .iter()
        .any(|n| n.role.as_deref() == Some("RootWebArea") && n.name.is_some());
    if !has_title {
        penalties.push(20.0);
        friction.push(FrictionPoint::new(NoPageTitle, FrictionValues::default()));
    }

    // Early content: does the top of the page carry text at all?
    //
    // The finding this feeds claims "little visible text in the upper area of
    // the page", so it is measured there: `measured_early_text` comes from the
    // rendered page, summing text whose box lies within the first viewport
    // height (`JourneyModule::collect`).
    //
    // The fallback counts text nodes among the first 50 in document order.
    // That is a proxy for vertical position and a poor one — on
    // www.inros-lackner.de the first 50 nodes are a skip link and forty
    // wrappers, while the articles further down are the actual top of the
    // page (plan 51). It stands in only where no page is available: the
    // library entry point `analyze_journey`, and tests.
    let early_text_len = measured_early_text.unwrap_or_else(|| {
        tree.iter_all()
            .take(50)
            .filter(|n| n.is_text())
            .filter_map(|n| n.name.as_ref())
            .map(|n| n.len())
            .sum()
    });

    if early_text_len < 30 {
        penalties.push(20.0);
        friction.push(FrictionPoint::new(
            LittleEarlyText,
            FrictionValues::default(),
        ));
    }

    let score = journey_dimension_score(&penalties, 100.0);
    build_dimension(JourneyDimensionKind::EntryClarity, score, 0.20)
}

/// Orientation: Can the user tell where they are and where they can go?
///
/// `dom_has_main`: when the caller has verified via DOM query that a `<main>`
/// element exists in the HTML (but may be hidden from the AX tree by an overlay
/// or `display:none`), set this to `true` to downgrade the finding severity.
fn analyze_orientation(
    tree: &AXTree,
    friction: &mut Vec<FrictionPoint>,
    dom_has_main: bool,
) -> JourneyDimension {
    use FrictionKind::*;
    let mut penalties = Vec::new();

    // Navigation landmark
    let has_nav = tree.iter().any(|n| n.role.as_deref() == Some("navigation"));
    if !has_nav {
        penalties.push(40.0);
        friction.push(FrictionPoint::new(
            NavigationMissing,
            FrictionValues::default(),
        ));
    }

    // Breadcrumbs or secondary nav hint
    let has_breadcrumb = tree.iter().any(|n| {
        let name = n.name.as_deref().unwrap_or("").to_lowercase();
        name.contains("breadcrumb")
            || n.role.as_deref() == Some("navigation") && name.contains("breadcrumb")
    });
    // Not penalized heavily, but bonus signals
    if !has_breadcrumb {
        penalties.push(10.0);
        friction.push(FrictionPoint::new(NoBreadcrumb, FrictionValues::default()));
    }

    // Main landmark
    let has_main = tree.iter().any(|n| n.role.as_deref() == Some("main"));
    if !has_main {
        if dom_has_main {
            // <main> exists in HTML but is hidden from the AX tree (overlay / display:none on
            // this viewport). Score impact is small — structure exists, but AT access is impaired.
            penalties.push(8.0);
            friction.push(FrictionPoint::new(
                MainHiddenFromAx,
                FrictionValues::default(),
            ));
        } else {
            penalties.push(20.0);
            friction.push(FrictionPoint::new(MainMissing, FrictionValues::default()));
        }
    }

    // Footer / complementary landmark
    let has_footer = tree
        .iter()
        .any(|n| n.role.as_deref() == Some("contentinfo"));
    if !has_footer {
        penalties.push(10.0);
        friction.push(FrictionPoint::new(NoFooter, FrictionValues::default()));
    }

    // Heading structure: are there sub-sections?
    let heading_count = tree.headings().len();
    if heading_count < 2 {
        penalties.push(15.0);
        friction.push(FrictionPoint::new(
            FewSubheadings,
            FrictionValues::default(),
        ));
    }

    let score = journey_dimension_score(&penalties, 100.0);
    build_dimension(JourneyDimensionKind::Orientation, score, 0.20)
}

/// Navigation: Are links clear, non-redundant, and well-structured?
fn analyze_navigation(tree: &AXTree, friction: &mut Vec<FrictionPoint>) -> JourneyDimension {
    use FrictionKind::*;
    let links = tree.links();
    let mut penalties = Vec::new();

    // Generic link labels
    let generic_count = links
        .iter()
        .filter(|l| {
            let name = l.name.as_deref().unwrap_or("").to_lowercase();
            let trimmed = name.trim();
            GENERIC_LINK_LABELS
                .iter()
                .any(|g| trimmed == *g || trimmed.starts_with(g))
        })
        .count();

    if generic_count > 0 {
        let p = saturating_penalty(generic_count as f64, 30.0, 8.0);
        penalties.push(p);
        if generic_count >= 3 {
            friction.push(FrictionPoint::new(
                GenericLinks,
                FrictionValues {
                    count: Some(generic_count as u32),
                },
            ));
        }
    }

    // Empty / unnamed links
    let empty_links = links
        .iter()
        .filter(|l| l.name.as_deref().is_none_or(|n| n.trim().is_empty()))
        .count();

    if empty_links > 0 {
        let p = saturating_penalty(empty_links as f64, 35.0, 5.0);
        penalties.push(p);
        if empty_links >= 2 {
            friction.push(FrictionPoint::new(
                EmptyLinks,
                FrictionValues {
                    count: Some(empty_links as u32),
                },
            ));
        }
    }

    // Duplicate link texts pointing potentially different places
    let mut link_names: Vec<String> = links
        .iter()
        .filter_map(|l| l.name.as_deref())
        .filter(|n| !n.trim().is_empty())
        .map(|n| n.to_lowercase().trim().to_string())
        .collect();
    link_names.sort();
    let total_links = link_names.len();
    link_names.dedup();
    let duplicate_count = total_links.saturating_sub(link_names.len());

    if duplicate_count > 5 {
        let p = saturating_penalty((duplicate_count - 5) as f64, 20.0, 10.0);
        penalties.push(p);
        if duplicate_count > 10 {
            friction.push(FrictionPoint::new(
                DuplicateLinks,
                FrictionValues {
                    count: Some(duplicate_count as u32),
                },
            ));
        }
    }

    // Link density: too many links for page size
    if links.len() > 60 {
        let excess = (links.len() - 60) as f64;
        let p = saturating_penalty(excess, 15.0, 60.0);
        penalties.push(p);
        friction.push(FrictionPoint::new(
            TooManyLinks,
            FrictionValues {
                count: Some(links.len() as u32),
            },
        ));
    }

    let score = journey_dimension_score(&penalties, 100.0);
    build_dimension(JourneyDimensionKind::Navigation, score, 0.25)
}

/// Interaction: Can users interact with controls effectively?
fn analyze_interaction(tree: &AXTree, friction: &mut Vec<FrictionPoint>) -> JourneyDimension {
    use FrictionKind::*;
    let buttons = tree.nodes_with_role("button");
    let form_controls = tree.form_controls();
    let mut penalties = Vec::new();

    // Buttons without accessible names
    let unnamed_buttons = buttons
        .iter()
        .filter(|b| b.name.as_deref().is_none_or(|n| n.trim().is_empty()))
        .count();

    if unnamed_buttons > 0 {
        let p = saturating_penalty(unnamed_buttons as f64, 40.0, 3.0);
        penalties.push(p);
        friction.push(FrictionPoint::new(
            UnnamedButtons,
            FrictionValues {
                count: Some(unnamed_buttons as u32),
            },
        ));
    }

    // Form controls without labels
    let unlabeled_forms = form_controls
        .iter()
        .filter(|fc| fc.name.as_deref().is_none_or(|n| n.trim().is_empty()))
        .count();

    if unlabeled_forms > 0 {
        let p = saturating_penalty(unlabeled_forms as f64, 35.0, 3.0);
        penalties.push(p);
        if unlabeled_forms >= 2 {
            friction.push(FrictionPoint::new(
                UnlabeledForms,
                FrictionValues {
                    count: Some(unlabeled_forms as u32),
                },
            ));
        }
    }

    // Generic button labels
    let generic_buttons = buttons
        .iter()
        .filter(|b| {
            let name = b.name.as_deref().unwrap_or("").to_lowercase();
            let trimmed = name.trim();
            matches!(
                trimmed,
                "ok" | "submit"
                    | "go"
                    | "next"
                    | "click"
                    | "button"
                    | "send"
                    // German
                    | "senden"
                    | "absenden"
                    | "los"
                    | "weiter"
                    | "schicken"
                    // French
                    | "envoyer"
                    | "suivant"
                    | "continuer"
                    | "valider"
                    // Spanish
                    | "enviar"
                    | "siguiente"
                    | "continuar"
                    | "aceptar"
                    // Italian
                    | "invia"
                    | "successivo"
                    | "continua"
                    | "conferma"
                    // Portuguese
                    | "próximo"
                    | "confirmar"
                    // Dutch
                    | "verzenden"
                    | "volgende"
                    | "doorgaan"
                    | "bevestigen"
                    // Swedish
                    | "skicka"
                    | "nästa"
                    | "fortsätt"
                    // Polish
                    | "wyślij"
                    | "następny"
                    | "kontynuuj"
                    // Turkish
                    | "gönder"
                    | "ileri"
                    | "devam"
            )
        })
        .count();

    if generic_buttons >= 2 {
        let p = saturating_penalty(generic_buttons as f64, 20.0, 5.0);
        penalties.push(p);
        friction.push(FrictionPoint::new(
            GenericButtons,
            FrictionValues {
                count: Some(generic_buttons as u32),
            },
        ));
    }

    let score = journey_dimension_score(&penalties, 100.0);
    build_dimension(JourneyDimensionKind::Interaction, score, 0.20)
}

/// Conversion: Can the user reach and complete the page's primary goal?
fn analyze_conversion(tree: &AXTree, friction: &mut Vec<FrictionPoint>) -> JourneyDimension {
    use FrictionKind::*;
    let buttons = tree.nodes_with_role("button");
    let links = tree.links();
    let mut penalties = Vec::new();

    // CTA presence
    let cta_found = buttons.iter().chain(links.iter()).any(|n| {
        let name = n.name.as_deref().unwrap_or("").to_lowercase();
        CTA_KEYWORDS.iter().any(|kw| name.contains(kw))
    });

    if !cta_found {
        penalties.push(40.0);
        friction.push(FrictionPoint::new(
            NoCallToAction,
            FrictionValues::default(),
        ));
    }

    // Are there interactive blockers before CTA? (modals, cookie banners hinted by roles)
    let has_dialog = tree
        .iter()
        .any(|n| matches!(n.role.as_deref(), Some("dialog" | "alertdialog")));
    if has_dialog {
        penalties.push(15.0);
        friction.push(FrictionPoint::new(
            BlockingDialog,
            FrictionValues::default(),
        ));
    }

    // Form complexity: too many fields can reduce conversion
    let form_controls = tree.form_controls();
    if form_controls.len() > 10 {
        let excess = (form_controls.len() - 10) as f64;
        let p = saturating_penalty(excess, 20.0, 10.0);
        penalties.push(p);
        if form_controls.len() > 15 {
            friction.push(FrictionPoint::new(
                ComplexForm,
                FrictionValues {
                    count: Some(form_controls.len() as u32),
                },
            ));
        }
    }

    // CTA competition: multiple equally strong CTAs dilute focus
    let cta_count: usize = buttons
        .iter()
        .chain(links.iter())
        .filter(|n| {
            let name = n.name.as_deref().unwrap_or("").to_lowercase();
            CTA_KEYWORDS.iter().any(|kw| name.contains(kw))
        })
        .count();

    if cta_count > 5 {
        let p = saturating_penalty((cta_count - 5) as f64, 15.0, 5.0);
        penalties.push(p);
        friction.push(FrictionPoint::new(
            CompetingCtas,
            FrictionValues {
                count: Some(cta_count as u32),
            },
        ));
    }

    let score = journey_dimension_score(&penalties, 100.0);
    build_dimension(JourneyDimensionKind::Conversion, score, 0.15)
}

// ── Helpers ─────────────────────────────────────────────────────────

/// Build a dimension, baking canonical-English `name`/`summary`.
fn build_dimension(kind: JourneyDimensionKind, score: u32, weight: f64) -> JourneyDimension {
    JourneyDimension {
        kind,
        name: journey_dimension_name(kind, true).to_string(),
        score,
        weight,
        summary: journey_dimension_summary(kind, score, true),
    }
}

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

    fn node(id: &str, role: &str, name: Option<&str>) -> AXNode {
        AXNode {
            node_id: id.into(),
            role: Some(role.into()),
            name: name.map(|s| s.into()),
            ..Default::default()
        }
    }

    /// Plan 51: the measurement from the rendered page wins over the
    /// tree-order proxy, in both directions. Without this the proxy silently
    /// decides, and it decides badly on wrapper-heavy markup.
    #[test]
    fn a_measured_page_beats_the_tree_order_proxy() {
        use crate::accessibility::AXTree;

        // A tree whose proxy window is full of text.
        let mut nodes = vec![node("root", "RootWebArea", Some("Seite"))];
        for i in 0..5 {
            nodes.push(node(
                &format!("t{i}"),
                "StaticText",
                Some("Reichlich Text ganz vorne im Baum."),
            ));
        }
        let tree = AXTree::from_nodes(nodes);

        let has_finding = |analysis: JourneyAnalysis| {
            analysis
                .friction_points
                .iter()
                .any(|f| matches!(f.kind, FrictionKind::LittleEarlyText))
        };

        assert!(
            !has_finding(analyze_journey(&tree)),
            "without a page the proxy applies, and this tree passes it"
        );
        assert!(
            has_finding(analyze_journey_with_page_context(&tree, false, Some(0))),
            "a page with no text above the fold is flagged even when the proxy passes"
        );
        assert!(
            !has_finding(analyze_journey_with_page_context(&tree, false, Some(400))),
            "a page with text above the fold is not flagged"
        );
    }

    /// Plan 50: the page's opening text sits on `StaticText` nodes, which
    /// `iter()` drops as browser-generated. Reading the window through it
    /// left only headings, and "little early text" fired on 1595 of 2731 real
    /// cached pages — each costing 20 points of Entry Clarity.
    #[test]
    fn a_page_that_opens_with_a_paragraph_has_early_text() {
        use crate::accessibility::AXTree;

        let mut root = node("root", "RootWebArea", Some("Seite"));
        root.child_ids = vec!["p".into()];
        let mut paragraph = node("p", "paragraph", None);
        paragraph.child_ids = vec!["p-text".into()];

        let tree = AXTree::from_nodes(vec![
            root,
            paragraph,
            node(
                "p-text",
                "StaticText",
                Some("Dieser Absatz steht ganz oben auf der Seite und ist gut lesbar."),
            ),
        ]);

        let analysis = analyze_journey(&tree);
        assert!(
            !analysis
                .friction_points
                .iter()
                .any(|f| matches!(f.kind, FrictionKind::LittleEarlyText)),
            "a page opening with a full paragraph has early text. Friction: {:?}",
            analysis
                .friction_points
                .iter()
                .map(|f| f.kind)
                .collect::<Vec<_>>(),
        );
    }

    /// Guard against German leaking into the canonical struct/JSON (#406): the
    /// analysis bakes English, so no visible result text (dimension summaries,
    /// friction problems/impacts/recommendations) may contain German umlauts/ß.
    #[test]
    fn canonical_struct_has_no_german_chars() {
        // Sparse tree: missing H1, no navigation, no <main>, no CTA, plus
        // unnamed links and buttons → triggers detectors across all dimensions.
        let mut nodes = vec![node("root", "RootWebArea", Some("Page"))];
        for i in 0..4 {
            nodes.push(node(&format!("link{i}"), "link", None));
        }
        for i in 0..3 {
            nodes.push(node(&format!("btn{i}"), "button", None));
        }
        let tree = AXTree::from_nodes(nodes);

        let analysis = analyze_journey(&tree);
        assert!(
            !analysis.friction_points.is_empty(),
            "scenario should produce friction points"
        );

        let has_umlaut = |s: &str| s.chars().any(|c| "äöüÄÖÜß".contains(c));

        for dim in [
            &analysis.entry_clarity,
            &analysis.orientation,
            &analysis.navigation,
            &analysis.interaction,
            &analysis.conversion,
        ] {
            assert!(
                !has_umlaut(&dim.name),
                "canonical dimension name contains German umlaut: {}",
                dim.name
            );
            assert!(
                !has_umlaut(&dim.summary),
                "canonical dimension summary contains German umlaut: {}",
                dim.summary
            );
        }

        for fp in &analysis.friction_points {
            assert!(
                !has_umlaut(&fp.problem),
                "canonical friction problem contains German umlaut: {}",
                fp.problem
            );
            assert!(
                !has_umlaut(&fp.impact),
                "canonical friction impact contains German umlaut: {}",
                fp.impact
            );
            assert!(
                !has_umlaut(&fp.recommendation),
                "canonical friction recommendation contains German umlaut: {}",
                fp.recommendation
            );
        }
    }

    /// PDF re-derivation: the pure text functions must yield real German.
    #[test]
    fn friction_text_german_for_pdf_derivation() {
        let (problem, impact, recommendation) = journey_friction_text(
            FrictionKind::NoH1,
            &FrictionValues::default(),
            false, // German
        );
        assert!(problem.contains("H1-Überschrift"));
        assert!(impact.contains("Nutzer"));
        assert!(recommendation.contains("aussagekräftige"));

        // A count-interpolated variant localizes too.
        let (problem, _, _) = journey_friction_text(
            FrictionKind::EmptyLinks,
            &FrictionValues { count: Some(3) },
            false,
        );
        assert_eq!(problem, "3 Links ohne erkennbaren Text");

        // Dimension summary localizes.
        assert_eq!(
            journey_dimension_summary(JourneyDimensionKind::Conversion, 95, false),
            "Klarer Conversion-Pfad mit erreichbarem CTA"
        );
    }
}