auditmysite 1.3.0

Resource-efficient WCAG 2.1 Accessibility Checker in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
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
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
//! Single-report page-section renderers for `generate_pdf`.
//!
//! Each function takes ownership of the builder, appends its section's
//! components, and returns the builder for further chaining.

use renderreport::components::advanced::{
    ChecklistPanel, ChecklistRow, DevicePreview, DiagnosisPanel, DiagnosisRow, Divider, List,
    MetricStrip, MetricStripItem, PageBreak, RecommendationCard, SectionHeaderSplit,
};
use renderreport::components::charts::{Chart, ChartType};
use renderreport::components::text::Label;
use renderreport::components::{AuditTable, CardDashboard, DashboardCard, Finding, TableColumn};
use renderreport::prelude::*;

use super::design;

use super::appendix::build_cli_snapshot_table;
use super::bik_guide::render_bik_guide_annex;
use super::detail_modules::{
    render_a11y_journey_findings, render_ai_transparency, render_ai_visibility,
    render_best_practices, render_budget_violations, render_commerce, render_content_visibility,
    render_dark_mode, render_design_quality, render_html_conform, render_journey, render_mobile,
    render_network_dns, render_performance, render_screen_reader_section, render_search_experience,
    render_security, render_seo, render_source_quality, render_tech_stack, render_ux,
    score_band_label,
};
use super::diagnosis::render_diagnosis_section;
use super::en301549::render_en301549_annex;
use super::findings::render_finding_technical;
use super::helpers::{
    manual_recheck_instruction, map_severity, priority_label_i18n, role_label_i18n,
};
use super::wcag_coverage::render_wcag_coverage_section;
use crate::audit::AuditReport;
use crate::cli::{AnnexKind, ReportLevel};
use crate::i18n::I18n;
use crate::output::module::active_report_modules;
use crate::output::report_model::*;

/// Render a part divider — visually separates the three report parts (#246).
///
/// Each divider produces a page break, a strong level=1 section header tagged
/// with "TEIL N / 3" (or "PART N OF 3"), an audience callout, and a contents list.
/// Part 3 is visually reinforced as a dedicated separator page before the technical
/// appendix and detailed evidence modules (plan/22-report-anhang-visual-cut.md).
pub(super) fn render_part_divider(
    mut builder: renderreport::engine::ReportBuilder,
    part_num: u8,
    title: &str,
    intro: &str,
    audience_title: &str,
    audience_body: &str,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let eyebrow = if en {
        if part_num == 3 {
            "PART 3 OF 3 · TECHNICAL APPENDIX".to_string()
        } else {
            format!("PART {} OF 3", part_num)
        }
    } else if part_num == 3 {
        "TEIL 3 VON 3 · TECHNISCHER ANHANG".to_string()
    } else {
        format!("TEIL {} VON 3", part_num)
    };
    if part_num > 1 {
        builder = builder.add_component(PageBreak::new());
    }
    builder = builder
        // Large chapter number — magazine-style opener.
        .add_component(
            Label::new(format!("{:02}", part_num))
                .with_size("72pt")
                .bold()
                .with_color(design::tokens::MUTED),
        )
        .add_component(
            SectionHeaderSplit::new(title, intro)
                .with_eyebrow(eyebrow)
                .with_level(1),
        )
        .add_component(
            Label::new(format!("{}: {}", audience_title, audience_body))
                .with_size("10.5pt")
                .with_color(design::tokens::NEUTRAL),
        );
    if part_num == 3 {
        builder = builder
            .add_component(Divider::thick().with_color(design::tokens::MUTED))
            .add_component(PageBreak::new());
    }
    builder
}

/// Scannable severity counter row for the executive dashboard — total findings
/// plus a critical/high/medium breakdown. Zero counts read as "all clear"
/// (green), non-zero counts carry their severity hue.
fn build_severity_counter_strip(vm: &ReportViewModel, i18n: &I18n) -> MetricStrip {
    let en = i18n.locale() == "en";
    let count_accent = |n: u32, hue: &'static str| {
        if n > 0 {
            hue
        } else {
            design::tokens::SUCCESS
        }
    };
    let items = vec![
        MetricStripItem::new(
            if en {
                "WCAG occurrences"
            } else {
                "WCAG-Vorkommen"
            },
            vm.severity.total.to_string(),
        )
        .with_accent(design::tokens::INK),
        MetricStripItem::new(
            if en { "Critical" } else { "Kritisch" },
            vm.severity.critical.to_string(),
        )
        .with_accent(count_accent(vm.severity.critical, design::tokens::DANGER)),
        MetricStripItem::new(
            if en { "High" } else { "Hoch" },
            vm.severity.high.to_string(),
        )
        .with_accent(count_accent(vm.severity.high, design::tokens::DANGER)),
        MetricStripItem::new(
            if en { "Medium" } else { "Mittel" },
            vm.severity.medium.to_string(),
        )
        .with_accent(count_accent(vm.severity.medium, design::tokens::WARN_DEEP)),
    ];
    MetricStrip::new(items).compact()
}

/// Build a dashboard card for one module, aligned with the report's grade bands
/// (good ≥ 75, watch 40–74, problem < 40). Carries the same non-normative
/// name-suffix qualifier as the cover gauges and the technical modules
/// overview for Heuristic/Optional-tier modules (#577).
fn module_dashboard_card(module: &ModuleScore, i18n: &I18n) -> DashboardCard {
    DashboardCard {
        name: super::helpers::module_name_with_taxonomy_suffix(
            &module.name,
            &module.measurement_type,
            i18n,
        ),
        score: module.score,
        interpretation: if module.interpretation.is_empty() {
            format!("{}/100", module.score)
        } else {
            module.interpretation.clone()
        },
        good_threshold: 75,
        warn_threshold: 40,
    }
}

/// "What works well" vs "Where optimization pays off" — splits the module
/// scores into two card groups so an unbriefed reader sees strengths and
/// priorities at a glance.
fn render_module_split_dashboards(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    // plan/7-management-summary-consolidation.md ("lighter" option): the
    // weighted, "measured" modules (Accessibility/Performance/Security/
    // Mobile/SEO) are now covered by the score-driver table above with more
    // detail (weight_pct + reasoning) — showing them a second time here as
    // strength/weakness cards was redundant. This dashboard now only covers
    // the composite/heuristic indicator modules (UX, Journey, Search
    // Experience, …) that the score-driver table deliberately excludes
    // (they don't feed the weighted overall score).
    let indicator_modules: Vec<&ModuleScore> = vm
        .modules
        .dashboard
        .iter()
        .filter(|m| m.measurement_type != "measured")
        .collect();
    let strong: Vec<DashboardCard> = indicator_modules
        .iter()
        .filter(|m| m.score >= 75)
        .map(|m| module_dashboard_card(m, i18n))
        .collect();
    let weak: Vec<DashboardCard> = indicator_modules
        .iter()
        .filter(|m| m.score < 75)
        .map(|m| module_dashboard_card(m, i18n))
        .collect();

    if !strong.is_empty() {
        builder = builder.add_component(CardDashboard::new(strong).with_title(if en {
            "What works particularly well"
        } else {
            "Was besonders gut funktioniert"
        }));
    }
    if !weak.is_empty() {
        builder = builder.add_component(CardDashboard::new(weak).with_title(if en {
            "Where optimization pays off"
        } else {
            "Wo sich Optimierung lohnt"
        }));
    } else if !indicator_modules.is_empty() {
        // Module *scores* (0-100 per module) are a different axis from the
        // risk-gated certificate (which can be downgraded to EINGESCHRÄNKT/
        // NICHT BESTANDEN by blocking operability issues or legal flags even
        // when every module score is >= 75 -- see gate_certificate_by_risk).
        // An unconditional "all good" claim here directly contradicted that
        // downgrade (confirmed live in satower-mosterei.de, 2026-08-31:
        // certificate EINGESCHRÄNKT / verdict fail / 4 blockers, right next
        // to "no module needs prioritized optimization"). Qualify the
        // message instead of suppressing it entirely, so the "module scores
        // are fine" observation stays but doesn't read as "nothing to fix".
        // Scoped to the indicator modules shown here — the weighted/measured
        // modules' status is the score-driver table's job, not this one's.
        let risk_gated = matches!(
            vm.summary.certificate.as_str(),
            "EINGESCHRÄNKT" | "NICHT BESTANDEN"
        );
        let message = if risk_gated {
            if en {
                "The additional indicator modules (UX, Journey, …) are in good shape, but operability/legal risk elsewhere in this report still requires action — see Management Summary."
            } else {
                "Die zusätzlichen Indikator-Module (UX, Journey, …) sind in gutem Zustand, dennoch besteht an anderer Stelle in diesem Report Bedienbarkeits- oder rechtliches Risiko, das Handeln erfordert — siehe Management-Zusammenfassung."
            }
        } else if en {
            "The additional indicator modules (UX, Journey, …) are in good shape — no module needs prioritized optimization."
        } else {
            "Die zusätzlichen Indikator-Module (UX, Journey, …) sind in gutem Zustand — kein Modul erfordert vorrangige Optimierung."
        };
        builder = builder.add_component(Label::new(message).with_size("10.5pt").with_color(
            if risk_gated {
                design::tokens::WARN_DEEP
            } else {
                design::tokens::SUCCESS
            },
        ));
    }
    builder
}

/// One of the five fixed report dimensions (Usability / Legal / Business /
/// SEO / Performance), evaluated to a status ("bad"/"warn"/"good") and a
/// localized description. Pure data — no rendering, no `ReportViewModel`
/// dependency — so the bucketing logic below is directly unit-testable.
struct DimensionRow {
    label: String,
    description: String,
    status: &'static str,
}

/// Evaluates the five fixed dimensions against their thresholds. Same
/// thresholds/wording as before #576 — only the presentation (which bucket
/// each row lands in, how 0..5 rows render) changed, not the scoring model.
#[allow(clippy::too_many_arguments)]
fn compute_dimension_rows(
    severity_critical: u32,
    severity_high: u32,
    cover_critical_issues: u32,
    summary_score: u32,
    seo_score: u32,
    perf_score: u32,
    mobile_score: u32,
    en: bool,
) -> Vec<DimensionRow> {
    let mut rows = Vec::with_capacity(5);

    // 1. Usability / Nutzbarkeit
    let user_desc = if severity_critical > 0 || severity_high > 0 {
        if en {
            "Screen reader and keyboard navigation blocked at critical points."
        } else {
            "Screenreader und Tastaturnavigation an kritischen Stellen blockiert oder beeinträchtigt."
        }
    } else {
        if en {
            "No major usability limitations detected."
        } else {
            "Keine wesentlichen Einschränkungen der Nutzbarkeit erkannt."
        }
    };
    // Status now completes the tier the description text already implies
    // ("no major limitations" is a positive result, not a warning) — the
    // numeric thresholds (critical/high counts) are unchanged (#576).
    let user_status = if severity_critical > 0 {
        "bad"
    } else if severity_high > 0 {
        "warn"
    } else {
        "good"
    };
    rows.push(DimensionRow {
        label: if en { "Usability" } else { "Nutzbarkeit" }.to_string(),
        description: user_desc.to_string(),
        status: user_status,
    });

    // 2. Compliance / Rechtliches
    let legal_desc = if cover_critical_issues > 0 {
        if en {
            "BFSG-relevant violations found (WCAG Level A/AA) — resolution recommended."
        } else {
            "BFSG-relevante Verstöße (WCAG Level A/AA) gefunden — Behebung empfohlen."
        }
    } else {
        if en {
            "Low compliance risk."
        } else {
            "Geringes Compliance-Risiko."
        }
    };
    // Two-tier text ("violations found" vs. "low risk") now maps to two
    // statuses instead of collapsing "low risk" into "warn" (#576).
    let legal_status = if cover_critical_issues > 0 {
        "bad"
    } else {
        "good"
    };
    rows.push(DimensionRow {
        label: if en {
            "Legal Conformance"
        } else {
            "Rechtliche Konformität (BFSG)"
        }
        .to_string(),
        description: legal_desc.to_string(),
        status: legal_status,
    });

    // 3. Conversion / Business-Risiko
    let business_desc = if summary_score < 60 {
        if en {
            "High risk of process abandonment and conversion loss."
        } else {
            "Hohes Risiko von Prozessabbrüchen und Conversion-Verlusten."
        }
    } else if summary_score < 80 {
        if en {
            "Usability hurdles may reduce conversion rate."
        } else {
            "Nutzungshürden können Conversion-Rate reduzieren."
        }
    } else {
        if en {
            "Low business risk, minor optimizations recommended."
        } else {
            "Geringes geschäftliches Risiko, kleine Optimierungen empfohlen."
        }
    };
    // Three-tier text (high risk / hurdles / low risk) now maps to three
    // statuses instead of collapsing "low risk, minor optimizations" into
    // "warn" (#576).
    let business_status = if summary_score < 60 {
        "bad"
    } else if summary_score < 80 {
        "warn"
    } else {
        "good"
    };
    rows.push(DimensionRow {
        label: if en {
            "Conversion & Business Risk"
        } else {
            "Conversion & Business-Risiko"
        }
        .to_string(),
        description: business_desc.to_string(),
        status: business_status,
    });

    // 4. SEO & AI Visibility
    let seo_desc = if seo_score < 70 {
        if en {
            "Missing metadata or structured schemas reduce search engine and AI crawlability."
        } else {
            "Fehlende Metadaten oder strukturierte Daten behindern Google- und KI-Crawler."
        }
    } else if seo_score < 90 {
        if en {
            "Some optimization potential for search engines and AI agents."
        } else {
            "Optimierungspotenzial für Suchmaschinen und KI-Agenten vorhanden."
        }
    } else {
        if en {
            "Excellent discoverability and schema definition."
        } else {
            "Sehr gute Auffindbarkeit und strukturierte Schema-Daten."
        }
    };
    let seo_status = if seo_score < 70 {
        "bad"
    } else if seo_score < 90 {
        "warn"
    } else {
        "good"
    };
    rows.push(DimensionRow {
        label: if en {
            "SEO & AI Visibility"
        } else {
            "SEO & KI-Sichtbarkeit"
        }
        .to_string(),
        description: seo_desc.to_string(),
        status: seo_status,
    });

    // 5. Loading & Mobile experience
    let speed_desc = if perf_score < 60 || mobile_score < 60 {
        if en {
            "High loading latency or touch target layout issues frustrate mobile visitors."
        } else {
            "Hohe Ladezeiten oder Touch-Target-Mängel frustrieren mobile Besucher."
        }
    } else if perf_score < 85 || mobile_score < 85 {
        if en {
            "Moderate performance bottlenecks on mobile networks."
        } else {
            "Mäßige Performance-Verzögerungen im Mobilfunknetz."
        }
    } else {
        if en {
            "Fast load speed and optimal responsive viewport."
        } else {
            "Schnelle Ladezeit und optimale responsive Darstellung."
        }
    };
    let speed_status = if perf_score < 60 || mobile_score < 60 {
        "bad"
    } else if perf_score < 85 || mobile_score < 85 {
        "warn"
    } else {
        "good"
    };
    rows.push(DimensionRow {
        label: if en {
            "Performance & Mobile"
        } else {
            "Ladezeit & Mobilfreundlichkeit"
        }
        .to_string(),
        description: speed_desc.to_string(),
        status: speed_status,
    });

    rows
}

/// Renders the risks block (only "bad"/"warn" dimensions, 0..5 rows,
/// zero-risk empty state when all dimensions are "good") and, directly
/// below it, a separate strengths block for the "good" dimensions (#576).
/// Replaces the previous `build_top_risks_checklist`, which unconditionally
/// rendered all 5 dimensions — including positive ones — under a fixed
/// "Die 5 wichtigsten Risiken" title.
pub(super) fn render_risks_and_strengths(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";

    let seo_score = vm
        .modules
        .dashboard
        .iter()
        .find(|m| m.name.contains("SEO"))
        .map(|m| m.score)
        .unwrap_or(100);
    let perf_score = vm
        .modules
        .dashboard
        .iter()
        .find(|m| m.name.contains("Performance") || m.name.contains("Ladezeit"))
        .map(|m| m.score)
        .unwrap_or(100);
    let mobile_score = vm
        .modules
        .dashboard
        .iter()
        .find(|m| m.name.contains("Mobile") || m.name.contains("Mobilfreundlichkeit"))
        .map(|m| m.score)
        .unwrap_or(100);

    let dimensions = compute_dimension_rows(
        vm.severity.critical,
        vm.severity.high,
        vm.cover.critical_issues,
        vm.summary.score,
        seo_score,
        perf_score,
        mobile_score,
        en,
    );

    let (mut risks, strengths): (Vec<DimensionRow>, Vec<DimensionRow>) =
        dimensions.into_iter().partition(|d| d.status != "good");
    // Within the risks block, "bad" outranks "warn" — a low-effort ordering
    // improvement by user impact without redesigning the dimension model.
    // `sort_by_key` is stable, so relative dimension order within each group
    // is preserved.
    risks.sort_by_key(|d| if d.status == "bad" { 0u8 } else { 1u8 });

    if risks.is_empty() {
        // Zero-risk empty state (#576) — reuses the same automated-scope
        // caveat mechanism/wording as the clean-run verdict callout (#572)
        // instead of inventing new phrasing.
        let (automated, total) = crate::wcag::coverage::coverage_stats();
        let empty_state = if en {
            format!(
                "No priority risks identified within the automated audit scope. This result applies to the automated audit scope only ({automated} of about {total} testable WCAG 2.1 AA criteria); criteria requiring manual review are listed in the appendix."
            )
        } else {
            format!(
                "Keine prioritären Risiken im automatisierten Prüfumfang erkannt. Diese Einschätzung bezieht sich ausschließlich auf den automatisierten Prüfumfang ({automated} von ca. {total} testbaren WCAG-2.1-AA-Kriterien); Kriterien mit manuellem Prüfbedarf sind im Anhang aufgeführt."
            )
        };
        builder = builder.add_component(Callout::success(&empty_state).with_title(if en {
            "Key Risks"
        } else {
            "Wichtigste Risiken"
        }));
    } else {
        let title = if en {
            format!("Key Risks ({} identified)", risks.len())
        } else {
            format!("Wichtigste Risiken ({} erkannt)", risks.len())
        };
        let rows: Vec<ChecklistRow> = risks
            .into_iter()
            .map(|d| ChecklistRow::new(d.label, d.description).with_status(d.status))
            .collect();
        builder = builder.add_component(ChecklistPanel::new(rows).with_title(title));
    }

    if !strengths.is_empty() {
        let rows: Vec<ChecklistRow> = strengths
            .into_iter()
            .map(|d| ChecklistRow::new(d.label, d.description).with_status("good"))
            .collect();
        builder = builder.add_component(ChecklistPanel::new(rows).with_title(if en {
            "Strengths within the audited scope"
        } else {
            "Stärken im geprüften Umfang"
        }));
    }

    builder
}

pub(super) fn build_top_measures_list(vm: &ReportViewModel, i18n: &I18n) -> List {
    let en = i18n.locale() == "en";
    let list_title = if en {
        "5 Key Measures"
    } else {
        "Die 5 wichtigsten Maßnahmen"
    };
    let mut list = List::new().with_title(list_title);

    for (idx, group) in vm.findings.top_findings.iter().take(5).enumerate() {
        let text = format!("{}. {}: {}", idx + 1, group.title, group.recommendation);
        list = list.add_item(&text);
    }

    if vm.findings.top_findings.is_empty() {
        let no_measures = if en {
            "No urgent actions required."
        } else {
            "Keine dringenden Maßnahmen erforderlich."
        };
        list = list.add_item(no_measures);
    }

    list
}

pub(super) fn render_management_page(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let mgt_title = if en {
        "Management Summary"
    } else {
        "Management-Sicht"
    };
    let mgt_subtitle = if en {
        "Overall status, key risks, prioritized actions, and leverage at a glance."
    } else {
        "Gesamtstatus, Hauptrisiken, wichtigste Maßnahmen und Hebel auf einen Blick."
    };

    builder = builder.add_component(
        SectionHeaderSplit::new(mgt_title, mgt_subtitle)
            .with_eyebrow(if en {
                "MANAGEMENT SUMMARY"
            } else {
                "MANAGEMENT-SUMMARY"
            })
            .with_level(1),
    );

    // Scope line (#575): this report only ever covers exactly one audited
    // URL, checked with both desktop and mobile viewports (the pipeline
    // always runs both — see `pipeline.rs`'s unconditional dual-viewport
    // pass), and never crawls the rest of the site. Stated explicitly and
    // prominently up front so findings/recommendations phrased around
    // "the audited page" further down aren't misread as domain-wide claims.
    let scope_line = if en {
        "Audited: 1 URL · Desktop and Mobile · no website crawl".to_string()
    } else {
        "Geprüft: 1 URL · Desktop und Mobile · kein Website-Crawl".to_string()
    };
    builder = builder.add_component(
        Label::new(scope_line)
            .with_size("10.5pt")
            .bold()
            .with_color(design::tokens::NEUTRAL),
    );

    // 1. Scannable severity counters — the 20-second top line
    builder = builder.add_component(build_severity_counter_strip(vm, i18n));
    // Short definition right at first use, so a reader doesn't have to reach
    // the methodology appendix to learn "Vorkommen" ≠ "distinct rule" — the
    // full breakdown (finding groups vs. occurrences, all categories) still
    // lives only in the appendix, this is just the one-line pointer (#572).
    builder = builder.add_component(
        Label::new(if en {
            "Occurrences = individual affected elements, not the number of distinct rules — see the appendix for the full breakdown."
        } else {
            "Vorkommen = einzelne betroffene Elemente, nicht die Anzahl unterschiedlicher Regeln — vollständige Aufschlüsselung im Anhang."
        })
        .with_size("8.5pt")
        .with_color(design::tokens::MUTED),
    );

    // 2. Overall verdict (the single core sentence)
    builder = builder.add_component(Callout::info(&vm.summary.verdict).with_title(if en {
        "Overall Verdict"
    } else {
        "Gesamturteil"
    }));

    // Problem profile badge (plan/20-problemprofil-badge.md)
    builder = render_problem_profile(builder, vm, i18n);

    // Surface a partial/insufficient audit run right here, not only in the
    // methodology appendix (#575-adjacent review finding, 2026-09-01): a
    // reader who never reaches the appendix must still see that the scores
    // above describe a downgraded run.
    if let Some(note) = &vm.summary.audit_quality_note {
        // Insufficient (failed rule checks) is a genuine data-quality problem
        // and stays a warning; Partial (a stability/retry budget hit) is a
        // normal automated-audit coverage limitation and is framed calmer,
        // as "Coverage" rather than "Audit Quality" (feedback: a plain
        // "audit incomplete" warning next to a clean run read as if the
        // tool itself had failed, see `audit_quality_severe`).
        let callout = if vm.summary.audit_quality_severe {
            Callout::warning(note).with_title(if en {
                "Audit Quality"
            } else {
                "Audit-Qualität"
            })
        } else {
            Callout::info(note).with_title(if en { "Coverage" } else { "Prüfabdeckung" })
        };
        builder = builder.add_component(callout);
    }
    // For a clean automated run (no findings), state the automated-scope
    // caveat directly alongside the headline verdict — not only in the
    // appendix — so "0 findings" doesn't read as a full WCAG conformance
    // claim (#572).
    if !vm.severity.has_issues {
        let (automated, total) = crate::wcag::coverage::coverage_stats();
        builder = builder.add_component(
            Label::new(if en {
                format!(
                    "This result applies to the automated audit scope only ({automated} of ~{total} testable WCAG 2.1 AA criteria); criteria requiring manual review are listed in the appendix."
                )
            } else {
                format!(
                    "Diese Einschätzung bezieht sich ausschließlich auf den automatisierten Prüfumfang ({automated} von ca. {total} testbaren WCAG-2.1-AA-Kriterien); Kriterien mit manuellem Prüfbedarf sind im Anhang aufgeführt."
                )
            })
            .with_size("9pt")
            .with_color(design::tokens::MUTED),
        );
    }

    // 2b. Quality profile radar — balance across all dimensions at a glance.
    let radar_data: Vec<(String, f64)> = vm
        .modules
        .dashboard
        .iter()
        .map(|m| {
            let short = m
                .name
                .split([' ', '&'])
                .next()
                .unwrap_or(m.name.as_str())
                .trim()
                .to_string();
            (short, m.score as f64)
        })
        .collect();
    if radar_data.len() >= 3 {
        builder = builder.add_component(
            Chart::new(
                if en {
                    "Quality profile"
                } else {
                    "Qualitätsprofil"
                },
                ChartType::Radar,
            )
            .add_series("scores", radar_data),
        );
    }

    // 2c. Score-driver table — the radar shows *balance*, this answers
    // "why is the overall score X": which modules pull it down vs.
    // stabilize it, and how much each one actually weighs
    // (plan/2-score-driver-breakdown.md).
    builder = render_score_driver_table(builder, vm, i18n);

    // 2d. Problem-concentration diagnosis — the bridge between the score
    // level above and the technical root-cause list on a later page: "how
    // concentrated are the occurrences on a few recurring causes"
    // (plan/3-problem-concentration-diagnosis-narrative.md).
    if let Some(note) = build_problem_concentration_note(vm, i18n) {
        builder = builder.add_component(Label::new(note).with_size("10.5pt"));
    }

    // 2d-bis. Additional score drivers beyond Accessibility — the note above
    // only explains the WCAG occurrences; on sites where Performance or
    // Security are equally significant drags on the overall score, they were
    // left unexplained next to their number in the table above (feedback:
    // management summary read as accessibility-only, e.g. "Performance 16"
    // and "Security 22" had no plain-language reason next to them).
    builder = render_additional_score_drivers(builder, vm, i18n);

    // 2e. Accessibility/Security sub-category breakdown — a low module
    // score explained at a finer grain than one number (plan/5-module-
    // accessibility-security-driver-detail.md).
    let en_label = if en {
        "Accessibility"
    } else {
        "Barrierefreiheit"
    };
    let accessibility_entries: Vec<(String, u32)> = vm
        .modules
        .accessibility_subcategory_scores
        .iter()
        .map(|s| (s.subcategory_kind.label(en).to_string(), s.score))
        .collect();
    builder = render_subcategory_breakdown(builder, en_label, &accessibility_entries, i18n);

    let security_label = if en { "Security" } else { "Sicherheit" };
    let security_entries: Vec<(String, u32)> = vm
        .modules
        .security_category_scores
        .iter()
        .map(|s| (s.category_kind.label(en).to_string(), s.score))
        .collect();
    builder = render_subcategory_breakdown(builder, security_label, &security_entries, i18n);

    // 3. Strengths vs. priorities as card groups
    builder = render_module_split_dashboards(builder, vm, i18n);

    // 4. Risks & strengths
    builder = render_risks_and_strengths(builder, vm, i18n);

    // 5. Measures
    builder = builder.add_component(build_top_measures_list(vm, i18n));

    builder
}

/// Number of top causes considered for the "problem concentration"
/// percentage (plan/3-problem-concentration-diagnosis-narrative.md's
/// suggested "kleinere, z. B. Top-4-Teilmenge" — deliberately smaller than
/// `ROOT_CAUSE_SHOWN` (6), which sizes the *list* further down, not this
/// one-sentence diagnosis).
const PROBLEM_CONCENTRATION_TOP_N: usize = 4;

/// Below this many total occurrences, "X% trace back to N recurring causes"
/// is statistically meaningless (e.g. "1 occurrence — 100% trace back to 1
/// recurring cause") — feedback: the concentration sentence read as
/// nonsensical/machine-generated on a near-clean audit. Below the threshold,
/// `build_problem_concentration_note` falls back to a plain occurrence count
/// instead, and `build_overall_leverage_note` is suppressed entirely.
const PROBLEM_CONCENTRATION_MIN_OCCURRENCES: usize = 3;

/// The raw numbers behind the "problem concentration" diagnosis
/// (plan/3-problem-concentration-diagnosis-narrative.md): how many
/// occurrences exist in total, how many of the top `PROBLEM_CONCENTRATION_TOP_N`
/// causes they concentrate into, and which cause is affected most. A single
/// calculation shared by two different sentences on two different pages
/// (`build_problem_concentration_note` for the Management Summary,
/// `build_overall_leverage_note` for the Action Plan, plan/7-management-
/// summary-consolidation.md) — same source number, not two independently
/// computed ones that could silently drift apart.
struct ProblemConcentration {
    total_occurrences: usize,
    top_n: usize,
    concentration_pct: i64,
    top1_title: String,
}

fn compute_problem_concentration(vm: &ReportViewModel) -> Option<ProblemConcentration> {
    // WCAG-only (`all_findings` also carries SEO findings, #406/report_model
    // doc comment) — matches `vm.severity.total` ("N WCAG occurrences" on the
    // cover/executive dashboard), so this sentence's total can't silently
    // diverge from the headline count a reader already saw (feedback:
    // "121 WCAG-Vorkommen" vs. "122 Vorkommen wurden erkannt" a page later).
    let mut findings: Vec<&FindingGroup> = vm
        .findings
        .all_findings
        .iter()
        .filter(|f| f.occurrence_count > 0 && !f.wcag_criterion.is_empty())
        .collect();
    if findings.is_empty() {
        return None;
    }
    findings.sort_by_key(|f| std::cmp::Reverse(f.occurrence_count));

    let total_occurrences: usize = findings.iter().map(|f| f.occurrence_count).sum();
    let top_n = findings.len().min(PROBLEM_CONCENTRATION_TOP_N);
    let top_occurrences: usize = findings[..top_n].iter().map(|f| f.occurrence_count).sum();
    let concentration_pct = if total_occurrences > 0 {
        (top_occurrences as f64 * 100.0 / total_occurrences as f64).round() as i64
    } else {
        0
    };

    Some(ProblemConcentration {
        total_occurrences,
        top_n,
        concentration_pct,
        top1_title: findings[0].title.clone(),
    })
}

/// Three-tier semantic condensation of the entire audit for the executive
/// summary, directly beneath the overall verdict (plan/20-problemprofil-badge.md).
/// Combines breadth (count of weighted modules scoring below 75) and systemics
/// (recurring WCAG problem concentration).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ProblemProfileKind {
    Punktuell,
    KonzentriertSystemisch,
    BreitSystemisch,
}

impl ProblemProfileKind {
    pub(super) fn label(&self, en: bool) -> &'static str {
        match self {
            Self::Punktuell => {
                if en {
                    "isolated"
                } else {
                    "punktuell"
                }
            }
            Self::KonzentriertSystemisch => {
                if en {
                    "concentrated & systemic"
                } else {
                    "konzentriert & systemisch"
                }
            }
            Self::BreitSystemisch => {
                if en {
                    "broad & systemic"
                } else {
                    "breit & systemisch"
                }
            }
        }
    }
}

/// Modules that contribute to the weighted overall score and fall below the "Good" band (< 75).
/// Sorted by drag impact descending ((100 - score) * weight). Supplementary context only (e.g.
/// deciding success-vs-info styling for an otherwise "isolated" profile) — NOT the breadth count
/// for the Problem-Profile tier itself, see `critical_contributing_modules`.
fn weak_contributing_modules(
    vm: &ReportViewModel,
) -> Vec<&crate::audit::normalized::ModuleScoreEntry> {
    let mut weak: Vec<&crate::audit::normalized::ModuleScoreEntry> = vm
        .modules
        .module_scores
        .iter()
        .filter(|m| m.contributes_to_overall && m.score < 75)
        .collect();
    weak.sort_by_key(|m| std::cmp::Reverse((100 - m.score) * m.weight_pct));
    weak
}

/// Modules that contribute to the weighted overall score and are "Kritisch" (< 40 — same
/// FIVE_BAND cutoff used elsewhere in the report, e.g. `score_band_label`). This, not the
/// broader < 75 "Good" band, decides how many modules "determine the need for action" for the
/// Problem-Profile breadth tiering (feedback 2026-09-07: the < 75 threshold pulled in merely
/// "Verbesserungswürdig" modules — e.g. Performance 64 / SEO 65 on inros-lackner.de — alongside
/// the two genuinely critical ones (Accessibility 20 / Security 30), producing "breit &
/// systemisch" where the real driver was two critical modules, not four weak ones).
/// Sorted by drag impact descending, same as `weak_contributing_modules`.
fn critical_contributing_modules(
    vm: &ReportViewModel,
) -> Vec<&crate::audit::normalized::ModuleScoreEntry> {
    let mut critical: Vec<&crate::audit::normalized::ModuleScoreEntry> = vm
        .modules
        .module_scores
        .iter()
        .filter(|m| m.contributes_to_overall && m.score < 40)
        .collect();
    critical.sort_by_key(|m| std::cmp::Reverse((100 - m.score) * m.weight_pct));
    critical
}

/// Pure classification function combining breadth (< 40 "Kritisch" module count) and systemics
/// (plan/20-problemprofil-badge.md).
pub(super) fn classify_problem_profile(vm: &ReportViewModel) -> ProblemProfileKind {
    let critical = critical_contributing_modules(vm);
    let critical_count = critical.len();
    let concentration = compute_problem_concentration(vm);
    let has_systemic_wcag = match &concentration {
        Some(c) => {
            c.total_occurrences > PROBLEM_CONCENTRATION_MIN_OCCURRENCES && c.concentration_pct >= 50
        }
        None => false,
    };

    if critical_count >= 3 {
        ProblemProfileKind::BreitSystemisch
    } else if critical_count == 2 || (critical_count == 1 && has_systemic_wcag) {
        ProblemProfileKind::KonzentriertSystemisch
    } else {
        ProblemProfileKind::Punktuell
    }
}

fn format_module_names(
    modules: &[&crate::audit::normalized::ModuleScoreEntry],
    i18n: &I18n,
) -> String {
    let en = i18n.locale() == "en";
    let names: Vec<String> = modules
        .iter()
        .map(|m| {
            let key = format!("module-{}", m.name.to_lowercase().replace(' ', "-"));
            let translated = i18n.t(&key);
            if translated == key {
                m.name.clone()
            } else {
                translated
            }
        })
        .collect();

    match names.len() {
        0 => String::new(),
        1 => names[0].clone(),
        2 => {
            if en {
                format!("{} and {}", names[0], names[1])
            } else {
                format!("{} und {}", names[0], names[1])
            }
        }
        _ => {
            let last = &names[names.len() - 1];
            let initial = names[..names.len() - 1].join(", ");
            if en {
                format!("{}, and {}", initial, last)
            } else {
                format!("{} und {}", initial, last)
            }
        }
    }
}

fn build_problem_profile_description(
    vm: &ReportViewModel,
    kind: ProblemProfileKind,
    i18n: &I18n,
) -> String {
    let en = i18n.locale() == "en";
    // Only "Kritisch" (< 40) modules are named as "determining the need for
    // action" — same set `classify_problem_profile` tiers on, so the badge
    // text and the tier it's attached to can't silently diverge (feedback
    // 2026-09-07: naming from the broader < 75 band pulled in merely
    // "Verbesserungswürdig" modules that didn't actually drive the tier).
    let critical_modules = critical_contributing_modules(vm);
    let concentration = compute_problem_concentration(vm);
    let has_systemic_wcag = match &concentration {
        Some(c) => {
            c.total_occurrences > PROBLEM_CONCENTRATION_MIN_OCCURRENCES && c.concentration_pct >= 50
        }
        None => false,
    };

    match kind {
        ProblemProfileKind::Punktuell => {
            if critical_modules.is_empty() {
                if en {
                    "Very good technical condition. Isolated local optimizations without structural problems.".to_string()
                } else {
                    "Sehr guter technischer Zustand. Einzelne lokale Optimierungen ohne strukturelles Problem.".to_string()
                }
            } else {
                let name = format_module_names(&critical_modules, i18n);
                if en {
                    format!("{name} determines the primary need for action. Isolated local optimizations without structural problems.")
                } else {
                    format!("{name} bestimmt den Handlungsbedarf. Einzelne lokale Optimierungen ohne strukturelles Problem.")
                }
            }
        }
        ProblemProfileKind::KonzentriertSystemisch => {
            let names = format_module_names(&critical_modules, i18n);
            let verb_plural = critical_modules.len() > 1;
            if has_systemic_wcag {
                if en {
                    let verb = if verb_plural {
                        "determine"
                    } else {
                        "determines"
                    };
                    format!("{names} {verb} the need for action. A large portion of the accessibility findings is concentrated in a few recurring patterns.")
                } else {
                    let verb = if verb_plural { "bestimmen" } else { "bestimmt" };
                    format!("{names} {verb} den Handlungsbedarf. Ein großer Teil der Accessibility-Befunde konzentriert sich auf wenige wiederkehrende Muster.")
                }
            } else if en {
                let verb = if verb_plural {
                    "determine"
                } else {
                    "determines"
                };
                format!(
                    "{names} {verb} the need for action while other technical areas remain stable."
                )
            } else {
                let verb = if verb_plural { "bestimmen" } else { "bestimmt" };
                format!("{names} {verb} den Handlungsbedarf bei ansonsten stabilen technischen Bereichen.")
            }
        }
        ProblemProfileKind::BreitSystemisch => {
            let names = format_module_names(&critical_modules, i18n);
            if names.is_empty() {
                if en {
                    "Multiple technical areas are affected simultaneously and require structural corrections.".to_string()
                } else {
                    "Mehrere technische Bereiche sind gleichzeitig betroffen und benötigen strukturelle Korrekturen.".to_string()
                }
            } else if en {
                format!("Multiple technical areas are affected simultaneously. In particular, {names} require structural corrections.")
            } else {
                format!("Mehrere technische Bereiche sind gleichzeitig betroffen. Besonders {names} benötigen strukturelle Korrekturen.")
            }
        }
    }
}

fn render_problem_profile(
    builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let kind = classify_problem_profile(vm);
    let title_prefix = if en {
        "Problem profile"
    } else {
        "Problemprofil"
    };
    let title = format!("{}: {}", title_prefix, kind.label(en));
    let desc = build_problem_profile_description(vm, kind, i18n);

    let callout = match kind {
        ProblemProfileKind::Punktuell => {
            // Context-only use of the broader < 75 band (not the < 40
            // "critical" band the tiering itself uses, see
            // `classify_problem_profile`): a lone merely-"Verbesserungswürdig"
            // module still earns an `info` callout instead of `success`, even
            // though it doesn't change the tier.
            if weak_contributing_modules(vm).is_empty() {
                Callout::success(desc).with_title(title)
            } else {
                Callout::info(desc).with_title(title)
            }
        }
        ProblemProfileKind::KonzentriertSystemisch => Callout::info(desc).with_title(title),
        ProblemProfileKind::BreitSystemisch => Callout::warning(desc).with_title(title),
    };
    builder.add_component(callout)
}

/// "N occurrences were found; ~X% trace back to M recurring causes,
/// especially <top cause>." — a single generated (not free LLM) sentence
/// bridging the score level above and the technical root-cause list further
/// down. Scope is Accessibility + SEO/Optimization combined (deliberate
/// choice, see the plan file's "Offene Frage" — broader than
/// `mandatory_root_causes`, which stays WCAG-only to match the "N
/// Accessibility-Befunde" header count it feeds).
fn build_problem_concentration_note(vm: &ReportViewModel, i18n: &I18n) -> Option<String> {
    let en = i18n.locale() == "en";
    let c = compute_problem_concentration(vm)?;
    if c.total_occurrences <= PROBLEM_CONCENTRATION_MIN_OCCURRENCES {
        return Some(if en {
            format!(
                "{} occurrence(s) were detected — too few to identify a recurring pattern.",
                c.total_occurrences
            )
        } else {
            format!(
                "Es wurden {} Vorkommen erkannt — zu wenige, um ein wiederkehrendes Muster abzuleiten.",
                c.total_occurrences
            )
        });
    }
    Some(if en {
        format!(
            "{} occurrences were detected. About {}% of them trace back to just {} recurring causes. Most affected: {}.",
            c.total_occurrences, c.concentration_pct, c.top_n, c.top1_title
        )
    } else {
        format!(
            "{} Vorkommen wurden erkannt. Rund {} % davon lassen sich auf {} wiederkehrende Ursachen zurückführen. Besonders betroffen: {}.",
            c.total_occurrences, c.concentration_pct, c.top_n, c.top1_title
        )
    })
}

/// Action-Plan-page framing of the same numbers, worded around leverage
/// rather than diagnosis: "fixing the top causes covers most of what's
/// listed below" (plan/7-management-summary-consolidation.md's suggested
/// "Die vier wichtigsten Ursachen erklären ca. 88 % der erkannten
/// WCAG-Vorkommen").
fn build_overall_leverage_note(vm: &ReportViewModel, i18n: &I18n) -> Option<String> {
    let en = i18n.locale() == "en";
    let c = compute_problem_concentration(vm)?;
    if c.total_occurrences <= PROBLEM_CONCENTRATION_MIN_OCCURRENCES {
        // Too few occurrences for a "top causes" leverage framing to be
        // meaningful (see `build_problem_concentration_note`) — the Action
        // Plan page already lists the few findings directly, so this bridge
        // sentence is simply omitted rather than restated at low counts.
        return None;
    }
    Some(if en {
        format!(
            "The {} most significant causes account for about {}% of the {} occurrences detected — addressing those first has the biggest leverage on the list below.",
            c.top_n, c.concentration_pct, c.total_occurrences
        )
    } else {
        format!(
            "Die {} wichtigsten Ursachen erklären rund {} % der {} erkannten Vorkommen — ihre Behebung hat die größte Hebelwirkung auf die folgende Liste.",
            c.top_n, c.concentration_pct, c.total_occurrences
        )
    })
}

/// "Why is the overall score X" — one compact row per module that actually
/// feeds the weighted `overall_score`, showing its score, its weight, and a
/// plain-language classification of whether it drags the overall score down
/// or stabilizes it (plan/2-score-driver-breakdown.md). Deliberately reads
/// `vm.modules.module_scores` (the canonical `ModuleScoreEntry` list, same
/// numbers `overall_score` is computed from) rather than
/// `vm.modules.dashboard` — the dashboard's cards are reshaped for
/// narrative presentation (e.g. "Search Experience" blends SEO with
/// heuristic AI-visibility signals into a composite score that is *not*
/// the raw SEO number actually carrying SEO's weight).
fn render_score_driver_table(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let contributing: Vec<&crate::audit::normalized::ModuleScoreEntry> = vm
        .modules
        .module_scores
        .iter()
        .filter(|m| m.contributes_to_overall)
        .collect();
    if contributing.len() < 2 {
        return builder;
    }

    // The "biggest weak point" is the module that pulls the overall score
    // down the hardest — that's a function of *both* how far below "Good"
    // it scores and how much weight it carries, not score alone. A 40%-
    // weighted module at 40/100 drags the overall score down far more than
    // a 10%-weighted module at 30/100, even though the latter's raw score
    // looks worse in isolation (the exact case this table exists to make
    // legible, see plan/2-score-driver-breakdown.md's "Accessibility 20 /
    // Security 30" example). Every other module scoring below the "Good"
    // band (>=75, reusing the shared FIVE_BAND cutoffs — no new threshold
    // logic) is a lesser but still real drag; everything at/above 75
    // stabilizes the overall score.
    let weakest_name = contributing
        .iter()
        .filter(|m| m.score < 75)
        .max_by_key(|m| (100 - m.score) * m.weight_pct)
        .map(|m| m.name.clone());

    let classify = |m: &crate::audit::normalized::ModuleScoreEntry| -> &'static str {
        if Some(&m.name) == weakest_name.as_ref() {
            if en {
                "Biggest weak point"
            } else {
                "Größter Schwachpunkt"
            }
        } else if m.score < 75 {
            if en {
                "Significant risk driver"
            } else {
                "Erheblicher Risikotreiber"
            }
        } else if en {
            "Stabilizes the overall score"
        } else {
            "Stabilisiert Gesamtwert"
        }
    };

    let mut table = AuditTable::new(vec![
        TableColumn::new(if en { "Module" } else { "Modul" }).with_width("28%"),
        TableColumn::new("Score").with_width("14%"),
        TableColumn::new(if en { "Weight" } else { "Gewichtung" }).with_width("16%"),
        TableColumn::new(if en { "Assessment" } else { "Einordnung" }).with_width("42%"),
    ])
    .with_title(if en {
        "Why is the overall score what it is"
    } else {
        "Warum ist der Gesamtwert, was er ist"
    });

    for m in &contributing {
        // Same lookup as `output::builder::helpers::localized_module_name`
        // (private to that module, so replicated here rather than exposed
        // just for this one call site): `module-<name>` Fluent key with the
        // canonical English name as a fallback.
        let key = format!("module-{}", m.name.to_lowercase().replace(' ', "-"));
        let translated = i18n.t(&key);
        let display_name = if translated == key {
            m.name.clone()
        } else {
            translated
        };
        table = table.add_row(vec![
            display_name,
            format!("{} ({})", m.score, score_band_label(m.score, i18n)),
            format!("{}%", m.weight_pct),
            classify(m).to_string(),
        ]);
    }

    builder = builder.add_component(table);
    builder
}

/// One plain-language reason per non-Accessibility score driver (SEO,
/// Security, Tech complexity/Performance) — reuses the bullets already
/// computed by `interpretation::build_technical_overview_localized`
/// (`vm.summary.technical_overview`), which is always exactly
/// `[accessibility, seo, security, tech]` followed by any cross-impact notes.
/// Bullet 0 (Accessibility) is skipped here — it's already covered by the
/// WCAG root-cause note directly above this table (#2d).
fn render_additional_score_drivers(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    if vm.summary.technical_overview.len() < 4 {
        return builder;
    }
    let mut list = List::new().with_title(if en {
        "Additional score drivers"
    } else {
        "Weitere Score-Treiber"
    });
    for item in &vm.summary.technical_overview[1..4] {
        list = list.add_item(item);
    }
    builder = builder.add_component(list);
    builder
}

/// Splits a list of `(label, score)` pairs into "critical weaknesses"
/// (below the shared FIVE_BAND "Verbesserungswürdig"/"Needs improvement"
/// cutoff at 60 — no new threshold invented) and "comparatively stable",
/// then renders a compact callout per module, matching the review's own
/// example format (plan/5-module-accessibility-security-driver-detail.md
/// and plan/21-accessibility-subcategory-breakdown-uniform-gap.md).
/// Handles both contrast (two-line) and uniform (single-line) distributions;
/// renders nothing only for an empty input (module didn't run).
fn render_subcategory_breakdown(
    mut builder: renderreport::engine::ReportBuilder,
    title: &str,
    entries: &[(String, u32)],
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    if entries.is_empty() {
        return builder;
    }
    const STABLE_CUTOFF: f32 = 60.0; // registry::FIVE_BAND's "Needs improvement" cutoff

    let mut weak: Vec<&(String, u32)> = entries
        .iter()
        .filter(|(_, score)| (*score as f32) < STABLE_CUTOFF)
        .collect();
    let mut stable: Vec<&(String, u32)> = entries
        .iter()
        .filter(|(_, score)| (*score as f32) >= STABLE_CUTOFF)
        .collect();
    if weak.is_empty() && stable.is_empty() {
        return builder;
    }
    weak.sort_by_key(|(_, score)| *score);
    stable.sort_by_key(|(_, score)| std::cmp::Reverse(*score));

    let render_side = |items: &[&(String, u32)]| -> String {
        items
            .iter()
            .map(|(name, score)| format!("{name} {score}"))
            .collect::<Vec<_>>()
            .join(" · ")
    };

    // "Stronger sub-areas within {title}" rather than "comparatively stable"
    // (feedback 2026-09-07): at an overall score of e.g. 20, a subcategory at
    // 67 read as "stable" on its own, contradicting the module's headline
    // "Kritisch" grade a few lines above. Framing it as relative-within-the-
    // module keeps the same information without the contradiction.
    let body = if !weak.is_empty() && !stable.is_empty() {
        if en {
            format!(
                "Critical weaknesses: {}\nStronger sub-areas within {title}: {}",
                render_side(&weak),
                render_side(&stable)
            )
        } else {
            format!(
                "Kritische Schwächen: {}\nStärkere Teilbereiche innerhalb der {title}: {}",
                render_side(&weak),
                render_side(&stable)
            )
        }
    } else if !weak.is_empty() {
        if en {
            format!("Critical weaknesses: {}", render_side(&weak))
        } else {
            format!("Kritische Schwächen: {}", render_side(&weak))
        }
    } else if en {
        format!(
            "Stronger sub-areas within {title}: {}",
            render_side(&stable)
        )
    } else {
        format!(
            "Stärkere Teilbereiche innerhalb der {title}: {}",
            render_side(&stable)
        )
    };
    builder = builder.add_component(Callout::info(body).with_title(title));
    builder
}

/// Sections 5b + 6+ — diagnosis, findings by severity tier, module metrics, appendix.
pub(super) fn render_tech_details(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    report: &AuditReport,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";

    // Technical modules overview DiagnosisPanel
    if !vm.modules.dashboard.is_empty() {
        let diag_rows: Vec<DiagnosisRow> = vm
            .modules
            .dashboard
            .iter()
            .map(|module| {
                let status = if module.score >= 80 {
                    "good"
                } else if module.score >= 50 {
                    "warn"
                } else {
                    "bad"
                };
                let display_name = super::helpers::module_name_with_taxonomy_suffix(
                    &module.name,
                    &module.measurement_type,
                    i18n,
                );
                DiagnosisRow::new(&display_name, format!("{}/100", module.score))
                    .with_status(status)
            })
            .collect();
        builder = builder.add_component(
            DiagnosisPanel::new(diag_rows).with_title(i18n.t("panel-modules-overview")),
        );
    }

    if vm.severity.has_issues {
        builder = render_diagnosis_section(builder, &vm.diagnosis, i18n);
    }
    // Element-evidence crop temp files are named `ams-evidence-{ts}-{n}.png`,
    // keyed off the report timestamp (matches `cleanup_screenshot_temps`'s
    // desktop/mobile naming) plus a per-report sequence number.
    let report_ts = report.timestamp.timestamp_nanos_opt().unwrap_or(0);
    let mut evidence_seq: usize = 0;
    let mut acronyms_expanded = false;
    builder = render_findings_section(
        builder,
        vm,
        en,
        i18n,
        report_ts,
        &mut evidence_seq,
        &mut acronyms_expanded,
    );

    // Interactive Accessibility-Journey findings (Phase 2+)
    if !report.interactive_findings.is_empty() {
        builder = render_a11y_journey_findings(
            builder,
            &report.interactive_findings,
            report.accessibility_journey.as_ref(),
            i18n,
        );
    }

    // Screen-reader reading-order audit (#411)
    if let Some(sr) = report.screen_reader_audit.as_ref() {
        builder = render_screen_reader_section(builder, sr, report.patterns.as_ref(), i18n);
    }

    builder
}

pub(super) fn render_appendix_full(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    report: &AuditReport,
    findings: &[crate::audit::normalized::NormalizedFinding],
    config: &ReportConfig,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let (app_title, app_intro) = if en {
        (
            "Appendix & Methodology",
            "Technical scope, methodology, WCAG coverage, and the complete violations list.",
        )
    } else {
        (
            "Anhang & Methodik",
            "Prüfumfang, Methodik, WCAG-Coverage und die vollständige Fundstellenliste.",
        )
    };
    builder = builder.add_component(PageBreak::new()).add_component(
        SectionHeaderSplit::new(app_title, app_intro)
            .with_eyebrow(if en { "APPENDIX" } else { "ANHANG" })
            .with_level(1),
    );

    // WCAG Coverage (issue #37)
    if vm.meta.report_level != ReportLevel::Executive {
        builder = render_wcag_coverage_section(builder, report, i18n);
        builder = render_manual_only_criteria_note(builder, i18n);

        // EN 301 549 clause annex — opt-in only (see `--annex en301549`).
        if config.annex == Some(AnnexKind::En301549) {
            builder = render_en301549_annex(
                builder,
                findings,
                &report.accessibility.wcag_results.rule_outcomes,
                i18n,
            );
        }

        // BIK-für-Alle guide chapter mapping — opt-in only (see `--annex bik`).
        if config.annex == Some(AnnexKind::Bik) {
            let design_quality_findings: &[crate::design_quality::DesignQualityFinding] = report
                .experience
                .design_quality
                .as_ref()
                .map(|m| m.findings.as_slice())
                .unwrap_or(&[]);
            let seo_technical_issues: Vec<crate::seo::technical::TechnicalIssue> = report
                .discoverability
                .seo
                .as_ref()
                .map(|s| crate::seo::collect_technical_issues(&s.technical, en))
                .unwrap_or_default();
            let easy_language_detected = report
                .patterns
                .as_ref()
                .is_some_and(|p| p.recognized.iter().any(|r| r.pattern == "EasyLanguage"));
            let screen_reader_issues: &[crate::screen_reader::SrAuditIssue] = report
                .screen_reader_audit
                .as_ref()
                .map(|sr| sr.issues.as_slice())
                .unwrap_or(&[]);
            let accessibility_assessments =
                crate::audit::normalized::normalize_assessments(&report.accessibility.wcag_results);
            builder = render_bik_guide_annex(
                builder,
                findings,
                &report.interactive_findings,
                screen_reader_issues,
                design_quality_findings,
                &seo_technical_issues,
                easy_language_detected,
                &accessibility_assessments,
                i18n,
            );
        }
    }

    builder = render_assessment_and_execution_notes(builder, report, i18n);

    // Methodology / disclaimer text blocks
    let limitations_title = i18n.t("callout-limitations-title");
    let limitations_text = format!("{}: {}", limitations_title, vm.methodology.limitations);
    builder = builder.add_component(
        Label::new(&limitations_text)
            .with_size("10.5pt")
            .with_color("#475569"),
    );

    let disclaimer_title = i18n.t("callout-note-title");
    let disclaimer_text = format!("{}: {}", disclaimer_title, vm.methodology.disclaimer);
    builder = builder.add_component(
        Label::new(&disclaimer_text)
            .with_size("10.5pt")
            .with_color("#475569"),
    );

    // Complete violations list
    builder = render_appendix_section(builder, vm, i18n);

    builder
}

/// Fixed list (plan/15) of WCAG A/AA criteria that stay outside automated
/// testing on structural grounds, not merely "not yet implemented" — the
/// contentual sensibleness of a focus order (2.4.3), the intelligibility of
/// an error message (3.3.1), the practical usability of 400% zoom (1.4.4/
/// 1.4.10), the factual correctness of an alt text (1.1.1) or a video's
/// caption/transcript summary (1.2.1/1.2.2) can never be judged from markup
/// alone, however good the tool. Deliberately not derived from this page's
/// findings (unlike the EN 301 549/BIK annexes) — a 0-finding report would
/// otherwise leave this fully invisible, which is exactly the transparency
/// gap this section closes. Renders unconditionally (no `--annex` flag),
/// same report-level gate as the WCAG coverage section it follows.
fn render_manual_only_criteria_note(
    builder: renderreport::engine::ReportBuilder,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let rows = if en {
        vec![
            ChecklistRow::new(
                "2.4.3 · Focus Order",
                "Whether the technical focus order makes sense in context depends on the page's \
                 content and cannot be assessed automatically.",
            ),
            ChecklistRow::new(
                "3.3.1 · Error Identification",
                "Whether an error message is actually understandable to people is a content \
                 question, not a structural check.",
            ),
            ChecklistRow::new(
                "1.4.4 / 1.4.10 · Resize Text & Reflow",
                "Whether the page stays practically usable at 400% zoom goes beyond the \
                 technical reflow structure and requires manual review.",
            ),
            ChecklistRow::new(
                "1.1.1 · Non-text Content",
                "Whether alt text correctly describes the image content can only be judged by \
                 a person; automated checks can only confirm that alt text is present at all.",
            ),
            ChecklistRow::new(
                "1.2.1 / 1.2.2 · Time-based Media",
                "Whether a caption or transcript summary correctly reflects a video's content \
                 cannot be checked automatically.",
            ),
        ]
    } else {
        vec![
            ChecklistRow::new(
                "2.4.3 · Fokusreihenfolge",
                "Ob die technische Fokusreihenfolge inhaltlich sinnvoll ist, hängt vom \
                 Seitenaufbau ab und lässt sich nicht automatisiert bewerten.",
            ),
            ChecklistRow::new(
                "3.3.1 · Fehlerkennzeichnung",
                "Ob eine Fehlermeldung für Menschen tatsächlich verständlich ist, ist eine \
                 inhaltliche Frage und kein struktureller Check.",
            ),
            ChecklistRow::new(
                "1.4.4 / 1.4.10 · Textgröße & Reflow",
                "Ob die Seite bei 400 % Zoom praktisch bedienbar bleibt, geht über die \
                 technische Reflow-Struktur hinaus und erfordert eine manuelle Prüfung.",
            ),
            ChecklistRow::new(
                "1.1.1 · Nicht-Text-Inhalte",
                "Ob ein Alternativtext den Bildinhalt korrekt beschreibt, kann nur ein Mensch \
                 beurteilen; automatisiert prüfbar ist nur, ob überhaupt ein Alternativtext \
                 vorhanden ist.",
            ),
            ChecklistRow::new(
                "1.2.1 / 1.2.2 · Zeitbasierte Medien",
                "Ob eine Untertitel- oder Transkript-Zusammenfassung den Videoinhalt inhaltlich \
                 korrekt wiedergibt, lässt sich nicht automatisiert prüfen.",
            ),
        ]
    };
    builder.add_component(ChecklistPanel::new(rows).with_title(if en {
        "Structurally manual-only criteria"
    } else {
        "Strukturell nur manuell prüfbare Kriterien"
    }))
}

fn render_assessment_and_execution_notes(
    mut builder: renderreport::engine::ReportBuilder,
    report: &AuditReport,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let wcag = &report.accessibility.wcag_results;
    if !wcag.warnings.is_empty() || !wcag.not_testables.is_empty() {
        let mut rows = Vec::new();
        for finding in wcag.not_testables.iter().take(20) {
            let mut recommendation = finding
                .rule_id
                .as_deref()
                .and_then(crate::output::explanations::get_explanation)
                .or_else(|| crate::output::explanations::get_explanation(&finding.rule))
                .map(|explanation| explanation.recommendation_for(i18n.locale()).to_string())
                .unwrap_or_else(|| {
                    if en {
                        "Verify this criterion manually on the rendered page.".to_string()
                    } else {
                        "Dieses Kriterium manuell an der gerenderten Seite prüfen.".to_string()
                    }
                });
            if let Some(instruction) = manual_recheck_instruction(&finding.rule, en) {
                recommendation.push(' ');
                recommendation.push_str(instruction);
            }
            rows.push(
                ChecklistRow::new(
                    format!(
                        "{} · {}",
                        finding.rule,
                        if en {
                            "Manual review"
                        } else {
                            "Manuelle Prüfung"
                        }
                    ),
                    recommendation,
                )
                .with_status("warn"),
            );
        }
        for finding in wcag
            .warnings
            .iter()
            .take(20usize.saturating_sub(rows.len()))
        {
            let mut text = finding
                .rule_id
                .as_deref()
                .and_then(crate::output::explanations::get_explanation)
                .or_else(|| crate::output::explanations::get_explanation(&finding.rule))
                .map(|explanation| explanation.recommendation_for(i18n.locale()).to_string())
                .unwrap_or_else(|| {
                    if en {
                        "Confirm this heuristic signal manually.".to_string()
                    } else {
                        "Dieses heuristische Signal manuell bestätigen.".to_string()
                    }
                });
            if let Some(instruction) = manual_recheck_instruction(&finding.rule, en) {
                text.push(' ');
                text.push_str(instruction);
            }
            rows.push(
                ChecklistRow::new(
                    format!(
                        "{} · {}",
                        finding.rule,
                        if en { "Warning" } else { "Hinweis" }
                    ),
                    text,
                )
                .with_status("warn"),
            );
        }
        builder = builder.add_component(ChecklistPanel::new(rows).with_title(if en {
            "Manual review and heuristic signals"
        } else {
            "Manuelle Prüfpunkte und heuristische Hinweise"
        }));
    }

    if let Some(journey) = report.accessibility_journey.as_ref() {
        let execution = &journey.execution;
        let text = if en {
            format!(
                "Interactive coverage: {} of {} attempted journeys completed; {} failed, {} skipped{}.",
                execution.completed,
                execution.attempted,
                execution.failed,
                execution.skipped,
                if execution.budget_exhausted { "; budget exhausted" } else { "" }
            )
        } else {
            format!(
                "Interaktive Abdeckung: {} von {} versuchten Journeys abgeschlossen; {} fehlgeschlagen, {} übersprungen{}.",
                execution.completed,
                execution.attempted,
                execution.failed,
                execution.skipped,
                if execution.budget_exhausted { "; Budget ausgeschöpft" } else { "" }
            )
        };
        builder = builder.add_component(Label::new(text).with_size("10.5pt").with_color("#475569"));
    }

    builder
}

fn render_findings_section(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    en: bool,
    i18n: &I18n,
    report_ts: i64,
    evidence_seq: &mut usize,
    acronyms_expanded: &mut bool,
) -> renderreport::engine::ReportBuilder {
    if vm.severity.has_issues {
        let (findings_title, findings_intro) = if en {
            (
                "Classification of Findings",
                "All technical findings, categorized by systemic template relevance and individual page occurrences.",
            )
        } else {
            (
                "Klassifizierung der Befunde",
                "Alle technischen Befunde, getrennt nach systemischen Komponentenfehlern und Einzelfällen.",
            )
        };
        builder = builder.add_component(PageBreak::new()).add_component(
            SectionHeaderSplit::new(findings_title, findings_intro)
                .with_eyebrow(if en { "FINDINGS" } else { "BEFUNDE" })
                .with_level(2),
        );

        let all_findings = &vm.findings.all_findings;

        let systemic_mandatory: Vec<&FindingGroup> = all_findings
            .iter()
            .filter(|f| f.is_component_issue && f.criticality_tier == CriticalityTier::Mandatory)
            .collect();

        let systemic_optimization: Vec<&FindingGroup> = all_findings
            .iter()
            .filter(|f| f.is_component_issue && f.criticality_tier == CriticalityTier::Optimization)
            .collect();

        let local_mandatory: Vec<&FindingGroup> = all_findings
            .iter()
            .filter(|f| !f.is_component_issue && f.criticality_tier == CriticalityTier::Mandatory)
            .collect();

        let local_optimization: Vec<&FindingGroup> = all_findings
            .iter()
            .filter(|f| {
                !f.is_component_issue && f.criticality_tier == CriticalityTier::Optimization
            })
            .collect();

        // Overview row so the classification header carries substance instead of
        // sitting alone on an otherwise blank page. One tile per rendered
        // category below (rather than two combined totals) so each number
        // maps 1:1 to the heading it belongs to — a combined "Einzelfälle"
        // total previously hid the fact that its optimization share is
        // rendered chapters later under a differently-named heading (#local
        // vs. #systemic classification page).
        builder = builder.add_component(
            MetricStrip::new(vec![
                MetricStripItem::new(
                    if en {
                        "Systemic (mandatory)"
                    } else {
                        "Systemisch (Pflicht)"
                    },
                    systemic_mandatory.len().to_string(),
                )
                .with_accent(if !systemic_mandatory.is_empty() {
                    design::tokens::INFO
                } else {
                    design::tokens::SUCCESS
                }),
                MetricStripItem::new(
                    if en {
                        "Systemic (optimization)"
                    } else {
                        "Systemisch (Optimierung)"
                    },
                    systemic_optimization.len().to_string(),
                )
                .with_accent(design::tokens::NEUTRAL),
                MetricStripItem::new(
                    if en {
                        "Local (mandatory)"
                    } else {
                        "Lokal (Pflicht)"
                    },
                    local_mandatory.len().to_string(),
                )
                .with_accent(if !local_mandatory.is_empty() {
                    design::tokens::INFO
                } else {
                    design::tokens::SUCCESS
                }),
                MetricStripItem::new(
                    if en {
                        "Local (optimization)"
                    } else {
                        "Lokal (Optimierung)"
                    },
                    local_optimization.len().to_string(),
                )
                .with_accent(design::tokens::NEUTRAL),
            ])
            .compact(),
        );

        // Findings matrix (#570): a single compact table listing every finding
        // group across all four buckets, sorted worst-first, so a reader can
        // prioritize and locate a specific finding without paging through the
        // full set of detail cards that follow below. Purely additive — does
        // not replace or alter the per-category cards rendered afterward.
        const FINDINGS_MATRIX_MAX_ROWS: usize = 30;

        let mut matrix_findings: Vec<&FindingGroup> = all_findings.iter().collect();
        matrix_findings.sort_by(|a, b| {
            b.priority
                .cmp(&a.priority)
                .then_with(|| b.occurrence_count.cmp(&a.occurrence_count))
        });

        if !matrix_findings.is_empty() {
            let (matrix_title, matrix_intro) = if en {
                (
                    "Findings Matrix",
                    "One row per finding group, sorted by priority — an overview to prioritize by before the detail cards below expand on each row.",
                )
            } else {
                (
                    "Befundmatrix",
                    "Eine Zeile je Befundgruppe, sortiert nach Priorität – als Überblick zur Priorisierung, bevor die Detailkarten unten jede Zeile vertiefen.",
                )
            };
            builder = builder.add_component(Label::new(matrix_intro).with_size("10.5pt"));

            let mut table = AuditTable::new(vec![
                TableColumn::new(if en { "Priority" } else { "Priorität" }).with_width("10%"),
                TableColumn::new("WCAG").with_width("10%"),
                TableColumn::new(if en { "Finding" } else { "Befund" }).with_width("28%"),
                TableColumn::new(if en { "Scope" } else { "Umfang" }).with_width("14%"),
                TableColumn::new(if en { "Responsible" } else { "Zuständig" }).with_width("14%"),
                TableColumn::new(if en { "Action" } else { "Maßnahme" }).with_width("24%"),
            ])
            .with_title(matrix_title);

            for group in matrix_findings.iter().take(FINDINGS_MATRIX_MAX_ROWS) {
                let wcag = if group.wcag_criterion.is_empty() {
                    "n/a".to_string()
                } else if group.wcag_level.is_empty() {
                    group.wcag_criterion.clone()
                } else {
                    format!("{} ({})", group.wcag_criterion, group.wcag_level)
                };
                let scope = if group.is_component_issue {
                    if en {
                        format!("Systemic · {}", group.occurrence_count)
                    } else {
                        format!("Systemisch · {}", group.occurrence_count)
                    }
                } else if en {
                    format!("Local · {}", group.occurrence_count)
                } else {
                    format!("Lokal · {}", group.occurrence_count)
                };
                table = table.add_row(vec![
                    priority_label_i18n(group.priority, i18n),
                    wcag,
                    truncate_title(&group.title, 48),
                    scope,
                    role_label_i18n(group.responsible_role, i18n),
                    truncate_title(&group.recommendation, 72),
                ]);
            }
            builder = builder.add_component(table);

            let remaining = matrix_findings
                .len()
                .saturating_sub(FINDINGS_MATRIX_MAX_ROWS);
            if remaining > 0 {
                let note = if en {
                    format!("{remaining} further findings are listed in the detail cards below.")
                } else {
                    format!(
                        "{remaining} weitere Befunde sind in den Detailkarten unten aufgeführt."
                    )
                };
                builder = builder.add_component(
                    Label::new(note)
                        .with_size("9pt")
                        .with_color(design::tokens::NEUTRAL),
                );
            }
        }

        // The first rendered category flows directly under the classification
        // header; only later categories start on a fresh page.
        let mut rendered_categories = 0usize;

        // 1. Systemic Mandatory
        if !systemic_mandatory.is_empty() {
            let title = if en {
                "Systemic Template & Component Issues (WCAG A/AA)"
            } else {
                "Systemische Template- & Komponentenfehler (WCAG A/AA)"
            };
            let desc = if en {
                "This pattern suggests a reused component or template — confirming that requires evidence from additional pages. A central fix would likely also resolve the cause on other pages sharing the same pattern."
            } else {
                "Dieses Muster deutet auf eine wiederverwendete Komponente oder Vorlage hin — bestätigt ist das erst mit Belegen von weiteren Seiten. Eine zentrale Behebung würde die Ursache voraussichtlich auch auf anderen Seiten mit demselben Muster beheben."
            };
            if rendered_categories > 0 {
                builder = builder.add_component(PageBreak::new());
            }
            rendered_categories += 1;
            builder = builder.add_component(
                SectionHeaderSplit::new(title, desc)
                    .with_eyebrow(if en {
                        "SYSTEMIC COMPLIANCE"
                    } else {
                        "SYSTEMISCHE PFLICHT"
                    })
                    .with_level(2),
            );
            for group in systemic_mandatory {
                builder = render_finding_technical(
                    builder,
                    group,
                    i18n,
                    report_ts,
                    evidence_seq,
                    acronyms_expanded,
                );
            }
        }

        // 2. Systemic Optimization
        if !systemic_optimization.is_empty() {
            let title = if en {
                "Systemic Quality & SEO Optimizations"
            } else {
                "Systemische Qualitäts- & SEO-Optimierungen"
            };
            let desc = if en {
                "These recommendations recur within this single page, which suggests a shared template — confirming that would require checking additional pages."
            } else {
                "Diese Empfehlungen wiederholen sich innerhalb dieser einen Seite, was auf eine gemeinsame Vorlage hindeutet — bestätigt ist das erst nach Prüfung weiterer Seiten."
            };
            if rendered_categories > 0 {
                builder = builder.add_component(PageBreak::new());
            }
            rendered_categories += 1;
            builder = builder.add_component(
                SectionHeaderSplit::new(title, desc)
                    .with_eyebrow(if en {
                        "SYSTEMIC OPTIMIZATION"
                    } else {
                        "SYSTEMISCHE OPTIMIERUNG"
                    })
                    .with_level(2),
            );
            for group in systemic_optimization {
                builder = render_finding_technical(
                    builder,
                    group,
                    i18n,
                    report_ts,
                    evidence_seq,
                    acronyms_expanded,
                );
            }
        }

        // 3. Local Mandatory
        if !local_mandatory.is_empty() {
            let title = if en {
                "Local & Editorial Findings (WCAG A/AA)"
            } else {
                "Einzelfälle & Redaktionelle Befunde (WCAG A/AA)"
            };
            let desc = if en {
                "Single instances of accessibility barriers affecting specific pages, images, or editorial content, usually requiring individual resolution."
            } else {
                "Punktuelle Barrieren, die nur einzelne Seiten, spezifische Bilder oder redaktionelle Texte betreffen und meist individuell behoben werden müssen."
            };
            if rendered_categories > 0 {
                builder = builder.add_component(PageBreak::new());
            }
            rendered_categories += 1;
            builder = builder.add_component(
                SectionHeaderSplit::new(title, desc)
                    .with_eyebrow(if en {
                        "LOCAL COMPLIANCE"
                    } else {
                        "LOKALE PFLICHT"
                    })
                    .with_level(2),
            );
            for group in local_mandatory {
                builder = render_finding_technical(
                    builder,
                    group,
                    i18n,
                    report_ts,
                    evidence_seq,
                    acronyms_expanded,
                );
            }
        }

        // 4. Local Optimization
        if !local_optimization.is_empty() {
            let title = if en {
                "Additional Quality & SEO Recommendations"
            } else {
                "Ergänzende Qualitäts- & SEO-Empfehlungen"
            };
            let desc = if en {
                "Usability, performance, or SEO recommendations for specific pages."
            } else {
                "Ergänzende Empfehlungen zur Verbesserung der Ladezeiten, Suchmaschinenoptimierung und Benutzerfreundlichkeit auf bestimmten Seiten."
            };
            if rendered_categories > 0 {
                builder = builder.add_component(PageBreak::new());
            }
            rendered_categories += 1;
            builder = builder.add_component(
                SectionHeaderSplit::new(title, desc)
                    .with_eyebrow(if en {
                        "LOCAL OPTIMIZATION"
                    } else {
                        "LOKALE OPTIMIERUNG"
                    })
                    .with_level(2),
            );
            for group in local_optimization {
                builder = render_finding_technical(
                    builder,
                    group,
                    i18n,
                    report_ts,
                    evidence_seq,
                    acronyms_expanded,
                );
            }
        }
        let _ = rendered_categories; // last write is intentional; silence dead-store lint
    }
    builder
}

fn render_appendix_section(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    // Appendix — full violations list, conclusion of Part 2 (#246). Only render
    // the section header when there are violations to list; otherwise it
    // promises a list that never appears (#364).
    if vm.appendix.has_violations {
        let (appendix_title, appendix_intro) = if en {
            (
                "Complete Findings List",
                "Raw audit data and the full list of detected violations.",
            )
        } else {
            (
                "Vollständige Fundstellen",
                "Rohdaten des Audits und die vollständige Liste aller erkannten Verstöße.",
            )
        };
        builder = builder.add_component(PageBreak::new()).add_component(
            SectionHeaderSplit::new(appendix_title, appendix_intro)
                .with_eyebrow(if en { "APPENDIX" } else { "ANHANG" })
                .with_level(2),
        );

        builder = builder.add_component(build_cli_snapshot_table(vm, i18n));

        // JSON hint in appendix (#219)
        let json_note = if en {
            "The accompanying JSON report contains the complete machine-readable issue list with selectors, occurrences, and all detail data for automated processing."
        } else {
            "Der begleitende JSON-Report enthält die vollständige maschinenlesbare Fehlerliste mit Selektoren, Vorkommen und allen Detaildaten für automatisierte Weiterverarbeitung."
        };
        builder = builder.add_component(Callout::info(json_note).with_title(if en {
            "Raw data & processing"
        } else {
            "Rohdaten & Weiterverarbeitung"
        }));

        if vm.meta.report_level == ReportLevel::Technical {
            for v in &vm.appendix.violations {
                let mut desc = v.message.clone();
                if let Some(ref fix) = v.fix_suggestion {
                    desc.push_str(&format!("\n\nFix: {}", fix));
                }
                desc.push_str(&format!(
                    "\n\n{} Elemente betroffen",
                    v.affected_elements.len()
                ));
                let useful_selectors: Vec<&str> = v
                    .affected_elements
                    .iter()
                    .map(|e| e.selector.as_str())
                    .filter(|s| {
                        s.contains('.')
                            || s.contains('#')
                            || s.contains('[')
                            || s.contains('>')
                            || s.contains(' ')
                    })
                    .collect();
                if !useful_selectors.is_empty() {
                    desc.push_str(&format!("\nSelektoren: {}", useful_selectors.join(", ")));
                }
                builder = builder.add_component(Finding::new(
                    format!("{} — {}", v.rule, v.rule_name),
                    map_severity(&v.severity),
                    &desc,
                ));
            }
        } else {
            let rows: Vec<ChecklistRow> = vm
                .appendix
                .violations
                .iter()
                .map(|v| {
                    let status = match v.severity {
                        crate::wcag::Severity::Critical => "bad",
                        crate::wcag::Severity::High => "warn",
                        _ => "neutral",
                    };
                    ChecklistRow::new(format!("{} — {}", v.rule, v.rule_name), v.message.clone())
                        .with_status(status)
                })
                .collect();
            builder = builder.add_component(
                ChecklistPanel::new(rows).with_title(i18n.t("section-all-violations")),
            );
        }
    }
    builder
}

fn render_positive_signals_section(
    mut builder: renderreport::engine::ReportBuilder,
    signals: &[PositiveSignal],
    is_first: bool,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    if signals.is_empty() {
        return builder;
    }

    if !is_first {
        builder = builder.add_component(PageBreak::new());
    }

    let en = i18n.locale() == "en";
    let mut rows = Vec::new();
    for signal in signals {
        let status = if signal.strong {
            if en {
                "Strong"
            } else {
                "Stark"
            }
        } else if en {
            "Present"
        } else {
            "Vorhanden"
        };
        rows.push(
            ChecklistRow::new(&signal.title, format!("{}: {}", status, signal.description))
                .with_status(if signal.strong { "good" } else { "info" }),
        );
    }

    builder.add_component(ChecklistPanel::new(rows).with_title(if en {
        "Recognized structural patterns"
    } else {
        "Erkannte Strukturmuster"
    }))
}

fn render_dual_viewport_summary_section(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    report: &AuditReport,
    is_first: bool,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let has_scores = vm.cover.desktop_score.is_some() && vm.cover.mobile_score.is_some();
    let has_screenshot_status = report.page_screenshots.is_some()
        || matches!(
            report.screenshot_status,
            crate::audit::ScreenshotStatus::Failed(_)
        );
    if !has_scores && !has_screenshot_status {
        return builder;
    }

    if !is_first {
        builder = builder.add_component(PageBreak::new());
    }

    let en = i18n.locale() == "en";
    if report.page_screenshots.is_some() {
        builder = builder.add_component(
            DevicePreview::new(
                super::PAGE_DESKTOP_SCREENSHOT_ASSET,
                super::PAGE_MOBILE_SCREENSHOT_ASSET,
            )
            .with_height(210.0),
        );
    }

    // A bordered panel here reads as its own boxed widget that then trails
    // into the blank rest of the (short) divider page — a compact strip
    // reads as part of the divider's own content instead, and names the
    // metric ("Accessibility-Score", not a bare "93/100") so it doesn't need
    // a caller to already know what dual-viewport scoring means.
    builder = builder.add_component(
        Label::new(if en {
            "Dual viewport summary"
        } else {
            "Dual-Viewport-Zusammenfassung"
        })
        .bold()
        .with_size("10.5pt"),
    );

    let mut items = Vec::new();
    if let (Some(desktop), Some(mobile)) = (vm.cover.desktop_score, vm.cover.mobile_score) {
        items.push(
            MetricStripItem::new(
                if en {
                    "Accessibility - Desktop"
                } else {
                    "Barrierefreiheit - Desktop"
                },
                format!("{desktop} / 100"),
            )
            .with_unit(score_range_label(desktop, en))
            .with_accent(design::score_color(desktop as u8)),
        );
        items.push(
            MetricStripItem::new(
                if en {
                    "Accessibility - Mobile"
                } else {
                    "Barrierefreiheit - Mobile"
                },
                format!("{mobile} / 100"),
            )
            .with_unit(score_range_label(mobile, en))
            .with_accent(design::score_color(mobile as u8)),
        );
        items.push(
            MetricStripItem::new(
                if en {
                    "Accessibility - overall"
                } else {
                    "Barrierefreiheit - Gesamt"
                },
                format!("{} / 100", vm.summary.score),
            )
            .with_unit(if en {
                "70/30 weighted"
            } else {
                "70/30 gewichtet"
            })
            .with_accent(design::score_color(vm.summary.score as u8)),
        );
    }
    if !has_scores
        && matches!(
            report.screenshot_status,
            crate::audit::ScreenshotStatus::Captured
        )
    {
        items.push(
            MetricStripItem::new(
                if en { "Preview" } else { "Vorschau" },
                if en { "Captured" } else { "Erfasst" },
            )
            .with_accent(design::tokens::SUCCESS),
        );
    }
    if !items.is_empty() {
        builder = builder.add_component(MetricStrip::new(items).compact());
    }

    if let crate::audit::ScreenshotStatus::Failed(reason) = &report.screenshot_status {
        builder = builder.add_component(Callout::warning(if en {
            format!("Screenshot capture failed: {reason}")
        } else {
            format!("Screenshot-Erfassung fehlgeschlagen: {reason}")
        }));
    }

    let occurrence_context = report
        .dual_viewport
        .as_ref()
        .map(|dual| {
            let desktop = dual.desktop.wcag_results.violations.len();
            let mobile = dual.mobile.wcag_results.violations.len();
            let combined = vm.severity.total;
            if en {
                format!("WCAG occurrences before cross-viewport consolidation: {desktop} on desktop and {mobile} on mobile. The normalized combined finding list contains {combined} occurrences; this count is used for evidence and remediation, not as a third score. ")
            } else {
                format!("WCAG-Vorkommen vor der ansichtsübergreifenden Zusammenführung: {desktop} auf Desktop und {mobile} auf Mobile. Die normalisierte gemeinsame Befundliste enthält {combined} Vorkommen; diese Anzahl dient Evidenz und Maßnahmenplanung, nicht als dritter Score. ")
            }
        })
        .unwrap_or_default();
    let explanation = if en {
        format!(
            "Each viewport accessibility score reflects the severity and variety of automatically detected WCAG findings; 100 means no issue was detected within the automated scope. Lower values mean more remediation pressure. {occurrence_context}The displayed accessibility overall score is calculated from mobile at 70% and desktop at 30%."
        )
    } else {
        format!(
            "Jeder Barrierefreiheits-Score bewertet Schwere und Vielfalt der automatisiert erkannten WCAG-Befunde seiner Ansicht; 100 bedeutet, dass im automatisierten Prüfumfang kein Problem erkannt wurde. Niedrigere Werte bedeuten höheren Handlungsdruck. {occurrence_context}Der ausgewiesene Barrierefreiheits-Gesamtwert wird mit 70 % Mobile und 30 % Desktop berechnet."
        )
    };

    builder.add_component(
        Label::new(explanation)
            .with_size("9pt")
            .with_color(design::tokens::MUTED),
    )
}

fn score_range_label(score: u32, en: bool) -> &'static str {
    crate::registry::SCORE_RANGE.label(score as f32, en)
}

pub(super) fn render_module_sections(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    report: &AuditReport,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let mut is_first = true;
    let has_dual_viewport_scores =
        vm.cover.desktop_score.is_some() && vm.cover.mobile_score.is_some();
    let has_screenshot_status = report.page_screenshots.is_some()
        || matches!(
            report.screenshot_status,
            crate::audit::ScreenshotStatus::Failed(_)
        );
    if has_dual_viewport_scores || has_screenshot_status {
        builder = render_dual_viewport_summary_section(builder, vm, report, is_first, i18n);
        is_first = false;
    }
    if let Some(ref sx) = vm.module_details.search_experience {
        builder = render_search_experience(builder, sx, is_first, i18n);
        is_first = false;
    }

    // #14: Source Quality, AI Visibility and Content Visibility are merged into
    // one "KI & Vertrauen" / "AI & Trust" chapter so the three trust- and
    // discoverability-indicator modules read as one section instead of three
    // fragmented ones. They render as level-3 sub-sections under one opener.
    let en = i18n.locale() == "en";
    let mut ki_opened = false;
    let mut in_ki_chapter = false;
    for module in active_report_modules(report) {
        let key = module.module_key();
        let is_trust = matches!(
            key,
            "source_quality" | "ai_visibility" | "content_visibility"
        );
        if is_trust && !ki_opened {
            builder = builder.add_component(PageBreak::new()).add_component(
                SectionHeaderSplit::new(
                    if en { "AI & Trust" } else { "KI & Vertrauen" },
                    if en {
                        "Source quality, AI readability and content visibility — trust and discoverability indicators."
                    } else {
                        "Quellenqualität, KI-Lesbarkeit und Content-Sichtbarkeit — Vertrauens- und Auffindbarkeits-Indikatoren."
                    },
                )
                .with_eyebrow(if en { "TRUST" } else { "VERTRAUEN" })
                .with_level(2),
            );
            ki_opened = true;
            in_ki_chapter = true;
            is_first = true; // the trio's first sub-section flows under the opener
        } else if !is_trust && in_ki_chapter {
            // Close the trust chapter before the next, unrelated module.
            builder = builder.add_component(PageBreak::new());
            in_ki_chapter = false;
            is_first = true;
        }
        let (next_builder, rendered) =
            render_active_module_section(builder, key, vm, report, is_first, i18n);
        builder = next_builder;
        if rendered {
            is_first = false;
        }
    }

    builder
}

fn render_active_module_section(
    mut builder: renderreport::engine::ReportBuilder,
    module_key: &str,
    vm: &ReportViewModel,
    report: &AuditReport,
    is_first: bool,
    i18n: &I18n,
) -> (renderreport::engine::ReportBuilder, bool) {
    match module_key {
        "performance" => {
            if let Some(ref perf) = vm.module_details.performance {
                builder = render_performance(builder, perf, is_first, i18n);
                if !report.experience.budget_violations.is_empty() {
                    builder = render_budget_violations(
                        builder,
                        &report.experience.budget_violations,
                        i18n,
                    );
                }
                return (builder, true);
            }
        }
        "seo" => {
            if let Some(ref seo) = vm.module_details.seo {
                return (render_seo(builder, seo, is_first, i18n), true);
            }
        }
        "security" => {
            if let Some(ref sec) = vm.module_details.security {
                return (render_security(builder, sec, is_first, i18n), true);
            }
        }
        "html_conform" => {
            if let Some(ref hc) = vm.module_details.html_conform {
                return (render_html_conform(builder, hc, is_first, i18n), true);
            }
        }
        "commerce" => {
            if let Some(ref c) = vm.module_details.commerce {
                return (render_commerce(builder, c, is_first, i18n), true);
            }
        }
        "mobile" => {
            if let Some(ref mobile) = vm.module_details.mobile {
                return (render_mobile(builder, mobile, is_first, i18n), true);
            }
        }
        "ux" => {
            if let Some(ref ux) = vm.module_details.ux {
                return (render_ux(builder, ux, is_first, i18n), true);
            }
        }
        "journey" => {
            if let Some(ref journey) = vm.module_details.journey {
                return (render_journey(builder, journey, is_first, i18n), true);
            }
        }
        "dark_mode" => {
            if let Some(ref dm) = vm.module_details.dark_mode {
                return (render_dark_mode(builder, dm, is_first, i18n), true);
            }
        }
        "design_quality" => {
            if let Some(ref dq) = vm.module_details.design_quality {
                return (render_design_quality(builder, dq, is_first, i18n), true);
            }
        }
        "ai_transparency" => {
            if let Some(ref at) = vm.module_details.ai_transparency {
                return (render_ai_transparency(builder, at, is_first, i18n), true);
            }
        }
        "network_dns" => {
            if let Some(ref dns) = vm.module_details.network_dns {
                return (render_network_dns(builder, dns, is_first, i18n), true);
            }
        }
        "source_quality" => {
            if let Some(ref sq) = vm.module_details.source_quality {
                return (render_source_quality(builder, sq, is_first, i18n), true);
            }
        }
        "ai_visibility" => {
            if let Some(ref av) = vm.module_details.ai_visibility {
                return (render_ai_visibility(builder, av, is_first, i18n), true);
            }
        }
        "content_visibility" => {
            if let Some(ref cv) = vm.module_details.content_visibility {
                return (render_content_visibility(builder, cv, is_first, i18n), true);
            }
        }
        "best_practices" => {
            if let Some(ref bp) = vm.module_details.best_practices {
                return (render_best_practices(builder, bp, is_first, i18n), true);
            }
        }
        "tech_stack" => {
            if let Some(ref ts) = vm.module_details.tech_stack {
                return (render_tech_stack(builder, ts, is_first, i18n), true);
            }
        }
        "patterns" if !vm.positive_signals.is_empty() => {
            return (
                render_positive_signals_section(builder, &vm.positive_signals, is_first, i18n),
                true,
            );
        }
        _ => {}
    }

    (builder, false)
}

/// Max number of root causes assigned a letter (A, B, C…) in the root-cause
/// analysis section. Shared with `render_timeframe_roadmap` so both sections
/// agree on which letter identifies which cause.
const ROOT_CAUSE_SHOWN: usize = 6;

/// WCAG-Mandatory-tier findings sorted by occurrence count (descending) — the
/// exact pool `render_root_cause_analysis` assigns letters A, B, C… from.
fn mandatory_root_causes(vm: &ReportViewModel) -> Vec<&FindingGroup> {
    let mut findings: Vec<&FindingGroup> = vm
        .findings
        .all_findings
        .iter()
        .filter(|f| f.occurrence_count > 0 && f.criticality_tier == CriticalityTier::Mandatory)
        .collect();
    findings.sort_by_key(|f| std::cmp::Reverse(f.occurrence_count));
    findings
}

/// Shorten a finding title for inline display next to a letter code (chart
/// labels, table cells) — same char-based ellipsis truncation pattern used
/// elsewhere in the PDF layer.
fn truncate_title(value: &str, max_chars: usize) -> String {
    let count = value.chars().count();
    if count <= max_chars {
        return value.to_string();
    }
    value
        .chars()
        .take(max_chars.saturating_sub(1))
        .collect::<String>()
        + "…"
}

/// `rule_id -> (letter, occurrence_count, share_pct)` for the top
/// `ROOT_CAUSE_SHOWN` mandatory root causes. Used by `render_timeframe_roadmap`
/// to tag systemic actions with the root cause they resolve, so the two
/// sections never disagree on which letter is which.
fn root_cause_lookup(
    findings: &[&FindingGroup],
) -> std::collections::HashMap<String, (char, usize, i64)> {
    let total_occurrences: usize = findings.iter().map(|f| f.occurrence_count).sum();
    findings
        .iter()
        .enumerate()
        .take(ROOT_CAUSE_SHOWN)
        .map(|(idx, f)| {
            let letter = (b'A' + idx as u8) as char;
            let share_pct = if total_occurrences > 0 {
                (f.occurrence_count as f64 * 100.0 / total_occurrences as f64).round() as i64
            } else {
                0
            };
            (f.rule_id.clone(), (letter, f.occurrence_count, share_pct))
        })
        .collect()
}

pub(super) fn render_root_cause_analysis(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let title = if en {
        "Root Cause Analysis"
    } else {
        "Ursachenanalyse"
    };
    let subtitle = if en {
        "Many individual findings trace back to a few recurring causes — fixing those has a compounding effect."
    } else {
        "Viele Einzelbefunde gehen auf wenige wiederkehrende Ursachen zurück – deren Behebung wirkt gebündelt."
    };

    // No leading PageBreak: the preceding part divider ("Befunde nach Ursache")
    // already opened the page — an extra break left that divider page 3/4 empty.
    builder = builder.add_component(
        SectionHeaderSplit::new(title, subtitle)
            .with_eyebrow(if en { "ROOT CAUSE" } else { "URSACHEN" })
            .with_level(2),
    );

    // Only WCAG/Mandatory findings — scope matches the header "N Accessibility-Befunde" count.
    // SEO findings (Optimization tier) appear in their own section below.
    let findings = mandatory_root_causes(vm);

    if findings.is_empty() {
        let msg = if en {
            "No accessibility findings were detected, so no root cause analysis is necessary."
        } else {
            "Es wurden keine Barrierefreiheits-Befunde erkannt, daher ist keine Ursachenanalyse erforderlich."
        };
        builder = builder.add_component(Callout::success(msg));
        return builder;
    }

    // Plain lead-in (Rule A): spell out what "root cause" means in practice
    // before the technical list of causes/components follows below.
    let lead_in = if en {
        "In practice: fixing the right root cause — a shared component or template — often resolves several findings at once, instead of fixing each one individually."
    } else {
        "Das bedeutet konkret: Ein Fix an der richtigen Stelle – etwa einer wiederverwendeten Komponente oder einem Template – behebt oft mehrere Befunde gleichzeitig, statt jeden einzeln reparieren zu müssen."
    };
    builder = builder.add_component(Label::new(lead_in).with_size("10.5pt"));

    // Render root causes (assigning letters A, B, C, etc.)
    let mut list = List::new().with_title(if en {
        "Systemic Root Causes"
    } else {
        "Erkannte Kernursachen"
    });
    let mut table_rows = Vec::new();
    let mut chart_data: Vec<(String, f64)> = Vec::new();
    let total_occurrences: usize = findings.iter().map(|f| f.occurrence_count).sum();

    // Rounded (not truncating) share so a small-but-real cause reads as "1 %"
    // rather than a self-contradictory "0 %" next to its own listed row.
    let share_pct = |occurrences: usize| -> i64 {
        if total_occurrences > 0 {
            (occurrences as f64 * 100.0 / total_occurrences as f64).round() as i64
        } else {
            0
        }
    };

    let mut shown_occurrences = 0usize;

    for (idx, finding) in findings.iter().enumerate().take(ROOT_CAUSE_SHOWN) {
        let letter = (b'A' + idx as u8) as char;
        let item_title = format!(
            "{} {}: {} {} — {}",
            if en { "Root Cause" } else { "Ursache" },
            letter,
            finding.occurrence_count,
            if en { "occurrences" } else { "Vorkommen" },
            finding.title
        );
        list = list.add_item(&item_title);
        shown_occurrences += finding.occurrence_count;

        // Repeat the clear-text title next to the letter — otherwise the chart
        // and table only carry "Ursache A", forcing readers to flip back to
        // the list above to remember what it refers to.
        let short_title = truncate_title(&finding.title, 45);
        table_rows.push(vec![
            format!("{letter} — {short_title}"),
            finding.occurrence_count.to_string(),
            format!("{} %", share_pct(finding.occurrence_count)),
        ]);
        chart_data.push((
            format!("{letter} — {short_title}"),
            finding.occurrence_count as f64,
        ));
    }

    // Findings beyond the top ROOT_CAUSE_SHOWN would otherwise inflate
    // `total_occurrences` (the true, honest denominator) with no visible row
    // to account for them — the displayed shares silently failed to sum to
    // 100 %. Disclose the remainder explicitly instead (#QA-039 report review).
    if findings.len() > ROOT_CAUSE_SHOWN {
        let remaining_causes = findings.len() - ROOT_CAUSE_SHOWN;
        let remaining_occurrences = total_occurrences - shown_occurrences;
        let label = if en {
            format!("Other ({remaining_causes} further causes)")
        } else {
            format!("Sonstige ({remaining_causes} weitere Ursachen)")
        };
        table_rows.push(vec![
            label.clone(),
            remaining_occurrences.to_string(),
            format!("{} %", share_pct(remaining_occurrences)),
        ]);
        chart_data.push((label, remaining_occurrences as f64));
    }

    builder = builder.add_component(list);

    // Occurrence distribution as a bar chart — shows at a glance where the
    // findings concentrate (#7 distribution bars).
    if chart_data.len() >= 2 {
        builder = builder.add_component(
            Chart::bar(if en {
                "Occurrence distribution by cause"
            } else {
                "Verteilung der Vorkommen nach Ursache"
            })
            .add_series("occurrences", chart_data)
            .horizontal(),
        );
    }

    // Render the table: Ursache | Vorkommen | Anteil
    let mut table = AuditTable::new(vec![
        TableColumn::new(if en { "Root Cause" } else { "Ursache" }).with_width("40%"),
        TableColumn::new(if en { "Occurrences" } else { "Vorkommen" }).with_width("30%"),
        TableColumn::new(if en { "Share" } else { "Anteil" }).with_width("30%"),
    ])
    .with_title(if en {
        "Distribution of Issues by Root Cause"
    } else {
        "Verteilung der Mängel nach Ursache"
    });

    for row in table_rows {
        table = table.add_row(row);
    }
    builder = builder.add_component(table);

    builder
}

pub(super) fn render_timeframe_roadmap(
    mut builder: renderreport::engine::ReportBuilder,
    vm: &ReportViewModel,
    i18n: &I18n,
) -> renderreport::engine::ReportBuilder {
    let en = i18n.locale() == "en";
    let title = if en { "Action Plan" } else { "Maßnahmenplan" };
    // Disclose the scope mismatch with the root-cause section above: this plan
    // also includes SEO/Optimization-tier actions, which are not part of the
    // WCAG-only root-cause count (#5 fix).
    let subtitle = if en {
        "Recommended actions grouped by where the problem lives — including supplementary SEO and quality recommendations without legal relevance."
    } else {
        "Empfohlene Maßnahmen, gruppiert nach Ebene des Problems — inklusive ergänzender SEO- und Qualitätsempfehlungen ohne Rechtsbezug."
    };

    builder = builder.add_component(PageBreak::new()).add_component(
        SectionHeaderSplit::new(title, subtitle)
            .with_eyebrow(if en { "ROADMAP" } else { "MASSNAHMEN" })
            .with_level(2),
    );

    // Overall-leverage sentence (plan/7-management-summary-consolidation.md):
    // reuses the same problem-concentration numbers shown earlier
    // (plan/3-problem-concentration-diagnosis-narrative.md) but framed
    // around leverage rather than diagnosis — not literally the same
    // sentence twice.
    if let Some(note) = build_overall_leverage_note(vm, i18n) {
        builder = builder.add_component(Label::new(note).with_size("10.5pt"));
    }

    let columns = &vm.actions.roadmap_columns;
    if columns.is_empty() {
        let empty_msg = if en {
            "No prioritized actions — no findings require remediation."
        } else {
            "Keine priorisierten Maßnahmen — keine Befunde mit Handlungsbedarf."
        };
        builder = builder.add_component(Label::new(empty_msg).with_color(design::tokens::NEUTRAL));
        return builder;
    }

    // Same letter assignment as `render_root_cause_analysis`, so an action
    // tied to root cause "A" always points at the same finding the reader saw
    // lettered "A" above (#2 fix).
    let root_causes = mandatory_root_causes(vm);
    let root_cause_by_rule = root_cause_lookup(&root_causes);

    // One level group per column (systemic vs. local), each action as a
    // clean recommendation card — what to do, why, and (plan/6) a
    // remediation-leverage line instead of a separate visual effort badge.
    for col in columns {
        builder = builder.add_component(
            SectionHeaderSplit::new(col.title.clone(), col.description.clone()).with_level(3),
        );
        for item in &col.items {
            let mut why = if !item.benefit.is_empty() {
                item.benefit.clone()
            } else {
                item.risk_effect.clone()
            };
            // plan/6-remediation-leverage-metric.md: "is this worth doing
            // first" verdict — reach (occurrences), cost (effort) and risk
            // condensed into one line. "betroffen", not "behoben"/"beseitigt"
            // (plan/4-root-cause-confidence-wording.md): occurrence_count is
            // how many elements this rule affects, not a guarantee that one
            // fix resolves every one of them.
            let leverage_tag = if en {
                format!(
                    "Remediation leverage: {} — {} occurrence(s) affected · effort: {}",
                    item.leverage, item.occurrence_count, item.effort
                )
            } else {
                format!(
                    "Reparaturhebel: {} — {} Vorkommen betroffen · Aufwand: {}",
                    item.leverage, item.occurrence_count, item.effort
                )
            };
            why = format!("{why}\n\n{leverage_tag}");
            if let Some((letter, occurrence_count, share_pct)) =
                root_cause_by_rule.get(&item.rule_id)
            {
                let tag = if en {
                    format!("→ Root Cause {letter}, {occurrence_count} occurrences ({share_pct}%)")
                } else {
                    format!("→ Ursache {letter}, {occurrence_count} Vorkommen ({share_pct} %)")
                };
                why = format!("{why}\n\n{tag}");
            }
            builder = builder.add_component(RecommendationCard::new(item.action.clone(), why));
        }
    }

    builder
}

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

    /// #576 acceptance scenario 1: a "critical, mixed" report — some
    /// dimensions bad/critical, some genuinely good (SEO here mirrors the
    /// exact cited bug: "Sehr gute Auffindbarkeit..." must never land in the
    /// risks bucket). Usability/Legal/Business are bad (critical findings,
    /// BFSG violations, low score); SEO and Performance/Mobile are good.
    #[test]
    fn mixed_report_buckets_bad_dimensions_as_risks_and_good_ones_as_strengths() {
        let dimensions = compute_dimension_rows(
            /* severity_critical */ 2, /* severity_high */ 1,
            /* cover_critical_issues */ 2, /* summary_score */ 45,
            /* seo_score */ 95, /* perf_score */ 95, /* mobile_score */ 95,
            /* en */ false,
        );
        assert_eq!(dimensions.len(), 5);

        let risks: Vec<&DimensionRow> = dimensions.iter().filter(|d| d.status != "good").collect();
        let strengths: Vec<&DimensionRow> =
            dimensions.iter().filter(|d| d.status == "good").collect();

        assert_eq!(
            risks.len(),
            3,
            "usability, legal and business should be risks"
        );
        assert!(risks.iter().all(|d| d.status == "bad"));
        assert!(
            risks.iter().all(|d| d.label != "SEO & KI-Sichtbarkeit"),
            "SEO must never appear in the risks bucket when its status is good"
        );

        assert_eq!(
            strengths.len(),
            2,
            "SEO and performance/mobile should be strengths"
        );
        let seo_strength = strengths
            .iter()
            .find(|d| d.label == "SEO & KI-Sichtbarkeit")
            .expect("SEO dimension should be a strength");
        assert!(
            seo_strength
                .description
                .contains("Sehr gute Auffindbarkeit"),
            "the exact bug cited in #576: positive SEO text must land in strengths, not risks"
        );
    }

    /// #576 acceptance scenario 2: a report where genuinely nothing is a
    /// risk — all 5 dimensions clear their "good" threshold. This must be
    /// achievable (i.e. every dimension's status derivation must have a
    /// reachable "good" branch), otherwise the zero-risk empty state could
    /// never render in practice.
    #[test]
    fn clean_report_puts_all_five_dimensions_in_strengths() {
        let dimensions = compute_dimension_rows(
            /* severity_critical */ 0, /* severity_high */ 0,
            /* cover_critical_issues */ 0, /* summary_score */ 95,
            /* seo_score */ 95, /* perf_score */ 95, /* mobile_score */ 95,
            /* en */ false,
        );
        assert_eq!(dimensions.len(), 5);
        assert!(
            dimensions.iter().all(|d| d.status == "good"),
            "all dimensions should be good, got: {:?}",
            dimensions
                .iter()
                .map(|d| (&d.label, d.status))
                .collect::<Vec<_>>()
        );
    }

    /// Ordering: within the risks bucket, "bad" entries sort before "warn"
    /// entries, but relative order within each status is preserved (stable
    /// sort) rather than reshuffled.
    #[test]
    fn risks_partition_sorts_bad_before_warn_stably() {
        let dimensions = compute_dimension_rows(
            /* severity_critical */ 0, /* severity_high */ 1, // usability -> warn
            /* cover_critical_issues */ 1, // legal -> bad
            /* summary_score */ 70, // business -> warn
            /* seo_score */ 50, // seo -> bad
            /* perf_score */ 95, /* mobile_score */ 95, /* en */ true,
        );
        let (mut risks, _strengths): (Vec<DimensionRow>, Vec<DimensionRow>) =
            dimensions.into_iter().partition(|d| d.status != "good");
        risks.sort_by_key(|d| if d.status == "bad" { 0u8 } else { 1u8 });

        let statuses: Vec<&str> = risks.iter().map(|d| d.status).collect();
        assert_eq!(statuses, vec!["bad", "bad", "warn", "warn"]);
        // Stable within the "bad" group: Legal Conformance came before SEO
        // in the fixed dimension order, so it stays first among bads.
        assert_eq!(risks[0].label, "Legal Conformance");
        assert_eq!(risks[1].label, "SEO & AI Visibility");
    }

    fn test_report_view_model() -> ReportViewModel {
        let mut results = crate::wcag::WcagResults::new();
        results.nodes_checked = 50;
        results.passes = 10;
        results.add_violation(
            crate::wcag::Violation::new(
                "1.1.1",
                "Non-text Content",
                crate::cli::WcagLevel::A,
                crate::wcag::Severity::High,
                "Image missing alt",
                "node-img",
            )
            .with_selector("img.hero")
            .with_html_snippet("<img class=\"hero\">")
            .with_fix("Add alt"),
        );
        let report = AuditReport::new(
            "https://example.com".into(),
            crate::cli::WcagLevel::AA,
            results,
            100,
        );
        let normalized = crate::audit::normalized::normalize(&report);
        let config = ReportConfig::default();
        crate::output::builder::build_view_model(&normalized, &config)
    }

    #[test]
    fn problem_profile_casoon_scenario_is_punktuell() {
        let mut vm = test_report_view_model();
        let i18n_de = I18n::new("de").unwrap();
        let i18n_en = I18n::new("en").unwrap();

        // Real module scores from a live casoon.de audit, 2026-09-07
        // (verified via `--debug-typ`'s "Warum ist der Gesamtwert"-table) — 0
        // critical (< 40) modules, and in fact 0 modules below 75 at all.
        vm.modules.module_scores = vec![
            crate::audit::normalized::ModuleScoreEntry {
                name: "Accessibility".into(),
                score: 99,
                grade: "Sehr gut".into(),
                weight_pct: 40,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Performance".into(),
                score: 75,
                grade: "Gut".into(),
                weight_pct: 20,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "SEO".into(),
                score: 100,
                grade: "Sehr gut".into(),
                weight_pct: 20,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Security".into(),
                score: 95,
                grade: "Sehr gut".into(),
                weight_pct: 10,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Mobile".into(),
                score: 90,
                grade: "Sehr gut".into(),
                weight_pct: 10,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
        ];
        // 1 occurrence — matches the real audit's single a11y.text_spacing.clipped finding.
        let mut finding = vm.findings.all_findings[0].clone();
        finding.rule_id = "1.4.12".into();
        finding.title = "Inhalt wird abgeschnitten".into();
        finding.occurrence_count = 1;
        finding.wcag_criterion = "1.4.12".into();
        vm.findings.all_findings = vec![finding];

        let kind = classify_problem_profile(&vm);
        assert_eq!(kind, ProblemProfileKind::Punktuell);
        assert_eq!(kind.label(false), "punktuell");
        assert_eq!(kind.label(true), "isolated");

        let desc_de = build_problem_profile_description(&vm, kind, &i18n_de);
        assert!(desc_de.contains("Sehr guter technischer Zustand"));
        let desc_en = build_problem_profile_description(&vm, kind, &i18n_en);
        assert!(desc_en.contains("Very good technical condition"));
    }

    #[test]
    fn problem_profile_inros_lackner_scenario_is_konzentriert_systemisch() {
        let mut vm = test_report_view_model();
        let i18n_de = I18n::new("de").unwrap();
        let i18n_en = I18n::new("en").unwrap();

        // Real module scores from a live inros-lackner.de audit, 2026-09-07
        // (verified via `--debug-typ`'s "Warum ist der Gesamtwert"-table) — 4
        // of 5 weighted modules are below 75 ("Good"), but only Accessibility
        // (20) and Security (30) are actually "Kritisch" (< 40); Performance
        // (64) and SEO (65) are merely "Verbesserungswürdig". Regression
        // coverage for the 2026-09-07 fix: with the broader < 75 breadth
        // count this used to misclassify as "breit & systemisch" (4 modules)
        // instead of "konzentriert & systemisch" (2 critical modules).
        vm.modules.module_scores = vec![
            crate::audit::normalized::ModuleScoreEntry {
                name: "Accessibility".into(),
                score: 20,
                grade: "Kritisch".into(),
                weight_pct: 40,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Performance".into(),
                score: 64,
                grade: "Verbesserungswürdig".into(),
                weight_pct: 20,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "SEO".into(),
                score: 65,
                grade: "Verbesserungswürdig".into(),
                weight_pct: 20,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Security".into(),
                score: 30,
                grade: "Kritisch".into(),
                weight_pct: 10,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Mobile".into(),
                score: 80,
                grade: "Gut".into(),
                weight_pct: 10,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
        ];
        let mut f1 = vm.findings.all_findings[0].clone();
        f1.rule_id = "1.4.3".into();
        f1.title = "Kontrast unzureichend".into();
        f1.occurrence_count = 60;
        f1.wcag_criterion = "1.4.3".into();

        let mut f2 = vm.findings.all_findings[0].clone();
        f2.rule_id = "4.1.2".into();
        f2.title = "Name/Rolle fehlt".into();
        f2.occurrence_count = 30;
        f2.wcag_criterion = "4.1.2".into();
        vm.findings.all_findings = vec![f1, f2];

        let kind = classify_problem_profile(&vm);
        assert_eq!(kind, ProblemProfileKind::KonzentriertSystemisch);
        assert_eq!(kind.label(false), "konzentriert & systemisch");
        assert_eq!(kind.label(true), "concentrated & systemic");

        let desc_de = build_problem_profile_description(&vm, kind, &i18n_de);
        assert!(desc_de.contains("Barrierefreiheit und Sicherheit bestimmen den Handlungsbedarf"));
        assert!(desc_de.contains("konzentriert sich auf wenige wiederkehrende Muster"));

        let desc_en = build_problem_profile_description(&vm, kind, &i18n_en);
        assert!(desc_en.contains("Accessibility and Security determine the need for action"));
        assert!(desc_en.contains("concentrated in a few recurring patterns"));
    }

    #[test]
    fn problem_profile_auto_birne_scenario_is_breit_systemisch() {
        let mut vm = test_report_view_model();
        let i18n_de = I18n::new("de").unwrap();
        let i18n_en = I18n::new("en").unwrap();

        // Real module scores from a live auto-birne.de audit, 2026-09-07
        // (verified via `--debug-typ`'s "Warum ist der Gesamtwert"-table) — 3
        // critical (< 40) modules (Accessibility, Performance, Security); SEO
        // (82) is stable and Mobile (70) is merely "Verbesserungswürdig", so
        // neither should be named as "determining the need for action".
        vm.modules.module_scores = vec![
            crate::audit::normalized::ModuleScoreEntry {
                name: "Accessibility".into(),
                score: 12,
                grade: "Kritisch".into(),
                weight_pct: 40,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Performance".into(),
                score: 34,
                grade: "Kritisch".into(),
                weight_pct: 20,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Security".into(),
                score: 22,
                grade: "Kritisch".into(),
                weight_pct: 10,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "SEO".into(),
                score: 82,
                grade: "Gut".into(),
                weight_pct: 20,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
            crate::audit::normalized::ModuleScoreEntry {
                name: "Mobile".into(),
                score: 70,
                grade: "Verbesserungswürdig".into(),
                weight_pct: 10,
                contributes_to_overall: true,
                measurement_type: "measured".into(),
            },
        ];

        let kind = classify_problem_profile(&vm);
        assert_eq!(kind, ProblemProfileKind::BreitSystemisch);
        assert_eq!(kind.label(false), "breit & systemisch");
        assert_eq!(kind.label(true), "broad & systemic");

        let desc_de = build_problem_profile_description(&vm, kind, &i18n_de);
        assert!(desc_de.contains("Mehrere technische Bereiche sind gleichzeitig betroffen"));
        assert!(desc_de.contains("Barrierefreiheit, Performance und Sicherheit"));

        let desc_en = build_problem_profile_description(&vm, kind, &i18n_en);
        assert!(desc_en.contains("Multiple technical areas are affected simultaneously"));
        assert!(desc_en.contains("Accessibility, Performance, and Security"));
    }

    #[test]
    fn subcategory_breakdown_handles_all_weak_entries() {
        let i18n = I18n::new("de").unwrap();
        let builder = renderreport::engine::ReportBuilder::new("single");
        let entries = vec![
            ("ARIA".to_string(), 10),
            ("Landmarks".to_string(), 20),
            ("Semantik".to_string(), 50),
        ];
        let builder = render_subcategory_breakdown(builder, "Accessibility", &entries, &i18n);
        let report = builder.build();
        assert_eq!(report.components.len(), 1);
        let json = serde_json::to_string(&report.components[0]).unwrap();
        assert!(json.contains("Kritische Schwächen:"));
        assert!(!json.contains("Stärkere Teilbereiche"));
        assert!(json.contains("ARIA 10"));
    }

    #[test]
    fn subcategory_breakdown_handles_all_stable_entries() {
        let i18n = I18n::new("de").unwrap();
        let builder = renderreport::engine::ReportBuilder::new("single");
        let entries = vec![
            ("Formulare".to_string(), 100),
            ("Alternativtexte".to_string(), 90),
        ];
        let builder = render_subcategory_breakdown(builder, "Barrierefreiheit", &entries, &i18n);
        let report = builder.build();
        assert_eq!(report.components.len(), 1);
        let json = serde_json::to_string(&report.components[0]).unwrap();
        assert!(!json.contains("Kritische Schwächen"));
        assert!(json.contains("Stärkere Teilbereiche innerhalb der Barrierefreiheit:"));
        assert!(json.contains("Formulare 100"));
    }

    #[test]
    fn subcategory_breakdown_handles_contrast_entries() {
        let i18n = I18n::new("de").unwrap();
        let builder = renderreport::engine::ReportBuilder::new("single");
        let entries = vec![("ARIA".to_string(), 10), ("Formulare".to_string(), 100)];
        let builder = render_subcategory_breakdown(builder, "Barrierefreiheit", &entries, &i18n);
        let report = builder.build();
        assert_eq!(report.components.len(), 1);
        let json = serde_json::to_string(&report.components[0]).unwrap();
        assert!(json.contains("Kritische Schwächen:"));
        assert!(json.contains("Stärkere Teilbereiche innerhalb der Barrierefreiheit:"));
    }

    #[test]
    fn subcategory_breakdown_handles_empty_entries() {
        let i18n = I18n::new("de").unwrap();
        let builder = renderreport::engine::ReportBuilder::new("single");
        let entries: Vec<(String, u32)> = vec![];
        let builder = render_subcategory_breakdown(builder, "Accessibility", &entries, &i18n);
        let report = builder.build();
        assert_eq!(report.components.len(), 0);
    }

    #[test]
    fn part_divider_part_1_and_2_do_not_have_trailing_break() {
        let i18n = I18n::new("de").unwrap();
        let b1 = renderreport::engine::ReportBuilder::new("single");
        let r1 = render_part_divider(b1, 1, "T1", "I1", "Z1", "B1", &i18n).build();
        assert_eq!(r1.components.len(), 3);

        let b2 = renderreport::engine::ReportBuilder::new("single");
        let r2 = render_part_divider(b2, 2, "T2", "I2", "Z2", "B2", &i18n).build();
        assert_eq!(r2.components.len(), 4);
    }

    #[test]
    fn part_divider_part_3_acts_as_standalone_trennseite() {
        let i18n = I18n::new("de").unwrap();
        let b3 = renderreport::engine::ReportBuilder::new("single");
        let r3 = render_part_divider(b3, 3, "T3", "I3", "Z3", "B3", &i18n).build();
        assert_eq!(r3.components.len(), 6);
        let json = serde_json::to_string(&r3.components).unwrap();
        assert!(json.contains("TECHNISCHER ANHANG"));
        assert!(json.contains("divider"));
    }

    #[test]
    fn part_divider_part_3_english_eyebrow() {
        let i18n = I18n::new("en").unwrap();
        let b3 = renderreport::engine::ReportBuilder::new("single");
        let r3 = render_part_divider(b3, 3, "T3", "I3", "Z3", "B3", &i18n).build();
        let json = serde_json::to_string(&r3.components).unwrap();
        assert!(json.contains("TECHNICAL APPENDIX"));
    }
}