rustio-admin 0.21.1

Django Admin, but for Rust. A small, focused admin framework.
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
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
//! Template context builders. Every piece of data the admin templates
//! need comes from here as a `serde::Serialize` struct. No HTML lives
//! in Rust code.
//!
//! Every page context embeds [`BaseContext`] via `#[serde(flatten)]`
//! so every template gets uniform access to `identity`, `csrf_token`,
//! site branding, and the active theme palette.
//!
//! Slimmed for Tier 1 P6: the legacy file's password-change /
//! user-new-edit / group-new-edit form sections, the developer-stub
//! "coming soon" context, the schema/search helpers, and the audit
//! history page contexts have been removed. They re-land with
//! `admin/builtin.rs` in P6.b.

#![allow(dead_code)]

use std::collections::HashMap;

use serde::Serialize;

use super::audit::AdminAction;
use super::types::{Admin, AdminEntry, AdminField, EditRow, ListRow};
use crate::auth::Identity;
use crate::error::Result;
use crate::http::FormData;
use crate::orm::Db;

#[derive(Serialize)]
pub(crate) struct IdentityCtx {
    pub email: String,
    pub is_admin: bool,
    pub is_developer: bool,
    /// Mirrors `Identity::mfa_enabled`. Surfaced into the topbar
    /// template so the chrome can pick between "Enable MFA" (un-
    /// enrolled) and "Two-factor" (already enrolled) links —
    /// `VISIBILITY_AUDIT.md` B1.
    pub mfa_enabled: bool,
}

impl From<&Identity> for IdentityCtx {
    fn from(i: &Identity) -> Self {
        Self {
            email: i.email.clone(),
            is_admin: i.is_admin(),
            is_developer: i.is_active && i.role.includes(crate::auth::Role::Developer),
            mfa_enabled: i.mfa_enabled,
        }
    }
}

#[derive(Serialize)]
pub(crate) struct BaseContext {
    pub identity: Option<IdentityCtx>,
    pub csrf_token: String,
    pub site_title: String,
    pub site_header: String,
    pub index_title: String,
    pub footer_copyright: String,
    /// User-facing application identity (e.g. "Library Circulation").
    /// Sourced from [`SiteBranding::app_name`]. Templates render this
    /// in the chrome footer brand slot, page titles where
    /// appropriate, and auth-surface wordmarks. Framework name
    /// `RustIO` is intentionally absent from this field.
    pub app_name: String,
    /// Optional brand tagline ("Operational library management",
    /// "Account security notification" fallback for emails).
    pub app_tagline: Option<String>,
    /// `true` → templates render the small "Powered by RustIO" credit
    /// in the chrome footer + email footer. Opt-in per
    /// [`SiteBranding::show_powered_by`].
    pub show_powered_by: bool,
    /// Framework SemVer (`env!("CARGO_PKG_VERSION")`). Surfaced in
    /// the footer's identity column and used to deep-link the
    /// "Documentation" entry at the matching `docs.rs/rustio-admin/X.Y.Z`.
    pub framework_version: &'static str,
    /// Free-text label rendered in the footer's environment badge —
    /// `RUSTIO_ENV` if set, otherwise "Development" for debug builds
    /// and "Production" for release builds. Cached in a process-wide
    /// `OnceLock`; one env read per process, not per request.
    pub environment_label: &'static str,
    /// Stable kind discriminator for CSS targeting (`prod` lights the
    /// success dot, `dev` lights the amber dot, anything else stays
    /// neutral). Derived from `environment_label`.
    pub environment_kind: &'static str,
    /// UTC timestamp formatted at render time. Renders in the
    /// footer's context column so operators can read at-a-glance
    /// when a given page was generated.
    pub server_now: String,
    /// `true` when the active session belongs to a demo user (`is_demo`
    /// column on `rustio_users`). Templates use this to render the red
    /// banner above the page content.
    pub is_demo_session: bool,
    pub demo_label: Option<String>,
    /// `true` when the active `AdminTheme` patch sets at least one
    /// field. Templates use it to skip emitting the inline `<style>`
    /// block entirely when no overrides are configured — the framework
    /// stylesheet is then the single source of truth.
    pub has_theme_overrides: bool,
    /// Accent colour in `#rrggbb` form, only `Some` when the project
    /// patched it. `None` means *no override — admin.css owns it*.
    pub accent_hex: Option<String>,
    /// Same colour as a space-separated RGB triplet (`"30 107 168"`)
    /// for use inside `rgb(... / opacity)` expressions. `None` paired
    /// with `accent_hex == None`.
    pub accent_rgb: Option<String>,
    pub theme_bg: Option<String>,
    pub theme_surface: Option<String>,
    pub theme_text: Option<String>,
    pub theme_text_muted: Option<String>,
    pub theme_border: Option<String>,
    /// `true` when the admin was constructed with
    /// [`crate::admin::Admin::read_only`]. Drives the chrome
    /// banner in `_base.html` and the suppression of top-level
    /// "Add" buttons on the dashboard and list pages.
    pub read_only: bool,
    /// Unread-notification count for the active operator. `0` when
    /// the page didn't pre-fetch (default) or there's no signed-in
    /// identity. Drives the topbar bell's red-dot badge —
    /// `_topbar.html` renders the badge only when this is `> 0`.
    /// Page handlers that want the badge live on their page chain
    /// `.with_unread_count(n)` after [`BaseContext::new`].
    pub unread_count: i64,
}

/// Convert an `#rrggbb` (or `rrggbb`) hex string into the
/// space-separated RGB-triplet form CSS variables expect (`160 52 26`
/// for `#A0341A`). On any parse failure returns the framework default
/// accent RGB so the admin chrome never breaks over a config typo.
pub(crate) fn hex_to_rgb_triplet(hex: &str) -> String {
    const FALLBACK: &str = "160 52 26"; // #A0341A — framework default crimson
    let h = hex.trim_start_matches('#');
    if h.len() != 6 || !h.chars().all(|c| c.is_ascii_hexdigit()) {
        return FALLBACK.into();
    }
    let r = u8::from_str_radix(&h[0..2], 16).unwrap_or(160);
    let g = u8::from_str_radix(&h[2..4], 16).unwrap_or(52);
    let b = u8::from_str_radix(&h[4..6], 16).unwrap_or(26);
    format!("{r} {g} {b}")
}

/// Environment label resolved from `RUSTIO_ENV` (if set) else
/// derived from build kind. Cached process-wide: one env read at
/// first request, reused thereafter.
fn environment_label() -> &'static str {
    static ENV_LABEL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    ENV_LABEL.get_or_init(|| {
        std::env::var("RUSTIO_ENV").unwrap_or_else(|_| {
            if cfg!(debug_assertions) {
                "Development".into()
            } else {
                "Production".into()
            }
        })
    })
}

/// Stable CSS-class discriminator paired with `environment_label`.
/// Free-text labels (`Staging`, `Sandbox`, …) collapse to `other`
/// so the footer's coloured dot only lights for the two operational
/// extremes.
fn environment_kind(label: &str) -> &'static str {
    match label.to_ascii_lowercase().as_str() {
        "production" | "prod" => "prod",
        "development" | "dev" => "dev",
        _ => "other",
    }
}

impl BaseContext {
    // internal:
    pub(crate) fn new(identity: Option<&Identity>, csrf_token: String, admin: &Admin) -> Self {
        let b = admin.branding();
        let (is_demo_session, demo_label) = match identity {
            Some(i) => (i.is_demo, i.demo_label.clone()),
            None => (false, None),
        };
        let theme = admin.active_theme();
        let accent_hex = theme.accent.clone();
        let accent_rgb = accent_hex.as_deref().map(hex_to_rgb_triplet);
        let env_label = environment_label();
        Self {
            identity: identity.map(IdentityCtx::from),
            csrf_token,
            site_title: b.site_title.clone(),
            site_header: b.site_header.clone(),
            index_title: b.index_title.clone(),
            footer_copyright: b.footer_copyright.clone(),
            app_name: b.app_name.clone(),
            app_tagline: b.app_tagline.clone(),
            show_powered_by: b.show_powered_by,
            framework_version: env!("CARGO_PKG_VERSION"),
            environment_label: env_label,
            environment_kind: environment_kind(env_label),
            server_now: chrono::Utc::now().format("%Y-%m-%d %H:%M UTC").to_string(),
            is_demo_session,
            demo_label,
            has_theme_overrides: theme.has_overrides(),
            accent_hex,
            accent_rgb,
            theme_bg: theme.bg.clone(),
            theme_surface: theme.surface.clone(),
            theme_text: theme.text.clone(),
            theme_text_muted: theme.text_muted.clone(),
            theme_border: theme.border.clone(),
            read_only: admin.is_read_only(),
            unread_count: 0,
        }
    }

    // internal:
    /// Builder helper — chain after [`Self::new`] to pin the
    /// operator's unread-notification count for the topbar badge.
    /// Handlers that want the badge to render on their page
    /// pre-fetch via [`crate::admin::notifications::unread_count`]
    /// and pass it in. Pages that skip this stay at the default
    /// `0` and the topbar shows just the bare bell.
    pub(crate) fn with_unread_count(mut self, n: i64) -> Self {
        self.unread_count = n.max(0);
        self
    }
}

#[derive(Serialize)]
pub(crate) struct SidebarEntry {
    pub admin_name: &'static str,
    pub display_name: &'static str,
}

impl From<&AdminEntry> for SidebarEntry {
    fn from(e: &AdminEntry) -> Self {
        Self {
            admin_name: e.admin_name,
            display_name: e.display_name,
        }
    }
}

#[derive(Serialize)]
pub(crate) struct FlashCtx {
    pub kind: &'static str,
    pub message: String,
}

// ---- Login -----------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct LoginCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub error: Option<String>,
    pub sections: Vec<FormSection>,
    pub flash: Option<FlashCtx>,
}

/// Pre-built FormField list for the login form. Static because the
/// values never change between requests; built once and cloned.
pub(crate) fn login_form_sections() -> Vec<FormSection> {
    vec![FormSection {
        title: None,
        fields: vec![
            FormField {
                name: "email",
                label: "Email".to_string(),
                widget: "input",
                input_type: "email",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 1,
                autocomplete: Some("username"),
                autofocus: true,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "password",
                label: "Password".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 1,
                autocomplete: Some("current-password"),
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
        ],
    }]
}

// ---- Dashboard ------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct DashboardCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub entries: Vec<SidebarEntry>,
    pub apps: Vec<DashboardApp>,
    pub recent_actions: Vec<RecentActionCtx>,
    pub flash: Option<FlashCtx>,
    /// Friendly greeting label — first segment of the identity's
    /// email (`alice` from `alice@example.com`), title-cased. The
    /// template uses it for the welcome header so it doesn't read
    /// as "Welcome, alice@example.com" (too formal / too long).
    pub greeting_name: String,
    /// Total project models registered (excludes the synthetic
    /// User entry). Surfaces in the stats strip.
    pub total_models: usize,
    /// Sum of `row_estimate` across every registered project model.
    /// Inherits the "approximate" caveat from `pg_class.reltuples`.
    pub total_rows: i64,
    /// `recent_actions.len()` — pre-computed so the template can
    /// show "Recent activity (N)" without a `length` filter.
    pub recent_actions_count: usize,
    /// 7-day audit-action counts (today − 6 .. today, UTC),
    /// padded with zeros for days with no activity. Drives an
    /// inline-SVG sparkline above the recent-activity list.
    pub activity_sparkline: Vec<DaySparkPoint>,
    /// Peak count in `activity_sparkline`, pre-computed so the
    /// template can size bars without a `max` filter. `0` when
    /// the audit table is empty or the query failed — the
    /// template clamps the divisor to 1 so the SVG still renders.
    pub activity_sparkline_max: i64,
    /// Total count across `activity_sparkline` — a one-liner
    /// "N actions in the last 7 days" caption.
    pub activity_sparkline_total: i64,
}

/// One bar in the dashboard's 7-day activity sparkline.
#[derive(Serialize)]
pub(crate) struct DaySparkPoint {
    /// `YYYY-MM-DD` of the day this point covers (UTC).
    pub date_iso: String,
    /// Short weekday label (`Mon`, `Tue`, …) — locale-neutral,
    /// suitable for the x-axis legend.
    pub label: &'static str,
    /// Audit-action count for the day; `0` when there's no
    /// activity.
    pub count: i64,
}

#[derive(Serialize)]
pub(crate) struct DashboardApp {
    pub label: String,
    pub models: Vec<DashboardModel>,
}

#[derive(Serialize)]
pub(crate) struct DashboardModel {
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub field_count: usize,
    /// Approximate row count from `pg_class.reltuples`, surfaced
    /// on the dashboard as "~ N". Refreshed by `ANALYZE` /
    /// autovacuum, not by every INSERT — operators read it as
    /// approximate, not ground truth. Zero when the table hasn't
    /// been analysed yet (fresh DB) or when the lookup query
    /// failed.
    pub row_estimate: i64,
    /// Exact count of rows whose `created_at > NOW() - INTERVAL
    /// '7 days'`. `None` for models that don't declare a
    /// `created_at` column. Surfaced on the dashboard tile as
    /// "N new this week" when set.
    pub new_this_week: Option<i64>,
    /// 7-day creation series for this model (`today-6 .. today`
    /// UTC, zero-padded). `None` for models without a
    /// `created_at` column. Drives the inline mini-sparkline
    /// next to the row count.
    pub weekly_series: Option<Vec<i64>>,
    /// Peak value in `weekly_series` — pre-computed so the
    /// template sizes bars without a `max` filter. Stays 0
    /// when the series is absent or all-zero; the template
    /// clamps the divisor.
    pub weekly_series_max: i64,
}

#[derive(Serialize)]
pub(crate) struct RecentActionCtx {
    pub action_type: String,
    pub label: &'static str,
    pub pill_class: &'static str,
    pub model_name: String,
    pub object_id: i64,
    pub user_email: String,
    pub summary: String,
    pub when_relative: String,
}

/// Group every `AdminEntry` by `app_label` derived from `admin_name`.
///
/// Convention: if `admin_name` contains a `.`, the prefix is the app
/// label (`"tolkhuset.translators"` → label `"Tolkhuset"`); the
/// remaining path is the model slug. Otherwise the whole `admin_name`
/// becomes a single-app label, capitalised.
///
/// `row_estimates` is keyed by `entry.table`; missing entries default
/// to `0` (fresh DB, never analysed, or query failed). Pass an empty
/// map to skip the per-model count column. `new_this_week` is keyed
/// by `entry.table` and carries an exact count for models that
/// declare `created_at`; absence (the common case for tables without
/// that column) renders the tile without the secondary stat.
pub(crate) fn group_entries_by_app(
    entries: &[AdminEntry],
    row_estimates: &HashMap<&str, i64>,
    new_this_week: &HashMap<&str, i64>,
    per_model_series: &HashMap<&str, Vec<i64>>,
) -> Vec<DashboardApp> {
    let mut apps: Vec<DashboardApp> = Vec::new();
    for entry in entries {
        // Core entries (the synthetic User) have a bespoke admin page;
        // listing them here would offer Add/Change actions that route
        // through `CoreUserOps`, which is route-only — those would 500.
        if entry.core {
            continue;
        }
        let label = app_label_for(entry.admin_name);
        let app = match apps.iter_mut().find(|a| a.label == label) {
            Some(a) => a,
            None => {
                apps.push(DashboardApp {
                    label: label.clone(),
                    models: Vec::new(),
                });
                apps.last_mut().unwrap()
            }
        };
        let estimate = row_estimates.get(entry.table).copied().unwrap_or(0).max(0);
        let week = new_this_week.get(entry.table).copied().map(|n| n.max(0));
        let series = per_model_series.get(entry.table).cloned();
        let series_max = series
            .as_ref()
            .and_then(|s| s.iter().copied().max())
            .unwrap_or(0)
            .max(0);
        app.models.push(DashboardModel {
            admin_name: entry.admin_name,
            display_name: entry.display_name,
            field_count: entry.fields.len(),
            row_estimate: estimate,
            new_this_week: week,
            weekly_series: series,
            weekly_series_max: series_max,
        });
    }
    apps
}

pub(crate) fn app_label_for(admin_name: &str) -> String {
    let prefix = admin_name.split('.').next().unwrap_or(admin_name);
    capitalise(prefix)
}

fn capitalise(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn dashboard_ctx(
    identity: &Identity,
    admin: &Admin,
    recent_actions: Vec<AdminAction>,
    csrf_token: String,
    row_estimates: &HashMap<&str, i64>,
    new_this_week: &HashMap<&str, i64>,
    per_model_series: &HashMap<&str, Vec<i64>>,
    activity_sparkline: Vec<DaySparkPoint>,
) -> DashboardCtx {
    let recent: Vec<RecentActionCtx> = recent_actions
        .into_iter()
        .map(|a| RecentActionCtx {
            action_type: a.action_type.clone(),
            label: action_label(&a.action_type),
            pill_class: action_pill_class(&a.action_type),
            model_name: a.model_name,
            object_id: a.object_id,
            user_email: a.user_email.unwrap_or_else(|| "".to_string()),
            summary: a.summary,
            when_relative: relative_time(a.timestamp),
        })
        .collect();

    let apps = group_entries_by_app(
        admin.entries(),
        row_estimates,
        new_this_week,
        per_model_series,
    );
    let total_models = apps.iter().map(|a| a.models.len()).sum();
    let total_rows = apps
        .iter()
        .flat_map(|a| a.models.iter())
        .map(|m| m.row_estimate)
        .sum();
    let recent_actions_count = recent.len();
    let greeting_name = greeting_from_email(&identity.email);
    let activity_sparkline_max = activity_sparkline
        .iter()
        .map(|p| p.count)
        .max()
        .unwrap_or(0)
        .max(0);
    let activity_sparkline_total = activity_sparkline.iter().map(|p| p.count).sum();

    DashboardCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        apps,
        recent_actions: recent,
        flash: None,
        greeting_name,
        total_models,
        total_rows,
        recent_actions_count,
        activity_sparkline,
        activity_sparkline_max,
        activity_sparkline_total,
    }
}

/// Pick a friendly greeting label from an identity email.
///
/// `alice@example.com` → `Alice`, `clinic.admin@…` → `Clinic Admin`,
/// `_root` → `Root`. The result is plain text used in the dashboard
/// welcome header; no HTML escaping required at this layer (minijinja
/// auto-escapes on render).
fn greeting_from_email(email: &str) -> String {
    let local = email.split('@').next().unwrap_or(email);
    let cleaned: String = local
        .split(['.', '_', '-'])
        .filter(|s| !s.is_empty())
        .map(capitalise)
        .collect::<Vec<_>>()
        .join(" ");
    if cleaned.is_empty() {
        "there".to_string()
    } else {
        cleaned
    }
}

/// Template context for `/admin/account/sessions` (read-only in R0).
#[derive(Serialize)]
pub(crate) struct AccountSessionsCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub entries: Vec<SidebarEntry>,
    pub sessions: Vec<AccountSessionRowCtx>,
}

#[derive(Serialize)]
pub(crate) struct AccountSessionRowCtx {
    pub session_id: i64,
    pub trust_label: &'static str,
    pub is_current: bool,
    pub ip: String,
    pub ua_summary: String,
    pub created_at: String,
    pub last_seen_relative: String,
    pub expires_relative: String,
}

pub(crate) fn account_sessions_ctx(
    identity: &Identity,
    admin: &Admin,
    sessions: Vec<crate::auth::Session>,
    current_session_id: Option<i64>,
    csrf_token: String,
) -> AccountSessionsCtx {
    let rows = sessions
        .into_iter()
        .map(|s| AccountSessionRowCtx {
            session_id: s.session_id,
            trust_label: trust_label(s.trust_level),
            is_current: Some(s.session_id) == current_session_id,
            ip: s.ip.unwrap_or_else(|| "".to_string()),
            ua_summary: summarise_user_agent(s.user_agent.as_deref()),
            created_at: s.created_at.format("%Y-%m-%d %H:%M").to_string(),
            last_seen_relative: relative_time(s.last_seen),
            expires_relative: relative_time(s.expires_at),
        })
        .collect();

    AccountSessionsCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: "Active sessions",
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        sessions: rows,
    }
}

const fn trust_label(t: crate::auth::SessionTrust) -> &'static str {
    match t {
        crate::auth::SessionTrust::Authenticated => "Signed in",
        crate::auth::SessionTrust::Elevated => "Elevated",
        crate::auth::SessionTrust::MfaVerified => "MFA verified",
    }
}

/// Heuristic User-Agent → short summary. Doctrine 20 — no fancy
/// risk scoring or device fingerprinting; just a deterministic
/// substring lookup so the table cell reads "macOS · Safari" instead
/// of an 80-char Mozilla string.
///
/// Returns "—" when no UA is recorded.
pub(crate) fn summarise_user_agent(ua: Option<&str>) -> String {
    let Some(ua) = ua else {
        return "".to_string();
    };
    let lc = ua.to_ascii_lowercase();

    // Order matters: iPhone / iPad UAs still include "Mac OS X"
    // (Apple convention), and Android UAs include "Linux". Check the
    // most-specific identifiers first.
    let os = if lc.contains("windows") {
        "Windows"
    } else if lc.contains("iphone") {
        "iOS"
    } else if lc.contains("ipad") {
        "iPadOS"
    } else if lc.contains("android") {
        "Android"
    } else if lc.contains("mac os x") || lc.contains("macos") {
        "macOS"
    } else if lc.contains("linux") {
        "Linux"
    } else {
        ""
    };

    let browser = if lc.contains("firefox") {
        "Firefox"
    } else if lc.contains("edg/") {
        "Edge"
    } else if lc.contains("opr/") || lc.contains("opera") {
        "Opera"
    } else if lc.contains("chrome") {
        "Chrome"
    } else if lc.contains("safari") {
        "Safari"
    } else if lc.contains("curl") {
        "curl"
    } else {
        ""
    };

    if os == "" && browser == "" {
        ua.chars().take(40).collect()
    } else {
        format!("{os} · {browser}")
    }
}

/// Human label for the `Action` column on `/admin/history` and the
/// per-object history pages. Covers every `AuditEvent::as_str()`
/// string (`admin/audit.rs`'s `ActionType` + `AuditEvent` namespaces
/// together — see `audit::tests::action_type_and_audit_event_vocabularies_dont_collide`).
///
/// `VISIBILITY_AUDIT.md` finding B3: pre-0.8.1 this function knew
/// only `create / update / delete` and fell through to a generic
/// "Action" label for every R1+ event. The history table rendered
/// rows of identical green chips that hid which user action
/// produced the row — exactly the audit-log readability regression
/// the brief flagged.
fn action_label(action_type: &str) -> &'static str {
    match action_type {
        // Legacy `ActionType` namespace (generic CRUD on
        // project-registered models).
        "create" => "Created",
        "update" => "Changed",
        "delete" => "Deleted",

        // User / Group lifecycle (R0).
        "user_created" => "User created",
        "user_updated" => "User updated",
        "user_deleted" => "User deleted",
        "group_created" => "Group created",
        "group_updated" => "Group updated",
        "group_deleted" => "Group deleted",

        // R1 self-recovery.
        "password_changed_self" => "Password changed",
        "password_reset_self_request" => "Reset link requested",
        "password_reset_self_consume" => "Reset link consumed",

        // R2 organisational recovery.
        "password_reset_by_other" => "Password reset by admin",
        "forced_password_change_completed" => "Forced password change",
        "account_locked" => "Account locked",
        "account_unlocked" => "Account unlocked",

        // R3 TOTP MFA.
        "mfa_enabled" => "MFA enabled",
        "mfa_disabled" => "MFA disabled",
        "mfa_reset_by_other" => "MFA reset by admin",
        "mfa_code_consumed" => "Backup code used",
        "backup_codes_regenerated" => "Backup codes regenerated",

        // R0/R1 session lifecycle.
        "sessions_revoked_self" => "Sessions revoked (self)",
        "sessions_revoked_by_other" => "Sessions revoked by admin",
        "session_logout" => "Logged out",

        // Authentication events.
        "login_succeeded" => "Signed in",
        "login_failed" => "Failed sign-in",

        // R4 shell-tier emergency recovery (CLI-only emissions).
        "emergency_recovery" => "Emergency recovery",

        _ => "Action",
    }
}

fn action_pill_class(action_type: &str) -> &'static str {
    match action_type {
        // Created / enabled (good news) → success green.
        "create" | "user_created" | "group_created" | "account_unlocked" | "mfa_enabled" => {
            "badge-success"
        }

        // Destructive or compromise-shaped events → danger red.
        "delete"
        | "user_deleted"
        | "group_deleted"
        | "account_locked"
        | "mfa_disabled"
        | "mfa_reset_by_other"
        | "sessions_revoked_by_other"
        | "login_failed" => "badge-danger",

        // Admin-initiated mutations on a user → warning amber. Same
        // visual weight as the "by other" R2 events; signals the
        // row was driven by someone other than the subject.
        "password_reset_by_other" | "forced_password_change_completed" | "emergency_recovery" => {
            "badge-warning"
        }

        // Routine changes and self-driven events → neutral.
        _ => "badge-neutral",
    }
}

pub(crate) fn relative_time(ts: chrono::DateTime<chrono::Utc>) -> String {
    let now = chrono::Utc::now();
    let delta = now - ts;
    if delta.num_seconds() < 60 {
        "just now".to_string()
    } else if delta.num_minutes() < 60 {
        format!("{}m ago", delta.num_minutes())
    } else if delta.num_hours() < 24 {
        format!("{}h ago", delta.num_hours())
    } else if delta.num_days() < 30 {
        format!("{}d ago", delta.num_days())
    } else {
        ts.format("%Y-%m-%d").to_string()
    }
}

// ---- Changelist (list page) ----------------------------------------------

#[derive(Serialize)]
pub(crate) struct ListField {
    pub name: String,
    pub label: String,
    /// `FieldType::widget()`'s output: `"text"` / `"number"` /
    /// `"checkbox"` / `"datetime"`. The list template dispatches on
    /// this rather than duck-typing on the cell's string shape.
    pub kind: &'static str,
    /// Sort hint for sortable column headers in `list.html`.
    /// `"asc"` → header link toggles to descending;
    /// `"desc"` → header link clears the sort (back to default);
    /// empty → header link sets ascending.
    pub sort_active: &'static str,
    /// URL the sortable header link points to. Pre-baked here so the
    /// template doesn't need to reproduce the toggle logic.
    pub sort_link: String,
}

#[derive(Serialize)]
pub(crate) struct ListCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    pub fields: Vec<ListField>,
    pub rows: Vec<ListRowCtx>,
    pub search_query: String,
    pub filters: Vec<FilterGroupCtx>,
    /// Count of filter groups whose user-selected value is non-empty.
    /// Drives the "Filters (N)" badge on the toolbar dropdown toggle.
    pub active_filter_count: usize,
    /// `(field, value)` pairs for every currently-set filter. The
    /// search form renders these as hidden inputs so submitting a
    /// query doesn't drop the active filters.
    pub active_filter_pairs: Vec<(String, String)>,
    /// Display-ready pills for every currently-set filter: friendly
    /// label, pretty value, and a remove-link that drops only this
    /// filter while keeping query / sort / other filters. Drives the
    /// "active filters" strip below the toolbar.
    pub active_filter_pills: Vec<ActiveFilterPillCtx>,
    /// URL the "Clear all" filters action navigates to: keeps the
    /// search query and sort, drops every filter.
    pub clear_all_filters_link: String,
    /// URL the toolbar's "Download CSV" link navigates to. Preserves
    /// the current search / filters / sort but drops `page` /
    /// `per_page` (CSV is paginate-free). Routes to the bulk export
    /// endpoint registered at `/admin/<name>/export.csv`.
    pub csv_export_url: String,
    /// Legacy sort-dropdown options — every visible field × {asc, desc}
    /// plus a leading "Default order" reset link. Kept on `ListCtx`
    /// for back-compat with project templates that still consume the
    /// pre-0.21.1 mega-dropdown; the framework's own `list.html` now
    /// uses [`Self::sort_fields`] + the direction toggle below.
    pub sort_options: Vec<SortOptionCtx>,
    /// Toolbar label for the legacy Sort toggle: "Default order" when
    /// no override is in effect, otherwise the active option's label.
    pub current_sort_label: String,
    /// Per-field rows for the redesigned Sort menu — one entry per
    /// sortable column. See [`SortFieldCtx`] for the field shape and
    /// the rationale behind the field-once layout.
    pub sort_fields: Vec<SortFieldCtx>,
    /// Toolbar label for the redesigned Sort toggle: the active
    /// field's `label` (e.g. "Scheduled At"), or "Default order"
    /// when no override is in effect.
    pub current_sort_field_label: String,
    /// Direction-aware copy for the toolbar's direction toggle:
    /// "newest first" / "oldest first" for datetime, "A → Z" /
    /// "Z → A" for text, etc. Empty when no sort override is in
    /// effect (the toggle is hidden in that state).
    pub current_sort_dir_label: &'static str,
    /// URL the direction toggle navigates to — flips the active
    /// field's direction while preserving search / filters /
    /// per-page. Empty when no sort is active.
    pub sort_dir_toggle_link: String,
    /// URL the Sort menu's "Default order" reset row navigates to —
    /// clears the sort while preserving search / filters / per-page.
    /// Same URL as `sort_options[0].link`; surfaced separately so the
    /// new template can render it without indexing into the legacy
    /// vec.
    pub default_sort_link: String,
    /// Active sort field + direction surfaced as plain strings so the
    /// search form can carry them as hidden inputs. `None` when no
    /// sort override is in effect.
    pub active_sort_field: Option<String>,
    pub active_sort_dir: Option<&'static str>,
    /// Per-page dropdown options (allow-listed: 25 / 50 / 100 / 200).
    pub per_page_options: Vec<PerPageOptionCtx>,
    /// Toolbar label for the per-page toggle: "50 / page" etc.
    pub current_per_page_label: String,
    /// `Some` when the URL carries an explicit `?per_page=…`. Hidden
    /// in the search form so query submission keeps the user's
    /// row-density choice; absent → fall back to model default.
    pub active_per_page_override: Option<usize>,
    pub page: usize,
    pub total_pages: usize,
    pub per_page: usize,
    pub total_rows: usize,
    /// Pre-baked URLs for the pagination strip. `None` when at the
    /// boundary (page 1 has no prev; last page has no next).
    pub prev_page_link: Option<String>,
    pub next_page_link: Option<String>,
    /// Numbered-page items for the pagination strip. For `total_pages
    /// ≤ 7` every page is listed in order; otherwise the list is
    /// compressed to first / current ±1 / last with `Ellipsis`
    /// markers in the gaps. Always empty when `total_pages == 1`.
    pub page_items: Vec<PageItem>,
    /// Whether the bulk-action UI should render. Always `false` until
    /// the bulk-action POST endpoint is wired in a later phase.
    pub bulk_actions_enabled: bool,
    /// Project-defined bulk actions registered via
    /// `ModelAdmin::bulk_actions()`. Rendered as extra buttons in
    /// the list-view bulk bar next to the framework's built-in
    /// Delete. Each button POSTs to `/admin/:model/bulk/:name`.
    pub bulk_action_buttons: Vec<BulkActionBtnCtx>,
    /// Per-user bookmarkable filter presets for this model. Each
    /// entry carries an `apply_url`, a `delete_url` (per-row form),
    /// and an `is_current` flag set when its `query_string` matches
    /// the current request's. Empty vec hides the Saved dropdown.
    pub saved_filters: Vec<SavedFilterBtnCtx>,
    /// Raw query string of the current request (without leading
    /// `?`). The Saved dropdown's "Save current view" form posts
    /// this verbatim so the bookmark captures the exact state the
    /// operator is looking at.
    pub current_query_string: String,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct SavedFilterBtnCtx {
    pub id: i64,
    pub name: String,
    /// `/admin/<model>?<saved query>` — the apply link. Empty
    /// query collapses to `/admin/<model>` (the "default view"
    /// bookmark).
    pub apply_url: String,
    /// `/admin/<model>/saved_filters/<id>/delete` — POST target
    /// for the per-row delete form.
    pub delete_url: String,
    /// `true` when this saved filter's `query_string` matches the
    /// current request. Drives a visual `is-active` marker so the
    /// operator sees which preset they're looking at.
    pub is_current: bool,
}

#[derive(Serialize)]
pub(crate) struct BulkActionBtnCtx {
    pub name: &'static str,
    pub label: &'static str,
    pub destructive: bool,
    pub form_action: String,
}

/// `values` is flattened into the JSON object so template code can do
/// `row[field.name]` (minijinja resolves dict subscript on the merged
/// map). The explicit `id: i64` field stays out of the flattened map.
#[derive(Serialize)]
pub(crate) struct ListRowCtx {
    pub id: i64,
    #[serde(flatten)]
    pub values: HashMap<String, serde_json::Value>,
    /// Per-column FK click-through links. Keyed by column name; value
    /// is the target's `/admin/{admin_name}/{id}/edit` URL. Populated
    /// by `handlers::hydrate_fk_cells` for relation-bearing columns
    /// and consumed by the list template to wrap the cell in `<a>`.
    pub links: HashMap<String, String>,
    /// Pre-escaped HTML fragments wrapping `?q=…` matches in `<mark>`
    /// tags. Only populated for columns the search actually scanned
    /// (`ModelAdmin::search_fields()`) and that contain at least one
    /// match. Cells with no entry here render via the plain string
    /// path in `values`; cells WITH an entry render the HTML fragment
    /// via `|safe` in the template.
    pub highlights: HashMap<String, String>,
}

#[derive(Serialize)]
pub(crate) struct FilterGroupCtx {
    pub field: String,
    pub label: String,
    /// `"chips"` for the discrete-option dropdown (Yes/No, status, …).
    /// `"date_range"` for the two-date-input form. Template branches
    /// on this string. Defaults to `"chips"` so existing call sites
    /// stay correct without touching them.
    #[serde(default = "default_filter_kind")]
    pub kind: &'static str,
    pub options: Vec<FilterOptionCtx>,
    pub current: Option<String>,
    /// URL for the "All" chip — clears this group while keeping every
    /// other piece of list state (search query, other filters, sort).
    /// Pre-baked in `list_ctx` so the template doesn't reproduce the
    /// URL-composition rules. Defaults to empty before `list_ctx`
    /// patches it in (handlers don't construct this field directly).
    #[serde(default)]
    pub all_link: String,
    /// `date_range` only: the currently-selected lower bound
    /// (`YYYY-MM-DD`) and the URL-parameter name the form must
    /// submit it under (`<field>__gte`).
    #[serde(default)]
    pub date_from_name: String,
    #[serde(default)]
    pub date_from_value: String,
    /// Upper bound counterpart — `<field>__lte`.
    #[serde(default)]
    pub date_to_name: String,
    #[serde(default)]
    pub date_to_value: String,
    /// `date_range` only: hidden inputs the form must carry to keep
    /// every other filter / sort / per_page selection across an
    /// Apply submit. Patched by `list_ctx`. Empty until then.
    #[serde(default)]
    pub hidden_pairs: Vec<(String, String)>,
    /// `date_range` only: `true` when at least one bound is set —
    /// drives the "Clear" affordance.
    #[serde(default)]
    pub has_active_range: bool,
    /// `multi_select` only: the currently-checked values, in their
    /// declared order. Used both to render the active-filter pill
    /// (`"active, pending"`) and to round-trip the same selections
    /// as hidden inputs in every neighbouring widget's URL.
    #[serde(default)]
    pub multi_selected: Vec<String>,
    /// `fk_autocomplete` only: the currently-selected FK id (as a
    /// string for HTML attribute use) and the resolved display
    /// label. Both empty when nothing is selected.
    #[serde(default)]
    pub fk_selected_id: String,
    #[serde(default)]
    pub fk_selected_label: String,
    /// `fk_autocomplete` only: relative URL the JS typeahead fetches
    /// for candidate rows (`/admin/_lookup/<target_admin_name>`).
    #[serde(default)]
    pub fk_lookup_url: String,
    /// `fk_autocomplete` only: target model's display name, used
    /// for the input placeholder ("Search Author…").
    #[serde(default)]
    pub fk_target_label: String,
}

fn default_filter_kind() -> &'static str {
    "chips"
}

#[derive(Serialize)]
pub(crate) struct FilterOptionCtx {
    pub value: String,
    pub label: String,
    pub selected: bool,
    /// URL the chip navigates to: applies this option to its group
    /// while preserving search / other filters / sort. Pre-baked in
    /// `list_ctx`. Empty until then.
    #[serde(default)]
    pub link: String,
}

/// One option in the toolbar's Sort dropdown — a field × direction
/// pair, or the "Default order" reset link. The label is field-type
/// aware ("A → Z" for text, "newest first" for datetime, etc.) so the
/// dropdown reads as English, not as a query string.
#[derive(Serialize)]
pub(crate) struct SortOptionCtx {
    pub label: String,
    pub link: String,
    pub is_active: bool,
}

/// One row in the redesigned Sort menu — *one entry per sortable
/// field*. The toolbar's previous "View" mega-dropdown emitted two
/// rows per field (asc + desc), so a model with eight columns
/// produced a 17-row menu (8 × 2 + Default) that operators had to
/// scan twice for the same label. `SortFieldCtx` collapses that to
/// one row per field; direction is selected by a sibling toggle
/// control whose URL is pre-baked into `sort_dir_toggle_link` on
/// the parent `ListCtx`.
///
/// Each entry carries explicit `asc_link` / `desc_link` URLs (both
/// passed through `build_list_url`) so the field row can render
/// either as a single "sort by X" click that defaults to ascending,
/// or — for power use — as a two-button group exposing both
/// directions inline. Direction-aware *labels*
/// ("newest first" / "A → Z") stay alongside the URLs so the
/// template can surface them without re-running `sort_direction_label`.
#[derive(Serialize)]
pub(crate) struct SortFieldCtx {
    /// Field name as it appears on the URL (`?sort=<field>`). Used
    /// only when the template needs the raw key; rendering reads
    /// `label` instead.
    pub field: String,
    /// Human-readable column label, identical to the table header
    /// label so the menu reads as "Sort by <column name>".
    pub label: String,
    /// URL that activates ascending sort for this field while
    /// preserving search / filters / per-page. Always populated.
    pub asc_link: String,
    /// URL that activates descending sort for this field.
    pub desc_link: String,
    /// Field-type-aware ascending label — "A → Z" for text,
    /// "oldest first" for datetime, "off → on" for bool, etc.
    pub asc_label: &'static str,
    /// Counterpart descending label — "Z → A", "newest first",
    /// "on → off".
    pub desc_label: &'static str,
    /// `true` when this field is the currently sorted column.
    /// Drives the menu's "selected" affordance and tells the
    /// direction toggle which field's URL to anchor against.
    pub is_active: bool,
}

/// One option in the toolbar's per-page dropdown. The link goes
/// through `build_list_url` so search / filter / sort survive a
/// row-density change. Page resets to 1 — staying on page N at a
/// new density would land somewhere arbitrary.
#[derive(Serialize)]
pub(crate) struct PerPageOptionCtx {
    pub value: usize,
    pub label: String,
    pub link: String,
    pub is_active: bool,
}

/// One pill in the "active filters" strip below the toolbar. `label`
/// is the field's human label, `value_label` is the option's display
/// text (not the raw URL value), and `remove_link` is the URL that
/// drops only this filter — query, sort, and the rest of the filter
/// set are preserved.
#[derive(Serialize)]
pub(crate) struct ActiveFilterPillCtx {
    pub label: String,
    pub value_label: String,
    pub remove_link: String,
}

/// One slot in the pagination strip — either a numbered page (with a
/// pre-baked link and an active marker) or a `…` gap. The template
/// renders the variant via the serialized `kind` discriminant.
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum PageItem {
    Number {
        number: usize,
        link: String,
        is_active: bool,
    },
    Ellipsis,
}

/// Build the numbered-page strip. Up to 7 pages render in full; past
/// that the list compresses to first, current ± 1, last with `…` in
/// the gaps. The build_link closure handles URL composition so this
/// helper stays unaware of search / filter / sort state.
fn build_page_items(
    current: usize,
    total: usize,
    build_link: impl Fn(usize) -> String,
) -> Vec<PageItem> {
    if total <= 1 {
        return Vec::new();
    }
    let mk = |n: usize| PageItem::Number {
        number: n,
        link: build_link(n),
        is_active: n == current,
    };
    if total <= 7 {
        return (1..=total).map(mk).collect();
    }
    let mut items: Vec<PageItem> = Vec::with_capacity(9);
    items.push(mk(1));
    if current > 3 {
        items.push(PageItem::Ellipsis);
    }
    let start = current.saturating_sub(1).max(2);
    let end = (current + 1).min(total - 1);
    for n in start..=end {
        items.push(mk(n));
    }
    if current + 2 < total {
        items.push(PageItem::Ellipsis);
    }
    items.push(mk(total));
    items
}

/// Field-type-aware copy for an `(field_type, direction)` pair.
/// Datetime descending reads as "newest first"; string ascending as
/// "A → Z"; everything else falls back to ascending/descending.
///
/// `FilePath` / `OptionalFilePath` are stored as strings in the DB
/// (they're `TEXT` paths under the uploads dir) and sort
/// lexicographically — so they share the `String` branch's
/// `A → Z` / `Z → A` copy rather than the generic
/// `ascending` / `descending` fallback that read awkwardly in
/// the sort dropdown.
fn sort_direction_label(
    field_type: super::types::FieldType,
    dir: super::modeladmin::SortDir,
) -> &'static str {
    use super::modeladmin::SortDir;
    use super::types::FieldType::*;
    match (field_type, dir) {
        (DateTime | OptionalDateTime, SortDir::Desc) => "newest first",
        (DateTime | OptionalDateTime, SortDir::Asc) => "oldest first",
        (String | OptionalString | FilePath | OptionalFilePath, SortDir::Asc) => "A → Z",
        (String | OptionalString | FilePath | OptionalFilePath, SortDir::Desc) => "Z → A",
        (I32 | I64 | OptionalI64, SortDir::Desc) => "highest first",
        (I32 | I64 | OptionalI64, SortDir::Asc) => "lowest first",
        (Bool, SortDir::Asc) => "off → on",
        (Bool, SortDir::Desc) => "on → off",
    }
    // FieldType is #[non_exhaustive] for downstream callers, but
    // within this crate the match must stay exhaustive — adding a
    // catch-all here would mask the missing arm a future variant
    // (e.g. `Numeric`, `Json`, `Uuid`) introduces. Forcing the next
    // contributor to pick deliberate direction copy for the new
    // type is the whole point of this function.
}

/// Compose a list-view URL with full query-state preservation.
///
/// Every link the list view emits — filter chips, sort options,
/// pagination, header-sort arrows, per-page picker — runs through
/// here so a click on one widget doesn't silently drop the others.
/// Inputs:
///
///   - `q` — current search query; `""` skipped
///   - `filters` — currently-set filters as `(field, value)` pairs;
///     callers compose their own override (set, clear, swap) before
///     passing this in
///   - `sort` — the desired sort, or `None` for "model default"
///   - `page` — `1` is implicit and skipped from the URL
///   - `per_page` — `Some(N)` carries an explicit row-density choice
///     into the URL; `None` means "use the model default" (no
///     `&per_page=…` segment emitted)
///
/// Append `c` to `out`, escaping the five HTML special chars.
/// Smaller than pulling a crate for the same job — the list view's
/// only escaping need is "treat this cell as plain text inside HTML."
fn push_html_escaped(out: &mut String, c: char) {
    match c {
        '&' => out.push_str("&amp;"),
        '<' => out.push_str("&lt;"),
        '>' => out.push_str("&gt;"),
        '"' => out.push_str("&quot;"),
        '\'' => out.push_str("&#39;"),
        other => out.push(other),
    }
}

fn push_html_escaped_str(out: &mut String, s: &str) {
    for c in s.chars() {
        push_html_escaped(out, c);
    }
}

/// Wrap every occurrence of `term` inside `text` with `<mark>…</mark>`,
/// HTML-escaping the rest. Returns `None` when the term doesn't
/// appear at all so the caller can keep using the plain-string
/// render path (avoids both unnecessary `|safe` work and template
/// branching cost for rows the search never touched).
///
/// **Matching semantics**: ASCII-case-insensitive — `"anna"` matches
/// `"Anna Lindqvist"`. Non-ASCII characters compare exactly
/// (`"Wåhlin"` matches the literal substring `"Wåhlin"` but not
/// `"WÅHLIN"`). The byte-length invariant of `char::to_ascii_lowercase`
/// means byte indices into the original `text` and its
/// ASCII-lowercased twin line up perfectly, so we can slice the
/// original by indices found in the lowercase. Full Unicode case
/// folding is deliberately deferred — most admin search terms are
/// ASCII, and the missed-non-ASCII case still renders the row
/// correctly; only the highlight is absent.
fn highlight_search_match(text: &str, term: &str) -> Option<String> {
    if term.is_empty() {
        return None;
    }
    // ASCII-lowercase both strings while preserving non-ASCII chars
    // unchanged. `char::to_ascii_lowercase` is byte-length-preserving
    // for both ASCII and non-ASCII inputs, so byte offsets carry over.
    let text_lower: String = text.chars().map(|c| c.to_ascii_lowercase()).collect();
    let term_lower: String = term.chars().map(|c| c.to_ascii_lowercase()).collect();
    let term_bytes = term_lower.len();

    let first = text_lower.find(&term_lower)?;
    let mut out = String::with_capacity(text.len() + 16);
    push_html_escaped_str(&mut out, &text[..first]);
    let mut cursor = first;
    loop {
        out.push_str("<mark>");
        push_html_escaped_str(&mut out, &text[cursor..cursor + term_bytes]);
        out.push_str("</mark>");
        cursor += term_bytes;
        match text_lower[cursor..].find(&term_lower) {
            Some(rel) => {
                let next = cursor + rel;
                push_html_escaped_str(&mut out, &text[cursor..next]);
                cursor = next;
            }
            None => break,
        }
    }
    push_html_escaped_str(&mut out, &text[cursor..]);
    Some(out)
}

/// Values are URL-encoded so search strings with spaces or unicode
/// don't break the link.
fn build_list_url(
    admin_name: &str,
    q: &str,
    filters: &[(String, String)],
    sort: Option<(&str, super::modeladmin::SortDir)>,
    page: usize,
    per_page: Option<usize>,
) -> String {
    use super::modeladmin::SortDir;
    let mut parts: Vec<String> = Vec::new();
    if !q.is_empty() {
        parts.push(format!("q={}", urlencoding::encode(q)));
    }
    for (field, value) in filters {
        parts.push(format!(
            "{}={}",
            urlencoding::encode(field),
            urlencoding::encode(value),
        ));
    }
    if let Some((col, dir)) = sort {
        parts.push(format!("sort={}", urlencoding::encode(col)));
        parts.push(
            match dir {
                SortDir::Asc => "dir=asc",
                SortDir::Desc => "dir=desc",
            }
            .to_string(),
        );
    }
    if page > 1 {
        parts.push(format!("page={page}"));
    }
    if let Some(n) = per_page {
        parts.push(format!("per_page={n}"));
    }
    if parts.is_empty() {
        format!("/admin/{admin_name}")
    } else {
        format!("/admin/{}?{}", admin_name, parts.join("&"))
    }
}

/// CSV export URL: `<list-page filter/search/sort state>` against
/// `/admin/<name>/export.csv`. Mirrors `build_list_url` but drops
/// pagination — CSV ignores it. Kept narrow so the toolbar link is
/// guaranteed-distinct from any list-page link it sits next to.
fn build_csv_export_url(
    admin_name: &str,
    q: &str,
    filters: &[(String, String)],
    sort: Option<(&str, super::modeladmin::SortDir)>,
) -> String {
    use super::modeladmin::SortDir;
    let mut parts: Vec<String> = Vec::new();
    if !q.is_empty() {
        parts.push(format!("q={}", urlencoding::encode(q)));
    }
    for (field, value) in filters {
        parts.push(format!(
            "{}={}",
            urlencoding::encode(field),
            urlencoding::encode(value),
        ));
    }
    if let Some((col, dir)) = sort {
        parts.push(format!("sort={}", urlencoding::encode(col)));
        parts.push(
            match dir {
                SortDir::Asc => "dir=asc",
                SortDir::Desc => "dir=desc",
            }
            .to_string(),
        );
    }
    if parts.is_empty() {
        format!("/admin/{admin_name}/export.csv")
    } else {
        format!("/admin/{}/export.csv?{}", admin_name, parts.join("&"))
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn list_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    rows: Vec<ListRow>,
    search_query: String,
    mut filters: Vec<FilterGroupCtx>,
    page: usize,
    per_page: usize,
    // `per_page_override = Some(N)` when the URL carried an allow-listed
    // `?per_page=…`. `None` means the model default is in effect —
    // every state-preserving link below then omits the segment so
    // default URLs stay clean.
    per_page_override: Option<usize>,
    total_rows: usize,
    // `active_sort = (column, direction)` carries the parsed override
    // from `?sort=&dir=`. `None` means the model's
    // `ModelAdmin::ordering()` default is in effect — sortable
    // header links still render, but no column gets the active arrow.
    active_sort: Option<(String, super::modeladmin::SortDir)>,
    csrf_token: String,
    saved_filters: Vec<super::saved_filters::SavedFilter>,
    current_query_string: String,
) -> ListCtx {
    let total_pages = total_rows.div_ceil(per_page.max(1)).max(1);

    // ---- URL-state preservation -------------------------------------
    // Every link the list view emits — filter chips, sort options,
    // pagination, header sort arrows — composes its href via
    // `build_list_url` so clicking one widget never silently drops
    // the others. `active_filter_pairs` is the canonical view of
    // currently-set filters; widgets derive their override URLs from
    // a copy of it.
    // Active filter pairs span both the chip groups (one pair) and
    // the date-range groups (one pair per set bound, encoded under
    // `<field>__gte` / `<field>__lte`). Every state-preserving link
    // — chip All / chip option / sort / per-page / pagination — is
    // built from this flat list, so a single source of truth means
    // no widget can silently drop another widget's selection.
    let active_filter_pairs: Vec<(String, String)> = filters
        .iter()
        .flat_map(|g| {
            let mut pairs: Vec<(String, String)> = Vec::new();
            if let Some(v) = g.current.as_ref() {
                pairs.push((g.field.clone(), v.clone()));
            }
            if !g.date_from_value.is_empty() {
                pairs.push((g.date_from_name.clone(), g.date_from_value.clone()));
            }
            if !g.date_to_value.is_empty() {
                pairs.push((g.date_to_name.clone(), g.date_to_value.clone()));
            }
            // Multi-select round-trips one repeated pair per checked
            // value — `?status=active&status=pending`. Order matches
            // the field's declared `choices` so the rendered URL is
            // stable across reloads.
            for v in &g.multi_selected {
                pairs.push((g.field.clone(), v.clone()));
            }
            pairs
        })
        .collect();
    let active_sort_ref: Option<(&str, super::modeladmin::SortDir)> =
        active_sort.as_ref().map(|(c, d)| (c.as_str(), *d));

    // Patch each filter group's URLs in-place. "All" drops this
    // group from the active set; chip options replace the group's
    // current value; date-range forms keep every *other* pair as
    // hidden inputs and submit with their own field names. Page
    // resets to 1 — page N of one filter rarely matches up with
    // page N of another.
    for group in &mut filters {
        let other: Vec<(String, String)> = active_filter_pairs
            .iter()
            .filter(|(field, _)| {
                // A chip group owns one key (`field`); a date-range
                // group owns two (`field__gte`, `field__lte`); a
                // multi-select group owns its field name (with
                // repeated entries). The "other" list excludes
                // whichever keys this group controls so its own
                // URLs replace rather than duplicate.
                if group.kind == "date_range" {
                    field != &group.date_from_name && field != &group.date_to_name
                } else {
                    field != &group.field
                }
            })
            .cloned()
            .collect();
        group.all_link = build_list_url(
            entry.admin_name,
            &search_query,
            &other,
            active_sort_ref,
            1,
            per_page_override,
        );
        // Chip options (BoolYesNo): each chip composes a URL with
        // this group's value replaced. Multi-select uses the same
        // `options` slot, but the form handles state preservation
        // via hidden inputs + checkboxes, so per-option links here
        // would be misleading — leave them empty.
        if group.kind == "chips" {
            for opt in &mut group.options {
                let mut combined = other.clone();
                combined.push((group.field.clone(), opt.value.clone()));
                opt.link = build_list_url(
                    entry.admin_name,
                    &search_query,
                    &combined,
                    active_sort_ref,
                    1,
                    per_page_override,
                );
            }
        }
        // Date-range, multi-select, and FK-autocomplete all render
        // as forms; each needs every *other* filter / sort / per_page
        // pair as hidden inputs so submitting one widget preserves
        // the rest of the list-view state.
        if group.kind == "date_range"
            || group.kind == "multi_select"
            || group.kind == "fk_autocomplete"
        {
            group.hidden_pairs = other;
        }
    }

    let clear_all_filters_link = build_list_url(
        entry.admin_name,
        &search_query,
        &[],
        active_sort_ref,
        1,
        per_page_override,
    );

    // CSV export URL: same filter/search/sort state as the list
    // page but addressed to the export endpoint. Page / per_page
    // are dropped — the CSV ignores pagination entirely, so
    // carrying them would just clutter the link.
    let csv_export_url = build_csv_export_url(
        entry.admin_name,
        &search_query,
        &active_filter_pairs,
        active_sort_ref,
    );

    // Display-ready pills for the "active filters" strip. Each pill
    // resolves the option's friendly `value_label` from the group's
    // option list (so a stored "true" reads as "Yes", etc.), and its
    // `remove_link` drops only this filter — search query, sort, and
    // every other filter stay intact.
    let active_filter_pills: Vec<ActiveFilterPillCtx> = filters
        .iter()
        .filter_map(|g| {
            if g.kind == "fk_autocomplete" {
                if g.fk_selected_id.is_empty() {
                    return None;
                }
                // Pill text uses the hydrated row label so the user
                // sees "Author: Anna Lindqvist" rather than "Author:
                // 42". A row that's been deleted falls back to
                // `#<id>` (set during hydration in the handler).
                let other: Vec<(String, String)> = active_filter_pairs
                    .iter()
                    .filter(|(field, _)| field != &g.field)
                    .cloned()
                    .collect();
                return Some(ActiveFilterPillCtx {
                    label: g.label.clone(),
                    value_label: if g.fk_selected_label.is_empty() {
                        format!("#{}", g.fk_selected_id)
                    } else {
                        g.fk_selected_label.clone()
                    },
                    remove_link: build_list_url(
                        entry.admin_name,
                        &search_query,
                        &other,
                        active_sort_ref,
                        1,
                        per_page_override,
                    ),
                });
            }
            if g.kind == "multi_select" {
                if g.multi_selected.is_empty() {
                    return None;
                }
                // One combined pill listing every checked value. The
                // remove link drops every pair under this field name
                // — search query, sort, every other filter survives.
                let value_label = g.multi_selected.join(", ");
                let other: Vec<(String, String)> = active_filter_pairs
                    .iter()
                    .filter(|(field, _)| field != &g.field)
                    .cloned()
                    .collect();
                return Some(ActiveFilterPillCtx {
                    label: g.label.clone(),
                    value_label,
                    remove_link: build_list_url(
                        entry.admin_name,
                        &search_query,
                        &other,
                        active_sort_ref,
                        1,
                        per_page_override,
                    ),
                });
            }
            if g.kind == "date_range" {
                if !g.has_active_range {
                    return None;
                }
                // One combined pill — "from → to", "from only", or
                // "≤ to". The remove link drops both bounds at once.
                let value_label = match (g.date_from_value.as_str(), g.date_to_value.as_str()) {
                    ("", "") => return None,
                    ("", to) => format!("{to}"),
                    (from, "") => format!("{from}"),
                    (from, to) => format!("{from}{to}"),
                };
                let other: Vec<(String, String)> = active_filter_pairs
                    .iter()
                    .filter(|(field, _)| field != &g.date_from_name && field != &g.date_to_name)
                    .cloned()
                    .collect();
                Some(ActiveFilterPillCtx {
                    label: g.label.clone(),
                    value_label,
                    remove_link: build_list_url(
                        entry.admin_name,
                        &search_query,
                        &other,
                        active_sort_ref,
                        1,
                        per_page_override,
                    ),
                })
            } else {
                let v = g.current.as_ref()?;
                let value_label = g
                    .options
                    .iter()
                    .find(|o| &o.value == v)
                    .map(|o| o.label.clone())
                    .unwrap_or_else(|| v.clone());
                let other: Vec<(String, String)> = active_filter_pairs
                    .iter()
                    .filter(|(field, _)| field != &g.field)
                    .cloned()
                    .collect();
                Some(ActiveFilterPillCtx {
                    label: g.label.clone(),
                    value_label,
                    remove_link: build_list_url(
                        entry.admin_name,
                        &search_query,
                        &other,
                        active_sort_ref,
                        1,
                        per_page_override,
                    ),
                })
            }
        })
        .collect();

    // Honour `ModelAdmin::list_display()`: when non-empty, render only
    // those columns (in the declared order). Empty falls back to every
    // model field. This is the contract documented on
    // `AdminEntry::list_display`; previously the renderer iterated
    // over `entry.fields` unconditionally and showed every column,
    // including bulky `body` / `description` fields the model author
    // had explicitly excluded.
    let visible_fields: Vec<&AdminField> = if entry.list_display.is_empty() {
        entry.fields.iter().collect()
    } else {
        entry
            .list_display
            .iter()
            .filter_map(|name| entry.fields.iter().find(|f| f.name == *name))
            .collect()
    };
    let fields: Vec<ListField> = visible_fields
        .iter()
        .map(|f| {
            let (sort_active, sort_link) = build_sort_link(
                f.name,
                &active_sort,
                entry.admin_name,
                &search_query,
                &active_filter_pairs,
                per_page_override,
            );
            ListField {
                name: f.name.to_string(),
                label: f.label.to_string(),
                kind: f.field_type.widget(),
                sort_active,
                sort_link,
            }
        })
        .collect();

    // Build the toolbar's Sort dropdown options. Each visible field
    // contributes two entries (asc + desc); a leading "Default order"
    // entry resets to `ModelAdmin::ordering()`. Every link goes
    // through `build_list_url` so search + filters survive a sort
    // change.
    use super::modeladmin::SortDir;
    let mut sort_options: Vec<SortOptionCtx> = Vec::with_capacity(visible_fields.len() * 2 + 1);
    sort_options.push(SortOptionCtx {
        label: "Default order".to_string(),
        link: build_list_url(
            entry.admin_name,
            &search_query,
            &active_filter_pairs,
            None,
            1,
            per_page_override,
        ),
        is_active: active_sort.is_none(),
    });
    for f in &visible_fields {
        for dir in [SortDir::Asc, SortDir::Desc] {
            let dir_label = sort_direction_label(f.field_type, dir);
            let is_active = matches!(
                &active_sort,
                Some((col, d)) if col == f.name && *d == dir
            );
            sort_options.push(SortOptionCtx {
                label: format!("{} ({})", f.label, dir_label),
                link: build_list_url(
                    entry.admin_name,
                    &search_query,
                    &active_filter_pairs,
                    Some((f.name, dir)),
                    1,
                    per_page_override,
                ),
                is_active,
            });
        }
    }
    let current_sort_label = sort_options
        .iter()
        .find(|o| o.is_active)
        .map(|o| o.label.clone())
        .unwrap_or_else(|| "Default order".to_string());

    // Redesigned Sort menu — one entry per sortable field. The legacy
    // `sort_options` vec stays populated above for project templates
    // that haven't migrated; the framework's own list template now
    // renders the field menu plus a direction toggle, which the
    // template builds against `sort_fields` + `sort_dir_toggle_link`.
    let sort_fields: Vec<SortFieldCtx> = visible_fields
        .iter()
        .map(|f| {
            let asc_link = build_list_url(
                entry.admin_name,
                &search_query,
                &active_filter_pairs,
                Some((f.name, SortDir::Asc)),
                1,
                per_page_override,
            );
            let desc_link = build_list_url(
                entry.admin_name,
                &search_query,
                &active_filter_pairs,
                Some((f.name, SortDir::Desc)),
                1,
                per_page_override,
            );
            let is_active = matches!(
                &active_sort,
                Some((col, _)) if col == f.name
            );
            SortFieldCtx {
                field: f.name.to_string(),
                label: f.label.to_string(),
                asc_link,
                desc_link,
                asc_label: sort_direction_label(f.field_type, SortDir::Asc),
                desc_label: sort_direction_label(f.field_type, SortDir::Desc),
                is_active,
            }
        })
        .collect();

    // `default_sort_link` mirrors `sort_options[0].link` (the
    // "Default order" reset). Surfacing it as a standalone field
    // lets the new template emit the link without indexing into
    // the legacy vec, which keeps the two layouts independently
    // editable.
    let default_sort_link = build_list_url(
        entry.admin_name,
        &search_query,
        &active_filter_pairs,
        None,
        1,
        per_page_override,
    );

    // Direction-toggle pair: the active field's label drives the
    // toolbar Sort chip's caption; the active field's *opposite*
    // direction URL drives the toggle button. When no sort is
    // active, both stay empty and the template hides the toggle.
    let (current_sort_field_label, current_sort_dir_label, sort_dir_toggle_link) =
        match &active_sort {
            Some((col, dir)) => {
                let field = sort_fields.iter().find(|sf| sf.field == *col);
                let label = field
                    .map(|f| f.label.clone())
                    .unwrap_or_else(|| col.clone());
                let (dir_label, toggle_link) = match (field, dir) {
                    (Some(f), SortDir::Asc) => (f.desc_label, f.desc_link.clone()),
                    (Some(f), SortDir::Desc) => (f.asc_label, f.asc_link.clone()),
                    // `active_sort` references a column not in
                    // `visible_fields` (rare: column dropped from
                    // `list_display` between requests). Fall back
                    // to generic labels + an empty toggle URL so
                    // the template renders without crashing.
                    (None, _) => ("", String::new()),
                };
                (label, dir_label, toggle_link)
            }
            None => ("Default order".to_string(), "", String::new()),
        };

    let prev_page_link = (page > 1).then(|| {
        build_list_url(
            entry.admin_name,
            &search_query,
            &active_filter_pairs,
            active_sort_ref,
            page - 1,
            per_page_override,
        )
    });
    let next_page_link = (page < total_pages).then(|| {
        build_list_url(
            entry.admin_name,
            &search_query,
            &active_filter_pairs,
            active_sort_ref,
            page + 1,
            per_page_override,
        )
    });

    let page_items = build_page_items(page, total_pages, |n| {
        build_list_url(
            entry.admin_name,
            &search_query,
            &active_filter_pairs,
            active_sort_ref,
            n,
            per_page_override,
        )
    });

    let (active_sort_field, active_sort_dir) = match &active_sort {
        Some((col, SortDir::Asc)) => (Some(col.clone()), Some("asc")),
        Some((col, SortDir::Desc)) => (Some(col.clone()), Some("desc")),
        None => (None, None),
    };

    // Per-page allow-list mirrors the handler's set; values outside it
    // are silently dropped server-side. Each option's link uses
    // `Some(value)` for non-default densities so the override carries
    // through, and `None` for the model default so the URL stays clean.
    let per_page_choices: [usize; 4] = [25, 50, 100, 200];
    let model_default_per_page = entry.list_per_page;
    let per_page_options: Vec<PerPageOptionCtx> = per_page_choices
        .iter()
        .map(|&n| {
            let override_for_link = (n != model_default_per_page).then_some(n);
            PerPageOptionCtx {
                value: n,
                label: format!("{n} / page"),
                link: build_list_url(
                    entry.admin_name,
                    &search_query,
                    &active_filter_pairs,
                    active_sort_ref,
                    1,
                    override_for_link,
                ),
                is_active: per_page == n,
            }
        })
        .collect();
    let current_per_page_label = format!("{per_page} / page");
    let field_names: Vec<&'static str> = entry.fields.iter().map(|f| f.name).collect();
    let field_types: Vec<crate::admin::FieldType> =
        entry.fields.iter().map(|f| f.field_type).collect();
    // Pre-compute the lowercase search term once. Each row × column
    // would otherwise redo the allocation; for a 100-row × 5-searched-
    // column page that's 500 redundant lowercases.
    let search_term_trimmed = search_query.trim();
    let search_term_for_highlight: Option<String> = if search_term_trimmed.is_empty() {
        None
    } else {
        Some(search_term_trimmed.to_string())
    };
    // Columns whose cells the highlighter should scan — only those
    // the SQL search clause actually ILIKE'd. Highlighting a column
    // that wasn't searched would be a lie.
    let searched_columns: std::collections::HashSet<&str> =
        entry.search_fields.iter().copied().collect();
    ListCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: entry.display_name.to_string(),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        display_name: entry.display_name,
        singular_name: entry.singular_name,
        fields,
        rows: rows
            .into_iter()
            .map(|r| {
                let mut values: HashMap<String, serde_json::Value> =
                    HashMap::with_capacity(field_names.len().saturating_sub(1));
                let mut links: HashMap<String, String> = HashMap::new();
                let mut highlights: HashMap<String, String> = HashMap::new();
                let cell_links = r.cell_links;
                for (i, cell) in r.cells.into_iter().enumerate() {
                    if let Some(name) = field_names.get(i) {
                        // Skip the "id" key so the explicit struct field
                        // wins on serialization.
                        if *name == "id" {
                            continue;
                        }
                        // Build the highlight HTML BEFORE moving `cell`
                        // into the typed value below. Only emit a
                        // fragment when the column was actually scanned
                        // by the search clause AND at least one match
                        // landed; otherwise the template falls back to
                        // the plain string path.
                        if let Some(term) = &search_term_for_highlight {
                            let is_bool =
                                matches!(field_types.get(i), Some(crate::admin::FieldType::Bool));
                            if !is_bool && searched_columns.contains(*name) {
                                if let Some(html) = highlight_search_match(&cell, term) {
                                    highlights.insert((*name).to_string(), html);
                                }
                            }
                        }
                        let typed = match field_types.get(i) {
                            Some(crate::admin::FieldType::Bool) => {
                                serde_json::Value::Bool(cell == "true")
                            }
                            _ => serde_json::Value::String(cell),
                        };
                        values.insert((*name).to_string(), typed);
                        if let Some(Some(link)) = cell_links.get(i) {
                            links.insert(
                                (*name).to_string(),
                                format!("/admin/{}/{}/edit", link.admin_name, link.id),
                            );
                        }
                    }
                }
                ListRowCtx {
                    id: r.id,
                    values,
                    links,
                    highlights,
                }
            })
            .collect(),
        search_query,
        active_filter_count: filters
            .iter()
            .filter(|g| g.current.is_some() || g.has_active_range || !g.multi_selected.is_empty())
            .count(),
        active_filter_pairs,
        active_filter_pills,
        clear_all_filters_link,
        csv_export_url,
        filters,
        sort_options,
        current_sort_label,
        sort_fields,
        current_sort_field_label,
        current_sort_dir_label,
        sort_dir_toggle_link,
        default_sort_link,
        active_sort_field,
        active_sort_dir,
        per_page_options,
        current_per_page_label,
        active_per_page_override: per_page_override,
        page,
        total_pages,
        per_page,
        total_rows,
        prev_page_link,
        next_page_link,
        page_items,
        bulk_actions_enabled: false,
        bulk_action_buttons: entry
            .bulk_actions
            .iter()
            .map(|a| BulkActionBtnCtx {
                name: a.name,
                label: a.label,
                destructive: a.destructive,
                form_action: format!("/admin/{}/bulk/{}", entry.admin_name, a.name),
            })
            .collect(),
        saved_filters: saved_filters
            .into_iter()
            .map(|sf| {
                let apply_url = if sf.query_string.is_empty() {
                    format!("/admin/{}", entry.admin_name)
                } else {
                    format!("/admin/{}?{}", entry.admin_name, sf.query_string)
                };
                let is_current = sf.query_string == current_query_string;
                SavedFilterBtnCtx {
                    delete_url: format!(
                        "/admin/{}/saved_filters/{}/delete",
                        entry.admin_name, sf.id
                    ),
                    apply_url,
                    name: sf.name,
                    is_current,
                    id: sf.id,
                }
            })
            .collect(),
        current_query_string,
        flash: None,
    }
}

/// Pre-bake the sortable-header URL + active-direction marker for one
/// column. Three states:
///   - column is the current sort, ascending  → click toggles to desc
///   - column is the current sort, descending → click clears the sort
///   - column is not the current sort         → click sets ascending
///
/// The URL goes through `build_list_url` so search query and active
/// filters are preserved across header clicks. Page resets to 1
/// because page N of one ordering rarely lines up with page N of
/// another.
fn build_sort_link(
    name: &'static str,
    active: &Option<(String, super::modeladmin::SortDir)>,
    admin_name: &str,
    q: &str,
    filters: &[(String, String)],
    per_page: Option<usize>,
) -> (&'static str, String) {
    use super::modeladmin::SortDir;
    let (marker, new_sort) = match active {
        Some((col, SortDir::Asc)) if col == name => ("asc", Some((name, SortDir::Desc))),
        Some((col, SortDir::Desc)) if col == name => ("desc", None),
        _ => ("", Some((name, SortDir::Asc))),
    };
    (
        marker,
        build_list_url(admin_name, q, filters, new_sort, 1, per_page),
    )
}

// ---- Change form ----------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct FormCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    pub mode: &'static str, // "new" or "edit"
    pub object_id: Option<i64>,
    pub sections: Vec<FormSection>,
    pub errors: Vec<String>,
    /// Related-children sections rendered below the action bar
    /// when `mode == "edit"`. Always empty on `"new"` (no parent
    /// id yet to filter children on). Each entry is one
    /// declared [`super::modeladmin::Inline`] resolved to a
    /// concrete row list.
    pub inlines: Vec<FormInlineCtx>,
    /// `true` when at least one field on the form is a
    /// `<input type="file">`. Drives
    /// `enctype="multipart/form-data"` on the form open tag;
    /// non-file forms keep the default urlencoded encoding so
    /// the existing fast path on `Request::form()` stays in
    /// effect.
    pub has_file_field: bool,
    pub flash: Option<FlashCtx>,
}

/// One resolved [`super::modeladmin::Inline`] — a child-model
/// section under the parent's edit form. Read-only in v1: a table
/// of click-through rows plus an "Add new" affordance that lands
/// the operator on the child's normal new-form.
#[derive(Serialize)]
pub(crate) struct FormInlineCtx {
    pub label: String,
    /// Pluralised display name of the child for empty-state copy.
    pub target_display_name: String,
    /// Child's admin slug. Drives the "Add new …" and "View all"
    /// click-through URLs.
    pub target_admin_name: String,
    pub rows: Vec<FormInlineRowCtx>,
    /// `true` when the child query was capped at `max_rows` —
    /// drives the "…and N more" link to the child's list page
    /// pre-filtered to this parent.
    pub has_more: bool,
    /// Total matching rows on the child table. Renders as
    /// "Showing X of Y" when `has_more` is `true`.
    pub total: i64,
    /// `/admin/<child>/new` — link target for "Add new …". v1
    /// doesn't prefill the parent FK; the operator picks it from
    /// the child's normal relation widget.
    pub add_url: String,
    /// `/admin/<child>?<fk_field>=<parent_id>` — link target for
    /// "View all …" so the operator can paginate / search beyond
    /// the inline cap.
    pub list_url: String,
}

#[derive(Serialize)]
pub(crate) struct FormInlineRowCtx {
    pub id: i64,
    pub label: String,
    pub edit_url: String,
    pub delete_url: String,
}

/// One option in a `<select>` list. Both fields are `String` because
/// options come from runtime data: enum choices, FK rows, M2M
/// memberships.
#[derive(Serialize, Clone)]
pub(crate) struct SelectOption {
    pub value: String,
    pub label: String,
}

#[derive(Serialize)]
pub(crate) struct FormField {
    pub name: &'static str,
    pub label: String,
    pub widget: &'static str,
    pub input_type: &'static str,
    pub value: String,
    pub hint: Option<String>,
    pub placeholder: Option<String>,
    pub required: bool,
    pub options: Option<Vec<SelectOption>>,
    pub multiple: bool,
    /// Grid-span hint. `1` (default) renders the field at half-width
    /// inside the section's `grid-cols-2`; `2` makes the field span
    /// both columns. Set to `2` for textareas, `1` everywhere else.
    pub span: u8,
    pub autocomplete: Option<&'static str>,
    pub autofocus: bool,
    pub disabled: bool,
    pub maxlength: Option<u16>,
    pub searchable: bool,
    pub has_more: bool,
    pub search_url: Option<String>,
    pub errors: Vec<String>,
    pub target_model: Option<String>,
    /// Computed checked-state for boolean fields, normalised once at
    /// FormField construction time using the same rules as
    /// `FormData::bool_flag` (`on` / `true` / `1` / `yes`).
    pub checked: bool,
}

/// One logical group of fields on a form. `title: None` renders
/// without an `<h3>` (used for the default "core fields" section).
#[derive(Serialize)]
pub(crate) struct FormSection {
    pub title: Option<&'static str>,
    pub fields: Vec<FormField>,
}

/// Snake-case → Title Case ("priority" → "Priority", "is_active" → "Is active").
///
/// Mirrors `rustio_admin_macros::humanise_field` byte-for-byte. The
/// macro emits validation messages prefixed with this transformed
/// label (`"Title is required."`); `bucket_errors_by_label` reverses
/// the mapping at runtime to route flat errors to their owning field.
///
/// Whole-word acronym recognition: each underscore-separated segment
/// is checked against [`HUMANISE_ACRONYMS`] before being
/// title-cased, so `id` → `ID`, `email_id` → `Email ID`,
/// `mfa_secret_key_id` → `MFA Secret Key ID`. Words *containing* but
/// not *being* an acronym (`video` is not `vIDeo`) are left to the
/// default first-letter-uppercase rule.
fn humanise_field(s: &str) -> String {
    if s.is_empty() {
        return String::new();
    }
    let mut out = String::with_capacity(s.len());
    let mut first_segment = true;
    for segment in s.split('_') {
        if !first_segment {
            out.push(' ');
        }
        first_segment = false;
        let lower = segment.to_ascii_lowercase();
        if HUMANISE_ACRONYMS.contains(&lower.as_str()) {
            // Whole-word acronym — emit as uppercase regardless
            // of the source case (`Id`, `ID`, and `id` all
            // become `ID`).
            out.push_str(&lower.to_ascii_uppercase());
        } else {
            let mut chars = segment.chars();
            if let Some(first) = chars.next() {
                out.push(first.to_ascii_uppercase());
                for c in chars {
                    out.push(c);
                }
            }
        }
    }
    out
}

/// Acronyms that should be fully uppercase in humanised labels.
///
/// Kept tight and audit-able rather than open-ended: every entry
/// is one a Postgres admin framework realistically meets in column
/// names. Adding to this list also requires updating the byte-for-
/// byte mirror in `rustio_admin_macros::HUMANISE_ACRONYMS` — the
/// macros crate cannot depend on this crate (proc-macro cycle), so
/// the two lists are intentionally duplicated.
pub(crate) const HUMANISE_ACRONYMS: &[&str] = &[
    "id", "ip", "url", "uri", "api", "uuid", "mfa", "csv", "sql", "html", "http", "https", "json",
    "tls", "ssl", "smtp", "xml",
];

/// Split a flat `Vec<String>` from `AdminOps::create / update` into a
/// global vec + a per-field map by prefix-matching against each
/// editable field's humanised label.
///
/// **Brittle by design.** Depends on `rustio-admin-macros` emitting
/// messages of the form `"<HumanisedLabel> ..."`. If the macro ever
/// changes that wording, unmatched errors fall through to the global
/// vec — the banner still shows them; only the inline / aria
/// attribution is lost.
pub(crate) fn bucket_errors_by_label(
    entry: &AdminEntry,
    errors: Vec<String>,
) -> (Vec<String>, HashMap<String, Vec<String>>) {
    // Pre-compute "<Label> " once per editable field. The trailing
    // space disambiguates `Title ` from `Title bar `.
    let labels: Vec<(&'static str, String)> = entry
        .fields
        .iter()
        .filter(|f| f.editable)
        .map(|f| (f.name, format!("{} ", humanise_field(f.name))))
        .collect();

    let mut global: Vec<String> = Vec::new();
    let mut per_field: HashMap<String, Vec<String>> = HashMap::new();
    'outer: for err in errors {
        for (name, prefix) in &labels {
            if err.starts_with(prefix.as_str()) {
                per_field.entry((*name).to_string()).or_default().push(err);
                continue 'outer;
            }
        }
        global.push(err);
    }
    (global, per_field)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn form_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    mode: &'static str,
    object_id: Option<i64>,
    existing: Option<&EditRow>,
    errors: Vec<String>,
    csrf_token: String,
    relation_options: HashMap<&'static str, (Vec<SelectOption>, bool)>,
    field_errors: HashMap<String, Vec<String>>,
    submitted: Option<&FormData>,
    inlines: Vec<FormInlineCtx>,
) -> FormCtx {
    let fields = entry
        .fields
        .iter()
        .filter(|f| f.editable)
        .map(|f| {
            // `ModelAdmin::readonly_fields()` flagged this column. The
            // browser-side `disabled` attribute prevents submission, so
            // the value always reflects the existing row (never the
            // re-rendered submitted form). On `new` there is no row
            // yet, so readonly has no effect until the row is saved.
            let readonly = mode == "edit" && entry.readonly_fields.contains(&f.name);
            let value = if let Some(form) = submitted.filter(|_| !readonly) {
                form.get(f.name).map(str::to_string).unwrap_or_default()
            } else {
                existing
                    .and_then(|row| {
                        row.values
                            .iter()
                            .find(|(col, _)| col == f.name)
                            .map(|(_, v)| v.clone())
                    })
                    .unwrap_or_default()
            };
            let ui = super::filters::field_ui_metadata(f);
            let (base_widget, input_type) = map_field_to_ui(f);
            // String fields with content-y names (body / description /
            // notes / content / summary) render as <textarea> instead
            // of single-line <input>. The base widget mapping doesn't
            // see field names, so the override stays here.
            let widget = if base_widget == "input"
                && matches!(
                    f.field_type,
                    super::types::FieldType::String | super::types::FieldType::OptionalString
                )
                && is_long_text_name(f.name)
            {
                "textarea"
            } else {
                base_widget
            };
            // Bools always submit (checked = true, absent = false), so
            // they never carry a required-asterisk; every other
            // non-nullable field does. Readonly drops the asterisk too
            // — the user can't satisfy it from this form.
            let required = !readonly
                && !f.field_type.nullable()
                && !matches!(f.field_type, super::types::FieldType::Bool);
            let (options, multiple, searchable, has_more) = if let Some(values) = f.choices {
                let mut opts: Vec<SelectOption> = Vec::with_capacity(values.len() + 1);
                if f.field_type.nullable() {
                    opts.push(SelectOption {
                        value: String::new(),
                        label: "".to_string(),
                    });
                }
                opts.extend(values.iter().map(|v| SelectOption {
                    value: (*v).to_string(),
                    label: (*v).to_string(),
                }));
                (Some(opts), false, false, false)
            } else if let Some(rel) = &f.relation {
                let (opts, has_more) = relation_options.get(f.name).cloned().unwrap_or_default();
                (Some(opts), rel.multi, true, has_more)
            } else {
                (None, false, false, false)
            };
            let span: u8 = if widget == "textarea" { 2 } else { 1 };
            let search_url = f
                .relation
                .as_ref()
                .map(|rel| format!("/admin/search/{}", rel.target_model));
            let target_model = f.relation.as_ref().map(|rel| rel.target_model.to_string());
            let checked = matches!(value.as_str(), "on" | "true" | "1" | "yes");
            let placeholder = if let Some(rel) = &f.relation {
                Some(format!("Select {}", rel.target_model))
            } else {
                ui.placeholder
            };
            FormField {
                name: f.name,
                label: ui.label,
                widget,
                input_type,
                value,
                hint: ui.hint,
                placeholder,
                required,
                options,
                multiple,
                span,
                autocomplete: None,
                autofocus: false,
                disabled: readonly,
                maxlength: None,
                searchable,
                has_more,
                search_url,
                errors: field_errors.get(f.name).cloned().unwrap_or_default(),
                target_model,
                checked,
            }
        })
        .collect::<Vec<FormField>>();

    let sections = if entry.fieldsets.is_empty() {
        group_fields_into_sections(fields)
    } else {
        group_fields_by_fieldsets(fields, entry.fieldsets)
    };

    FormCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: match mode {
            "new" => format!("Add {}", entry.singular_name),
            _ => format!("Change {}", entry.singular_name),
        },
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        display_name: entry.display_name,
        singular_name: entry.singular_name,
        mode,
        object_id,
        sections,
        errors,
        inlines,
        has_file_field: entry.fields.iter().any(|f| {
            matches!(
                f.field_type,
                crate::admin::FieldType::FilePath | crate::admin::FieldType::OptionalFilePath
            )
        }),
        flash: None,
    }
}

/// Apply a per-field error map to an existing `Vec<FormSection>` in
/// place. Used by bespoke validators that already know which field a
/// given error belongs to.
pub(crate) fn apply_field_errors(
    sections: &mut [FormSection],
    field_errors: &HashMap<String, Vec<String>>,
) {
    for section in sections.iter_mut() {
        for field in section.fields.iter_mut() {
            if let Some(errs) = field_errors.get(field.name) {
                field.errors = errs.clone();
            }
        }
    }
}

/// Group the rendered fields according to the project-supplied
/// [`super::modeladmin::Fieldset`] slice. Each fieldset becomes a
/// [`FormSection`] with the declared title; fields are emitted in
/// the order the project listed them inside each fieldset. Names
/// the project misspelt (no matching `FormField`) are silently
/// skipped — they would otherwise force a runtime panic on
/// production traffic, and the missing field is visible to the
/// project by absence in the rendered form. Fields that the
/// project owns (in `entry.fields`) but did not list in any
/// fieldset are appended to a trailing untitled "Other" section so
/// the form is never silently incomplete; the project promotes them
/// into a real fieldset to take ownership of their placement.
fn group_fields_by_fieldsets(
    mut fields: Vec<FormField>,
    fieldsets: &'static [super::modeladmin::Fieldset],
) -> Vec<FormSection> {
    let mut sections: Vec<FormSection> = Vec::with_capacity(fieldsets.len() + 1);
    for fs in fieldsets {
        let mut grouped = Vec::with_capacity(fs.fields.len());
        for &name in fs.fields {
            if let Some(pos) = fields.iter().position(|f| f.name == name) {
                grouped.push(fields.remove(pos));
            }
        }
        if !grouped.is_empty() {
            sections.push(FormSection {
                title: Some(fs.title),
                fields: grouped,
            });
        }
    }
    if !fields.is_empty() {
        sections.push(FormSection {
            title: Some("Other"),
            fields,
        });
    }
    sections
}

/// Partition the form's flat field list into Default / System /
/// Advanced sections by name heuristic. Empty sections are dropped.
fn group_fields_into_sections(fields: Vec<FormField>) -> Vec<FormSection> {
    let mut default_fields = Vec::new();
    let mut metadata_fields = Vec::new();
    let mut advanced_fields = Vec::new();

    for field in fields {
        match classify_field_section(field.name) {
            FieldSection::Default => default_fields.push(field),
            FieldSection::Metadata => metadata_fields.push(field),
            FieldSection::Advanced => advanced_fields.push(field),
        }
    }

    let mut sections: Vec<FormSection> = Vec::with_capacity(3);
    if !default_fields.is_empty() {
        sections.push(FormSection {
            title: None,
            fields: default_fields,
        });
    }
    if !metadata_fields.is_empty() {
        sections.push(FormSection {
            title: Some("System"),
            fields: metadata_fields,
        });
    }
    if !advanced_fields.is_empty() {
        sections.push(FormSection {
            title: Some("Advanced"),
            fields: advanced_fields,
        });
    }
    sections
}

enum FieldSection {
    Default,
    Metadata,
    Advanced,
}

fn classify_field_section(name: &str) -> FieldSection {
    if name.contains("created") || name.contains("updated") || name.contains("timestamp") {
        FieldSection::Metadata
    } else if matches!(name, "id" | "uuid" | "slug") {
        FieldSection::Advanced
    } else {
        FieldSection::Default
    }
}

/// Names that imply multi-line content. Used by `form_ctx` to upgrade
/// a `String` / `OptionalString` field to a `<textarea>`.
fn is_long_text_name(name: &str) -> bool {
    matches!(
        name,
        "body" | "description" | "notes" | "content" | "summary" | "bio" | "details"
    )
}

/// Backend-driven field-to-UI mapping. Resolution priority (top-down):
///   1. `field.choices.is_some()` → enum-style `<select>`.
///   2. `field.relation.is_some()` && `relation.multi` → `<select multiple>`.
///   3. `field.relation.is_some()` (belongs-to) → single `<select>`.
///   4. Fall through to the `field.field_type` mapping.
fn map_field_to_ui(field: &super::types::AdminField) -> (&'static str, &'static str) {
    if field.choices.is_some() {
        return ("select", "select");
    }
    if let Some(rel) = &field.relation {
        if rel.multi {
            return ("select", "select-multiple");
        }
        return ("select", "select");
    }
    use super::types::FieldType::*;
    match field.field_type {
        Bool => ("checkbox", "checkbox"),
        I32 | I64 | OptionalI64 => ("input", "number"),
        DateTime | OptionalDateTime => ("input", "datetime-local"),
        FilePath | OptionalFilePath => ("file", "file"),
        String | OptionalString => ("input", "text"),
    }
}

/// Initial-render row cap for FK / M2M selects.
pub(crate) const FK_OPTIONS_LIMIT: usize = 50;

/// Fetch real `<select>` options for every FK / M2M field on an
/// `AdminEntry`, keyed by the field's name.
///
/// Return value is `(Vec<SelectOption>, bool)` per key. The bool is
/// `has_more`: `true` when the relation had more rows than
/// `FK_OPTIONS_LIMIT` and the option list was truncated. Empty target
/// lists, missing target models, and non-relation fields all produce
/// a benign empty entry — never a panic.
///
/// The label for each option follows the resolution ladder:
///   1. `relation.display_field` if present and the column exists.
///   2. `"name"` column if present.
///   3. `"title"` column if present.
///   4. Stringified id.
pub(crate) async fn resolve_relation_options(
    admin: &Admin,
    entry: &AdminEntry,
    db: &Db,
) -> Result<HashMap<&'static str, (Vec<SelectOption>, bool)>> {
    let mut out: HashMap<&'static str, (Vec<SelectOption>, bool)> = HashMap::new();
    for f in entry.fields.iter() {
        let Some(rel) = &f.relation else {
            continue;
        };
        let target = admin.entries().iter().find(|e| {
            e.singular_name == rel.target_model
                || e.admin_name == rel.target_model
                || e.display_name == rel.target_model
        });
        let Some(target) = target else {
            out.insert(f.name, (Vec::new(), false));
            continue;
        };
        // Cap to FK_OPTIONS_LIMIT in SQL; the total count tells us
        // whether to set `has_more` for the form's "showing first N"
        // hint. Pre-P10 this called `list()` and slung every row over
        // the wire before truncating client-side.
        let page = target
            .ops
            .list(
                db,
                super::types::ListOpts {
                    limit: Some(FK_OPTIONS_LIMIT as i64),
                    ..super::types::ListOpts::default()
                },
            )
            .await?;
        let display_idx = pick_display_index(target.fields, rel.display_field);
        let opts: Vec<SelectOption> = page
            .rows
            .into_iter()
            .map(|r| {
                let label = display_idx
                    .and_then(|i| r.cells.get(i).cloned())
                    .filter(|s| !s.is_empty())
                    .unwrap_or_else(|| r.id.to_string());
                SelectOption {
                    value: r.id.to_string(),
                    label,
                }
            })
            .collect();
        let has_more = page.total > FK_OPTIONS_LIMIT as i64;
        out.insert(f.name, (opts, has_more));
    }
    Ok(out)
}

pub(crate) fn pick_display_index(
    fields: &[AdminField],
    display_field: Option<&str>,
) -> Option<usize> {
    if let Some(preferred) = display_field {
        if let Some(i) = fields.iter().position(|f| f.name == preferred) {
            return Some(i);
        }
    }
    // Fallback ladder — checked in order, first match wins. `name` and
    // `title` cover Library / Catalogue / Article / Movie shapes;
    // `full_name` covers Person / Customer / Patient / Employee
    // shapes (the universal Patron / User column across both shipped
    // examples); `email` is the last resort for user-like rows that
    // skipped full_name. A row whose schema fits none of these
    // patterns still renders as `#<id>` from the caller's fallback.
    for fallback in ["name", "title", "full_name", "email"] {
        if let Some(i) = fields.iter().position(|f| f.name == fallback) {
            return Some(i);
        }
    }
    None
}

// ---- Confirm-delete -------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct ConfirmDeleteCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    pub object_id: i64,
    pub object_label: String,
    /// Models that point at this one via a `BelongsTo` FK.
    pub cascading: Vec<CascadeItem>,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct CascadeItem {
    pub source_display_name: String,
    pub source_admin_name: String,
    pub source_field: String,
}

pub(crate) fn confirm_delete_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    object_id: i64,
    object_label: String,
    cascading: Vec<CascadeItem>,
    csrf_token: String,
) -> ConfirmDeleteCtx {
    ConfirmDeleteCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: format!("Delete {}", entry.singular_name),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        display_name: entry.display_name,
        singular_name: entry.singular_name,
        object_id,
        object_label,
        cascading,
        flash: None,
    }
}

// ---- Bulk-delete confirmation -------------------------------------------

#[derive(Serialize)]
pub(crate) struct BulkConfirmDeleteCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    /// `(id, label)` for each row the user selected, in selection
    /// order. Rendered as a list on the confirm page so the user
    /// sees exactly what will be deleted.
    pub items: Vec<BulkDeleteItem>,
    /// Comma-separated IDs replayed into the confirm form's hidden
    /// `_ids` field — same wire format the checkbox form posts.
    pub ids_csv: String,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct BulkDeleteItem {
    pub id: i64,
    pub label: String,
}

// ---- Bulk action confirmation (project-defined) -------------------------

#[derive(Serialize)]
pub(crate) struct BulkConfirmActionCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    /// The action's URL slug (e.g. `"publish"`) — replayed back into
    /// the confirm form's `formaction` URL.
    pub action_name: &'static str,
    pub action_label: &'static str,
    pub action_destructive: bool,
    pub items: Vec<BulkDeleteItem>,
    pub ids_csv: String,
    pub flash: Option<FlashCtx>,
}

pub(crate) fn bulk_confirm_action_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    action: super::modeladmin::BulkAction,
    items: Vec<BulkDeleteItem>,
    csrf_token: String,
) -> BulkConfirmActionCtx {
    let ids_csv = items
        .iter()
        .map(|i| i.id.to_string())
        .collect::<Vec<_>>()
        .join(",");
    BulkConfirmActionCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: format!("{}{} {}", action.label, items.len(), entry.display_name),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        display_name: entry.display_name,
        singular_name: entry.singular_name,
        action_name: action.name,
        action_label: action.label,
        action_destructive: action.destructive,
        items,
        ids_csv,
        flash: None,
    }
}

pub(crate) fn bulk_confirm_delete_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    items: Vec<BulkDeleteItem>,
    csrf_token: String,
) -> BulkConfirmDeleteCtx {
    let ids_csv = items
        .iter()
        .map(|i| i.id.to_string())
        .collect::<Vec<_>>()
        .join(",");
    BulkConfirmDeleteCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: format!("Delete {} {}", items.len(), entry.display_name),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        display_name: entry.display_name,
        singular_name: entry.singular_name,
        items,
        ids_csv,
        flash: None,
    }
}

// ---- 403 Forbidden + generic admin error ---------------------------------

#[derive(Serialize)]
pub(crate) struct ForbiddenCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub entries: Vec<SidebarEntry>,
    pub page_title: &'static str,
    /// The permission codename or URL the user tried to reach.
    pub attempted: Option<String>,
    /// The minimum role required by the page that rejected them.
    pub required_role: Option<&'static str>,
}

#[derive(Serialize)]
pub(crate) struct ErrorCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub status: u16,
    pub heading: String,
    pub message: String,
    /// Project-model entries for the sidebar. Required to keep the
    /// chrome navigable on 4xx/5xx pages (`VISIBILITY_AUDIT.md` A2):
    /// previously the error page rendered without a sidebar because
    /// `entries` was absent, so the operator hit a navigational
    /// dead-end the moment they bounced off a 404.
    pub entries: Vec<SidebarEntry>,
}

pub(crate) fn admin_error_heading(status: u16) -> &'static str {
    match status {
        400 => "Bad request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not found",
        405 => "Method not allowed",
        409 => "Conflict",
        500 => "Server error",
        _ => "Error",
    }
}

pub(crate) fn render_admin_error_response(
    admin: &Admin,
    templates: &crate::templates::Templates,
    identity: Option<&Identity>,
    status: u16,
    message: String,
) -> crate::http::Response {
    let heading = admin_error_heading(status).to_string();
    // Sidebar entries for the chrome. `core=true` entries (User /
    // Group) are excluded from the dynamic Models loop the way
    // every other page does it — they live in the hardcoded Auth
    // block of `_sidebar.html`.
    let sidebar_entries: Vec<SidebarEntry> = admin
        .entries()
        .iter()
        .filter(|e| !e.core)
        .map(SidebarEntry::from)
        .collect();
    let view = ErrorCtx {
        base: BaseContext::new(identity, String::new(), admin),
        page_title: format!("{status} {heading}"),
        status,
        heading: heading.clone(),
        message,
        entries: sidebar_entries,
    };
    let html_status =
        hyper::StatusCode::from_u16(status).unwrap_or(hyper::StatusCode::INTERNAL_SERVER_ERROR);
    match templates.render("admin/error.html", &view) {
        Ok(body) => crate::http::Response::html(body).with_status(html_status),
        Err(e) => {
            log::error!("admin/error.html render failed: {e}");
            crate::http::Response::text(format!("{status} {heading}: {}", view.message))
                .with_status(html_status)
        }
    }
}

pub(crate) fn render_forbidden_body(
    admin: &Admin,
    templates: &crate::templates::Templates,
    identity: &Identity,
    csrf_token: String,
    attempted: Option<String>,
    required_role: Option<&'static str>,
) -> crate::error::Result<String> {
    let view = ForbiddenCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        page_title: "Permission denied",
        attempted,
        required_role,
    };
    templates.render("admin/forbidden.html", &view)
}

// ---- History pages -------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct HistoryEntryCtx {
    pub timestamp_iso: String,
    pub when_relative: String,
    /// `YYYY-MM-DD` of the audit timestamp (UTC). Drives the
    /// day-divider rows in the history templates — when this
    /// changes between consecutive entries, `is_new_day` is
    /// `true` and the template emits a divider before the row.
    pub date_iso: String,
    /// `true` when this entry's `date_iso` differs from the
    /// previous entry's (or this is the first entry). Computed by
    /// `map_audit_actions`; template uses it to render a
    /// `YYYY-MM-DD` divider above the row.
    pub is_new_day: bool,
    pub user_id: i64,
    pub user_email: String,
    pub action_type: String,
    pub label: &'static str,
    pub pill_class: &'static str,
    pub model_name: String,
    pub model_admin_name: String,
    pub object_id: i64,
    pub summary: String,
    pub ip_address: String,
    /// Per-field before/after diff extracted from
    /// `audit_action.metadata.changes`. Empty when the row carries
    /// no diff (create / delete / pre-diff-feature updates). The
    /// object-history template iterates this to render a tight
    /// `<dl>` of changed columns under the audit row.
    pub changes: Vec<HistoryChangeCtx>,
}

// ---- /admin/apis HTML index ---------------------------------------------

#[derive(Serialize)]
pub(crate) struct ApisIndexCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    /// Sidebar nav models — same shape every other authenticated
    /// page uses.
    pub entries: Vec<SidebarEntry>,
    /// One row per non-core registered model.
    pub apis: Vec<ApiEntryCtx>,
    pub openapi_url: &'static str,
}

#[derive(Serialize)]
pub(crate) struct ApiEntryCtx {
    pub admin_name: &'static str,
    pub singular_name: &'static str,
    pub display_name: &'static str,
    /// Path documenting the model in OpenAPI shorthand — same
    /// shape the spec lists. Surfaced verbatim in the table.
    pub list_path: String,
    pub detail_path: String,
    pub field_count: usize,
    /// `(field_name, type_label, nullable)` triples for the
    /// compact field table under each model. `type_label` is the
    /// human-readable form ("integer", "string", "date-time",
    /// "boolean", "file path") so the page reads at a glance
    /// without leaking the internal `FieldType` Debug shape.
    pub fields: Vec<ApiFieldCtx>,
}

#[derive(Serialize)]
pub(crate) struct ApiFieldCtx {
    pub name: &'static str,
    pub type_label: &'static str,
    pub nullable: bool,
}

/// Human-friendly type label for one `AdminField`. Pulled out as
/// a small free fn so the API-index renderer and any future
/// schema dumper share one projection.
pub(crate) fn api_field_type_label(field: &AdminField) -> &'static str {
    use crate::admin::types::FieldType::*;
    match field.field_type {
        Bool => "boolean",
        I32 => "integer (i32)",
        I64 | OptionalI64 => "integer (i64)",
        String | OptionalString => "string",
        DateTime | OptionalDateTime => "date-time",
        FilePath | OptionalFilePath => "file path",
    }
}

#[derive(Serialize)]
pub(crate) struct DocsIndexCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub entries: Vec<SidebarEntry>,
    pub docs: Vec<DocSummaryCtx>,
}

#[derive(Serialize)]
pub(crate) struct DocSummaryCtx {
    pub slug: &'static str,
    pub title: &'static str,
}

#[derive(Serialize)]
pub(crate) struct DocPageCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub doc_title: &'static str,
    /// Pre-rendered HTML fragment from `docs::render_markdown`.
    /// The template marks it `|safe` because this is the
    /// trusted boundary — markdown source is framework-owned,
    /// never user-supplied.
    pub body_html: String,
}

pub(crate) fn docs_index_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
) -> DocsIndexCtx {
    DocsIndexCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: "Framework docs",
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        docs: crate::admin::docs::EMBEDDED_DOCS
            .iter()
            .map(|d| DocSummaryCtx {
                slug: d.slug,
                title: d.title,
            })
            .collect(),
    }
}

pub(crate) fn doc_page_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
    doc: &crate::admin::docs::EmbeddedDoc,
) -> DocPageCtx {
    DocPageCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: format!("Docs — {}", doc.title),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        doc_title: doc.title,
        body_html: crate::admin::docs::render_markdown(doc.source),
    }
}

#[derive(Serialize)]
pub(crate) struct CsvImportResultCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: String,
    pub display_name: String,
    pub total: usize,
    pub inserted: usize,
    pub failed: usize,
    pub outcomes: Vec<CsvOutcomeCtx>,
}

#[derive(Serialize)]
pub(crate) struct CsvOutcomeCtx {
    pub row_number: usize,
    pub status: &'static str, // "inserted" | "failed"
    pub id: Option<i64>,
    pub errors: Vec<String>,
}

pub(crate) fn csv_import_result_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
    entry: &AdminEntry,
    report: crate::admin::csv_import::ImportReport,
) -> CsvImportResultCtx {
    use crate::admin::csv_import::RowOutcome;
    let outcomes = report
        .outcomes
        .into_iter()
        .map(|o| match o {
            RowOutcome::Inserted { row_number, id } => CsvOutcomeCtx {
                row_number,
                status: "inserted",
                id: Some(id),
                errors: Vec::new(),
            },
            RowOutcome::Failed { row_number, errors } => CsvOutcomeCtx {
                row_number,
                status: "failed",
                id: None,
                errors,
            },
        })
        .collect();
    CsvImportResultCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: format!("CSV import — {}", entry.display_name),
        admin_name: entry.admin_name.to_string(),
        display_name: entry.display_name.to_string(),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        total: report.total,
        inserted: report.inserted,
        failed: report.failed,
        outcomes,
    }
}

#[derive(Serialize)]
pub(crate) struct NotificationsCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub entries: Vec<SidebarEntry>,
    pub notifications: Vec<NotificationRowCtx>,
    pub unread_count: i64,
}

#[derive(Serialize)]
pub(crate) struct NotificationRowCtx {
    pub id: i64,
    pub message: String,
    pub url: String,
    /// `true` while the notification is unread; controls the
    /// row's visual emphasis in the template.
    pub unread: bool,
    pub when_relative: String,
    pub created_iso: String,
}

pub(crate) fn notifications_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
    notifications: Vec<crate::admin::notifications::Notification>,
) -> NotificationsCtx {
    let unread_count = notifications.iter().filter(|n| n.read_at.is_none()).count() as i64;
    let rows = notifications
        .into_iter()
        .map(|n| NotificationRowCtx {
            id: n.id,
            message: n.message,
            url: n.url,
            unread: n.read_at.is_none(),
            when_relative: relative_time(n.created_at),
            created_iso: n.created_at.to_rfc3339(),
        })
        .collect();
    NotificationsCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: "Notifications",
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        notifications: rows,
        unread_count,
    }
}

#[derive(Serialize)]
pub(crate) struct FeatureFlagsCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub entries: Vec<SidebarEntry>,
    pub flags: Vec<FeatureFlagCtx>,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct FeatureFlagCtx {
    pub key: String,
    pub enabled: bool,
    pub description: String,
    pub created_iso: String,
    pub updated_iso: String,
}

pub(crate) fn feature_flags_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
    flags: Vec<crate::admin::feature_flags::FeatureFlag>,
    flash: Option<FlashCtx>,
) -> FeatureFlagsCtx {
    FeatureFlagsCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: "Feature flags",
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        flags: flags
            .into_iter()
            .map(|f| FeatureFlagCtx {
                key: f.key,
                enabled: f.enabled,
                description: f.description,
                created_iso: f.created_at.to_rfc3339(),
                updated_iso: f.updated_at.to_rfc3339(),
            })
            .collect(),
        flash,
    }
}

#[derive(Serialize)]
pub(crate) struct HealthCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub entries: Vec<SidebarEntry>,
    pub checks: Vec<HealthCheckCtx>,
    /// `true` when every check returned `Ok` — drives the
    /// overall-status banner.
    pub all_ok: bool,
    /// Pre-computed counts for the banner copy.
    pub ok_count: usize,
    pub warn_count: usize,
    pub error_count: usize,
}

#[derive(Serialize)]
pub(crate) struct HealthCheckCtx {
    pub label: &'static str,
    /// `ok` / `warn` / `error` — mirrors `HealthStatus::as_str`.
    pub status: &'static str,
    pub message: String,
}

pub(crate) fn health_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
    checks: Vec<crate::admin::health_dashboard::HealthCheck>,
) -> HealthCtx {
    use crate::admin::health_dashboard::HealthStatus;
    let mut ok_count = 0;
    let mut warn_count = 0;
    let mut error_count = 0;
    for c in &checks {
        match c.status {
            HealthStatus::Ok => ok_count += 1,
            HealthStatus::Warn => warn_count += 1,
            HealthStatus::Error => error_count += 1,
        }
    }
    let all_ok = warn_count == 0 && error_count == 0;
    let ctx_checks: Vec<HealthCheckCtx> = checks
        .into_iter()
        .map(|c| HealthCheckCtx {
            label: c.label,
            status: c.status.as_str(),
            message: c.message,
        })
        .collect();
    HealthCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: "Health",
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        checks: ctx_checks,
        all_ok,
        ok_count,
        warn_count,
        error_count,
    }
}

#[derive(Serialize)]
pub(crate) struct PlaygroundCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub entries: Vec<SidebarEntry>,
    /// Models eligible for the playground — admin_name + a human-
    /// readable label for the dropdown.
    pub models: Vec<PlaygroundModelCtx>,
}

#[derive(Serialize)]
pub(crate) struct PlaygroundModelCtx {
    pub admin_name: &'static str,
    pub display_name: &'static str,
}

pub(crate) fn playground_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
) -> PlaygroundCtx {
    PlaygroundCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: "API playground",
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        models: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(|e| PlaygroundModelCtx {
                admin_name: e.admin_name,
                display_name: e.display_name,
            })
            .collect(),
    }
}

pub(crate) fn apis_index_ctx(
    identity: &Identity,
    admin: &Admin,
    csrf_token: String,
) -> ApisIndexCtx {
    let apis: Vec<ApiEntryCtx> = admin
        .entries()
        .iter()
        .filter(|e| !e.core)
        .map(|e| ApiEntryCtx {
            admin_name: e.admin_name,
            singular_name: e.singular_name,
            display_name: e.display_name,
            list_path: format!("/admin/{}", e.admin_name),
            detail_path: format!("/admin/{}/{{id}}", e.admin_name),
            field_count: e.fields.len(),
            fields: e
                .fields
                .iter()
                .map(|f| ApiFieldCtx {
                    name: f.name,
                    type_label: api_field_type_label(f),
                    nullable: f.field_type.nullable(),
                })
                .collect(),
        })
        .collect();
    ApisIndexCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: "API surface",
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        apis,
        openapi_url: "/admin/apis/openapi.json",
    }
}

#[derive(Serialize, Clone)]
pub(crate) struct HistoryChangeCtx {
    /// Snake-case field identifier (`title`, `published_at`).
    /// Surfaced as a `<dt>`'s `data-field` attribute mostly so
    /// downstream CSS can hook in if needed.
    pub field: String,
    /// Humanised label rendered as the row header (`Title`,
    /// `Published at`).
    pub label: String,
    /// Stringified previous value. Empty string means "was unset"
    /// (matches the column's display representation of NULL).
    pub from: String,
    /// Stringified new value. Same empty-means-unset convention.
    pub to: String,
}

#[derive(Serialize)]
pub(crate) struct ObjectHistoryCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub admin_name: String,
    pub display_name: String,
    pub singular_name: String,
    pub object_id: i64,
    pub object_label: String,
    /// Sidebar nav models — read by `_sidebar.html` as
    /// `{{ entry.admin_name }}` / `{{ entry.display_name }}`.
    /// Kept under the conventional `entries` name to match every
    /// other rendered page; the audit rows for the page body live
    /// in `history_entries` to avoid colliding on the sidebar
    /// template's reads.
    pub entries: Vec<SidebarEntry>,
    pub history_entries: Vec<HistoryEntryCtx>,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct LogEntriesCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    /// Sidebar nav models — see `ObjectHistoryCtx::entries`.
    pub entries: Vec<SidebarEntry>,
    pub history_entries: Vec<HistoryEntryCtx>,
    pub flash: Option<FlashCtx>,
    /// When `Some(label)`, the page is showing audit entries
    /// filtered by `?user_id=N`. The label is the actor's email
    /// (or `#<id>` fallback) for the banner. `None` → no filter
    /// banner rendered; the table shows the unfiltered feed.
    pub user_filter_label: Option<String>,
}

pub(crate) fn map_audit_actions(actions: Vec<AdminAction>) -> Vec<HistoryEntryCtx> {
    let mut prev_date_iso: Option<String> = None;
    actions
        .into_iter()
        .map(|a| {
            let changes = extract_changes_from_metadata(a.metadata.as_ref());
            let date_iso = a.timestamp.format("%Y-%m-%d").to_string();
            let is_new_day = prev_date_iso.as_deref() != Some(date_iso.as_str());
            prev_date_iso = Some(date_iso.clone());
            HistoryEntryCtx {
                timestamp_iso: a.timestamp.to_rfc3339(),
                when_relative: relative_time(a.timestamp),
                date_iso,
                is_new_day,
                user_id: a.user_id,
                user_email: a.user_email.unwrap_or_else(|| "".to_string()),
                label: action_label(&a.action_type),
                pill_class: action_pill_class(&a.action_type),
                model_name: a.model_name.clone(),
                // The audit row's `model_name` IS the admin_name slug per
                // the convention enforced at `audit::record` call sites.
                model_admin_name: a.model_name,
                action_type: a.action_type,
                object_id: a.object_id,
                summary: a.summary,
                ip_address: a.ip_address.unwrap_or_default(),
                changes,
            }
        })
        .collect()
}

/// Pull a `changes: [{field, label, from, to}, …]` array out of an
/// audit row's `metadata` JSONB. Any structural mismatch (no key,
/// not an array, entries missing fields) collapses to an empty
/// vec — the History page renders the row without a diff and the
/// caller never has to defend against malformed metadata.
///
/// The shape mirrors `handlers::FieldChange` so the JSON written
/// by `do_update` round-trips losslessly through Postgres' JSONB
/// column.
fn extract_changes_from_metadata(metadata: Option<&serde_json::Value>) -> Vec<HistoryChangeCtx> {
    let Some(obj) = metadata.and_then(|m| m.as_object()) else {
        return Vec::new();
    };
    let Some(arr) = obj.get("changes").and_then(|v| v.as_array()) else {
        return Vec::new();
    };
    arr.iter()
        .filter_map(|entry| {
            let o = entry.as_object()?;
            let field = o.get("field")?.as_str()?.to_string();
            let label = o
                .get("label")
                .and_then(|v| v.as_str())
                .unwrap_or(&field)
                .to_string();
            let from = o
                .get("from")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let to = o
                .get("to")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            Some(HistoryChangeCtx {
                field,
                label,
                from,
                to,
            })
        })
        .collect()
}

// ---- Password change page -----------------------------------------------

#[derive(Serialize)]
pub(crate) struct PasswordChangeCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub errors: Vec<String>,
    pub success: bool,
    pub sections: Vec<FormSection>,
}

// ---- Bespoke form sections (used by admin/builtin.rs) -------------------

/// Role options for user_new / user_edit. Labels carry privilege
/// descriptions; values are the role slugs the auth layer expects.
///
/// `editor_rank` filters out roles strictly above the editor's own
/// rank — first-line defense for the role-ceiling guard, so the user
/// never sees an option the server would reject. Server-side
/// `enforce_role_ceiling` catches forged POSTs as defense-in-depth;
/// this function is reflection, not security.
pub(crate) fn role_select_options(editor_rank: u32) -> Vec<SelectOption> {
    let all = [
        (crate::auth::Role::User, "user", "User (no admin access)"),
        (
            crate::auth::Role::Staff,
            "staff",
            "Staff (admin access; per-model group permissions)",
        ),
        (
            crate::auth::Role::Supervisor,
            "supervisor",
            "Supervisor (view + edit; no destructive ops)",
        ),
        (
            crate::auth::Role::Administrator,
            "administrator",
            "Administrator (full coverage; bypasses group checks)",
        ),
        (
            crate::auth::Role::Developer,
            "developer",
            "Developer (highest tier)",
        ),
    ];
    all.iter()
        .filter(|(role, _, _)| role.rank() <= editor_rank)
        .map(|(_, slug, label)| SelectOption {
            value: (*slug).to_string(),
            label: (*label).to_string(),
        })
        .collect()
}

/// FormField list for the user_new form. Two sections: Identity
/// (email + password) and Role (the 5-option select). Caller passes
/// the current values so re-render after validation failure preserves
/// them. `editor_rank` filters the role select per the ceiling guard.
/// `min_length` populates the password hint so a project that
/// overrides `Admin::password_policy(...)` sees its actual floor on
/// the form — passed in from `Admin::active_password_policy().min_length()`,
/// the same plumbing R1 commit #11 added for `password_change_form_sections`.
///
/// Pre-R2 the hint string was hardcoded to "8 characters"; R2
/// commit #3 routed it through the policy so the framework default
/// (10) and project overrides (12 / 16 / …) both render correctly.
pub(crate) fn user_new_form_sections(
    email: &str,
    role: &str,
    editor_rank: u32,
    min_length: usize,
) -> Vec<FormSection> {
    let password_hint = format!(
        "At least {min_length} characters. The user can change it later via Change password."
    );
    vec![
        FormSection {
            title: Some("Identity"),
            fields: vec![
                FormField {
                    name: "email",
                    label: "Email".to_string(),
                    widget: "input",
                    input_type: "email",
                    value: email.to_string(),
                    hint: Some("Must be unique across all users.".to_string()),
                    placeholder: None,
                    required: true,
                    options: None,
                    multiple: false,
                    span: 2,
                    autocomplete: Some("off"),
                    autofocus: true,
                    disabled: false,
                    maxlength: None,
                    searchable: false,
                    has_more: false,
                    search_url: None,
                    errors: vec![],
                    target_model: None,
                    checked: false,
                },
                FormField {
                    name: "password",
                    label: "Password".to_string(),
                    widget: "input",
                    input_type: "password",
                    value: String::new(),
                    hint: Some(password_hint),
                    placeholder: None,
                    required: true,
                    options: None,
                    multiple: false,
                    span: 2,
                    autocomplete: Some("new-password"),
                    autofocus: false,
                    disabled: false,
                    maxlength: None,
                    searchable: false,
                    has_more: false,
                    search_url: None,
                    errors: vec![],
                    target_model: None,
                    checked: false,
                },
            ],
        },
        FormSection {
            title: Some("Role"),
            fields: vec![FormField {
                name: "role",
                label: "Role".to_string(),
                widget: "select",
                input_type: "select",
                value: role.to_string(),
                hint: Some(
                    "Higher roles include all lower-role capabilities. Group memberships are assigned on the next page after save."
                        .to_string(),
                ),
                placeholder: None,
                required: true,
                options: Some(role_select_options(editor_rank)),
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            }],
        },
    ]
}

/// General section for group_new / group_edit. Two fields: name
/// (text, required, 150-char max) and description (textarea).
pub(crate) fn group_form_sections(name: &str, description: &str) -> Vec<FormSection> {
    vec![FormSection {
        title: Some("General"),
        fields: vec![
            FormField {
                name: "name",
                label: "Name".to_string(),
                widget: "input",
                input_type: "text",
                value: name.to_string(),
                hint: Some(
                    "A short identifier — letters, digits, dots and dashes only. Example: editors."
                        .to_string(),
                ),
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("off"),
                autofocus: true,
                disabled: false,
                maxlength: Some(150),
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "description",
                label: "Description".to_string(),
                widget: "textarea",
                input_type: "text",
                value: description.to_string(),
                hint: Some("Optional. What this group is for.".to_string()),
                placeholder: None,
                required: false,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
        ],
    }]
}

/// Identity section for user_edit. Email is disabled (read-only);
/// role is the select; is_active is the checkbox. Built per render
/// so values reflect the current row. `editor_rank` filters the role
/// select per the ceiling guard.
pub(crate) fn user_edit_identity_sections(
    email: &str,
    role: &str,
    is_active: bool,
    editor_rank: u32,
) -> Vec<FormSection> {
    vec![FormSection {
        title: Some("Identity"),
        fields: vec![
            FormField {
                name: "email",
                label: "Email".to_string(),
                widget: "input",
                input_type: "email",
                value: email.to_string(),
                hint: Some(
                    "Email changes aren't exposed here — they require a full user update."
                        .to_string(),
                ),
                placeholder: None,
                required: false,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: true,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "role",
                label: "Role".to_string(),
                widget: "select",
                input_type: "select",
                value: role.to_string(),
                hint: None,
                placeholder: None,
                required: true,
                options: Some(role_select_options(editor_rank)),
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "is_active",
                label: "Active".to_string(),
                widget: "checkbox",
                input_type: "checkbox",
                value: if is_active {
                    "true".to_string()
                } else {
                    "false".to_string()
                },
                hint: Some("Inactive users cannot sign in or hold sessions.".to_string()),
                placeholder: None,
                required: false,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: is_active,
            },
        ],
    }]
}

/// Pre-built FormField list for the password-change form. Values are
/// always empty (we never echo passwords back). The
/// `min_length` parameter controls the live policy hint shown
/// beneath the new-password input — passed in from
/// `Admin::active_password_policy().min_length()` so a project that
/// overrides the policy gets accurate copy on the form
/// (`DESIGN_RECOVERY.md` §13).
///
/// Pre-R1 the hint string was hardcoded to "8 characters"; R1
/// commit #11 routed it through the policy so the framework
/// default (10) and project overrides (12 / 16 / …) both render
/// correctly.
pub(crate) fn password_change_form_sections(min_length: usize) -> Vec<FormSection> {
    let new_password_hint = format!("At least {min_length} characters.");
    vec![FormSection {
        title: None,
        fields: vec![
            FormField {
                name: "old_password",
                label: "Old password".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("current-password"),
                autofocus: true,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "new_password1",
                label: "New password".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: Some(new_password_hint),
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("new-password"),
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "new_password2",
                label: "Confirm".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("new-password"),
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
        ],
    }]
}

/// FormField list for the R2 forced-rotation interstitial
/// (`/admin/must-change-password`). Two fields — `new_password1`
/// and `new_password2` — and no `old_password`: the user has just
/// authenticated with the temp password the admin issued seconds
/// ago, and the design contract (`DESIGN_R2_ORGANISATIONAL.md`
/// §3.4) intentionally skips collecting it again.
///
/// `min_length` is read from
/// `Admin::active_password_policy().min_length()`, mirroring R1's
/// [`password_change_form_sections`].
pub(crate) fn must_change_password_form_sections(min_length: usize) -> Vec<FormSection> {
    let new_password_hint = format!("At least {min_length} characters.");
    vec![FormSection {
        title: None,
        fields: vec![
            FormField {
                name: "new_password1",
                label: "New password".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: Some(new_password_hint),
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("new-password"),
                autofocus: true,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "new_password2",
                label: "Confirm".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("new-password"),
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
        ],
    }]
}

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

    /// `humanise_field` and its macro-side mirror must produce
    /// identical output. This battery pins the contract; if a
    /// future change drifts one without the other the validation-
    /// error routing in [`bucket_errors_by_label`] breaks because
    /// the runtime label no longer matches the macro-emitted one.
    #[test]
    fn humanise_field_standalone_acronyms() {
        // The shipped fix: `id` no longer humanises to `Id`.
        assert_eq!(humanise_field("id"), "ID");
        assert_eq!(humanise_field("ip"), "IP");
        assert_eq!(humanise_field("url"), "URL");
        assert_eq!(humanise_field("uuid"), "UUID");
        assert_eq!(humanise_field("mfa"), "MFA");
    }

    #[test]
    fn humanise_field_compound_acronyms() {
        assert_eq!(humanise_field("email_id"), "Email ID");
        assert_eq!(humanise_field("id_card"), "ID Card");
        assert_eq!(humanise_field("user_ip"), "User IP");
        assert_eq!(humanise_field("api_token"), "API Token");
        assert_eq!(humanise_field("mfa_secret_key_id"), "MFA Secret Key ID");
        assert_eq!(humanise_field("csv_export_path"), "CSV Export Path");
    }

    #[test]
    fn humanise_field_acronym_substrings_left_alone() {
        // Whole-word rule: `id` inside `video` does not become
        // `vIDeo`. Same for `ip` inside `recipe`, etc.
        assert_eq!(humanise_field("video"), "Video");
        assert_eq!(humanise_field("video_url"), "Video URL");
        assert_eq!(humanise_field("hidden_field"), "Hidden Field");
        assert_eq!(humanise_field("idle_seconds"), "Idle Seconds");
    }

    #[test]
    fn humanise_field_plain_snake_case() {
        assert_eq!(humanise_field("title"), "Title");
        assert_eq!(humanise_field("chart_number"), "Chart Number");
        assert_eq!(humanise_field("full_name"), "Full Name");
        assert_eq!(
            humanise_field("performed_by_technician"),
            "Performed By Technician",
        );
    }

    #[test]
    fn humanise_field_edge_cases() {
        assert_eq!(humanise_field(""), "");
        assert_eq!(humanise_field("a"), "A");
        assert_eq!(humanise_field("created_at"), "Created At");
        assert_eq!(humanise_field("revoked_by"), "Revoked By");
    }

    #[test]
    fn sort_direction_label_strings_read_alphabetical() {
        use super::super::modeladmin::SortDir;
        use super::super::types::FieldType::*;
        // Required and optional flavours share the same copy.
        assert_eq!(sort_direction_label(String, SortDir::Asc), "A → Z");
        assert_eq!(sort_direction_label(String, SortDir::Desc), "Z → A");
        assert_eq!(sort_direction_label(OptionalString, SortDir::Asc), "A → Z");
        assert_eq!(sort_direction_label(OptionalString, SortDir::Desc), "Z → A");
    }

    #[test]
    fn sort_direction_label_filepaths_read_alphabetical() {
        // FilePath / OptionalFilePath store strings on the wire
        // and sort lexicographically — they belong in the same
        // copy bucket as String, not the numeric fallback that
        // used to read "Photo Path (ascending)" / "(descending)"
        // and surfaced as a UX nit on the patients list page.
        use super::super::modeladmin::SortDir;
        use super::super::types::FieldType::*;
        assert_eq!(sort_direction_label(FilePath, SortDir::Asc), "A → Z");
        assert_eq!(sort_direction_label(FilePath, SortDir::Desc), "Z → A");
        assert_eq!(
            sort_direction_label(OptionalFilePath, SortDir::Asc),
            "A → Z"
        );
        assert_eq!(
            sort_direction_label(OptionalFilePath, SortDir::Desc),
            "Z → A"
        );
    }

    #[test]
    fn sort_direction_label_datetimes_read_chronological() {
        use super::super::modeladmin::SortDir;
        use super::super::types::FieldType::*;
        assert_eq!(sort_direction_label(DateTime, SortDir::Asc), "oldest first");
        assert_eq!(
            sort_direction_label(DateTime, SortDir::Desc),
            "newest first"
        );
        assert_eq!(
            sort_direction_label(OptionalDateTime, SortDir::Asc),
            "oldest first",
        );
        assert_eq!(
            sort_direction_label(OptionalDateTime, SortDir::Desc),
            "newest first",
        );
    }

    #[test]
    fn sort_direction_label_bools_read_off_on() {
        use super::super::modeladmin::SortDir;
        use super::super::types::FieldType::*;
        assert_eq!(sort_direction_label(Bool, SortDir::Asc), "off → on");
        assert_eq!(sort_direction_label(Bool, SortDir::Desc), "on → off");
    }

    #[test]
    fn sort_direction_label_numerics_read_highest_lowest() {
        // Numeric columns get the same direction-aware treatment
        // as datetime / string / bool: "lowest first" /
        // "highest first" beats generic "ascending" / "descending"
        // for a column named `count`, `score`, `priority`, or any
        // other quantity an operator scans by magnitude.
        use super::super::modeladmin::SortDir;
        use super::super::types::FieldType::*;
        assert_eq!(sort_direction_label(I32, SortDir::Asc), "lowest first");
        assert_eq!(sort_direction_label(I64, SortDir::Asc), "lowest first");
        assert_eq!(
            sort_direction_label(OptionalI64, SortDir::Desc),
            "highest first"
        );
    }

    /// `VISIBILITY_AUDIT.md` finding B3 enforcement.
    ///
    /// Every `AuditEvent::as_str()` value MUST have a non-generic
    /// label entry in [`action_label`]. Pre-0.8.1 the function knew
    /// only `create / update / delete` and fell through to "Action"
    /// for everything else, so the History page rendered identical
    /// generic pills for every R1+ event.
    ///
    /// When a new `AuditEvent` variant ships, this test fails until
    /// the new event-string is added to the `action_label` match.
    /// Same drift-protection shape as the
    /// `audit_event_existing_variants_have_stable_strings` test in
    /// `admin/audit.rs`.
    #[test]
    fn action_label_covers_every_audit_event_string() {
        // Canonical list of every audit-event string written into
        // `rustio_admin_actions.action_type`. Mirrors the
        // `ALL_AUDIT_EVENTS` array in `admin/audit.rs::tests` —
        // duplicated here because the audit array lives under
        // `#[cfg(test)]` in a different module.
        let known_event_strings: &[&str] = &[
            // Legacy CRUD namespace.
            "create",
            "update",
            "delete",
            // R0 user / group lifecycle.
            "user_created",
            "user_updated",
            "user_deleted",
            "group_created",
            "group_updated",
            "group_deleted",
            // R1 self-recovery.
            "password_changed_self",
            "password_reset_self_request",
            "password_reset_self_consume",
            // R2 organisational recovery.
            "password_reset_by_other",
            "forced_password_change_completed",
            "account_locked",
            "account_unlocked",
            // R3 TOTP MFA.
            "mfa_enabled",
            "mfa_disabled",
            "mfa_reset_by_other",
            "mfa_code_consumed",
            "backup_codes_regenerated",
            // R0/R1 session lifecycle.
            "sessions_revoked_self",
            "sessions_revoked_by_other",
            "session_logout",
            // Authentication events.
            "login_succeeded",
            "login_failed",
            // R4 emergency recovery.
            "emergency_recovery",
        ];
        let mut missing: Vec<&'static str> = Vec::new();
        for &s in known_event_strings {
            if action_label(s) == "Action" {
                missing.push(s);
            }
        }
        assert!(
            missing.is_empty(),
            "action_label falls through to the generic \"Action\" \
             label for these event strings — add explicit match arms \
             in `admin/render.rs::action_label` (and pick a pill class \
             in `action_pill_class`): {missing:?}"
        );
    }

    #[test]
    fn action_pill_class_returns_known_classes() {
        // Every pill class must be one the CSS knows about. New
        // arms must use one of `badge-success / badge-neutral /
        // badge-danger / badge-warning` — see
        // `assets/static/admin.css` for the rio-pill-- definitions.
        let known_strings: &[&str] = &[
            "create",
            "update",
            "delete",
            "user_created",
            "user_updated",
            "user_deleted",
            "group_created",
            "group_updated",
            "group_deleted",
            "password_changed_self",
            "password_reset_self_request",
            "password_reset_self_consume",
            "password_reset_by_other",
            "forced_password_change_completed",
            "account_locked",
            "account_unlocked",
            "mfa_enabled",
            "mfa_disabled",
            "mfa_reset_by_other",
            "mfa_code_consumed",
            "backup_codes_regenerated",
            "sessions_revoked_self",
            "sessions_revoked_by_other",
            "session_logout",
            "login_succeeded",
            "login_failed",
            "emergency_recovery",
        ];
        let known_classes = [
            "badge-success",
            "badge-neutral",
            "badge-danger",
            "badge-warning",
        ];
        for &s in known_strings {
            let class = action_pill_class(s);
            assert!(
                known_classes.contains(&class),
                "action_pill_class({s:?}) returned {class:?} which is \
                 not one of {known_classes:?}"
            );
        }
    }

    #[test]
    fn ua_summary_macos_safari() {
        let ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";
        assert_eq!(summarise_user_agent(Some(ua)), "macOS · Safari");
    }

    #[test]
    fn ua_summary_windows_chrome() {
        let ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        assert_eq!(summarise_user_agent(Some(ua)), "Windows · Chrome");
    }

    #[test]
    fn ua_summary_linux_firefox() {
        let ua = "Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0";
        assert_eq!(summarise_user_agent(Some(ua)), "Linux · Firefox");
    }

    #[test]
    fn ua_summary_android_chrome() {
        let ua = "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36";
        assert_eq!(summarise_user_agent(Some(ua)), "Android · Chrome");
    }

    #[test]
    fn ua_summary_ios_safari() {
        let ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1";
        assert_eq!(summarise_user_agent(Some(ua)), "iOS · Safari");
    }

    #[test]
    fn ua_summary_curl_falls_through_to_unknown_os() {
        // curl/8.4.0 — no OS identifier, only browser. Returns the raw
        // UA truncated.
        let ua = "curl/8.4.0";
        let s = summarise_user_agent(Some(ua));
        assert!(s.contains("curl"));
    }

    #[test]
    fn ua_summary_unknown_returns_truncated() {
        let ua =
            "QuiteUnusualUserAgent/1.0 with extremely long descriptor that should be truncated";
        let s = summarise_user_agent(Some(ua));
        assert!(s.len() <= 40);
    }

    #[test]
    fn ua_summary_none_returns_dash() {
        assert_eq!(summarise_user_agent(None), "");
    }

    #[test]
    fn trust_label_strings() {
        assert_eq!(
            trust_label(crate::auth::SessionTrust::Authenticated),
            "Signed in"
        );
        assert_eq!(trust_label(crate::auth::SessionTrust::Elevated), "Elevated");
        assert_eq!(
            trust_label(crate::auth::SessionTrust::MfaVerified),
            "MFA verified"
        );
    }

    /// R1 commit #11 — `password_change_form_sections` reflects the
    /// caller-supplied `min_length` so a project that overrides the
    /// `PasswordPolicy` floor sees accurate copy on the form. The
    /// pre-R1 hardcoded "8 characters" is gone.
    #[test]
    fn password_change_form_sections_renders_live_min_length() {
        let sections = password_change_form_sections(10);
        assert_eq!(sections.len(), 1);
        let fields = &sections[0].fields;
        // Three fields: old_password, new_password1, new_password2.
        assert_eq!(fields.len(), 3);
        assert_eq!(fields[0].name, "old_password");
        assert_eq!(fields[1].name, "new_password1");
        assert_eq!(fields[2].name, "new_password2");
        // Hint reflects the caller's parameter, not a hardcoded
        // "8" or "12".
        assert_eq!(
            fields[1].hint.as_deref(),
            Some("At least 10 characters."),
            "default-policy floor 10 must surface in the hint"
        );

        // Project override propagates.
        let sections = password_change_form_sections(16);
        assert_eq!(
            sections[0].fields[1].hint.as_deref(),
            Some("At least 16 characters."),
        );
    }

    /// Old + confirm fields don't carry the hint — only the new-
    /// password field does. Belt-and-braces: the policy minimum is
    /// surfaced exactly once, beneath the input the user is typing
    /// the new password into.
    #[test]
    fn password_change_form_sections_only_new_password_carries_hint() {
        let sections = password_change_form_sections(10);
        let fields = &sections[0].fields;
        assert!(fields[0].hint.is_none(), "old_password must have no hint");
        assert!(fields[1].hint.is_some(), "new_password1 must have the hint");
        assert!(fields[2].hint.is_none(), "new_password2 must have no hint");
    }

    /// `ModelAdmin::fieldsets()` honoured: each fieldset becomes a
    /// titled section in declaration order, fields render in the
    /// order the project listed them inside each fieldset.
    #[test]
    fn fieldsets_drive_section_order_and_titles() {
        use super::super::modeladmin::Fieldset;
        let fields = vec![
            stub_form_field("title"),
            stub_form_field("body"),
            stub_form_field("created_at"),
            stub_form_field("slug"),
        ];
        // Note: declare "body" before "title" so the section flips
        // the in-flat order — proves we respect Fieldset.fields
        // ordering, not the original Vec ordering.
        let fieldsets: &'static [Fieldset] = &[
            Fieldset {
                title: "Content",
                fields: &["body", "title"],
            },
            Fieldset {
                title: "Metadata",
                fields: &["created_at"],
            },
        ];
        let sections = group_fields_by_fieldsets(fields, fieldsets);
        // Two declared sections + trailing "Other" for `slug` (the
        // model field nobody listed in a fieldset).
        assert_eq!(sections.len(), 3);
        assert_eq!(sections[0].title, Some("Content"));
        assert_eq!(
            sections[0]
                .fields
                .iter()
                .map(|f| f.name)
                .collect::<Vec<_>>(),
            vec!["body", "title"],
        );
        assert_eq!(sections[1].title, Some("Metadata"));
        assert_eq!(
            sections[1]
                .fields
                .iter()
                .map(|f| f.name)
                .collect::<Vec<_>>(),
            vec!["created_at"],
        );
        assert_eq!(sections[2].title, Some("Other"));
        assert_eq!(
            sections[2]
                .fields
                .iter()
                .map(|f| f.name)
                .collect::<Vec<_>>(),
            vec!["slug"],
        );
    }

    /// Names in a `Fieldset` with no matching `FormField` are
    /// silently skipped — a typo doesn't panic in production. An
    /// empty section is also dropped so the form doesn't render a
    /// titled blank.
    #[test]
    fn fieldsets_with_unknown_field_names_skip_silently() {
        use super::super::modeladmin::Fieldset;
        let fields = vec![stub_form_field("title")];
        let fieldsets: &'static [Fieldset] = &[
            Fieldset {
                title: "Real",
                fields: &["title", "typo_nonexistent"],
            },
            Fieldset {
                title: "Empty",
                fields: &["also_missing"],
            },
        ];
        let sections = group_fields_by_fieldsets(fields, fieldsets);
        // "Empty" is dropped (zero matches); "Real" stays with just
        // the one real field.
        assert_eq!(sections.len(), 1);
        assert_eq!(sections[0].title, Some("Real"));
        assert_eq!(sections[0].fields.len(), 1);
        assert_eq!(sections[0].fields[0].name, "title");
    }

    fn stub_form_field(name: &'static str) -> FormField {
        FormField {
            name,
            label: name.to_string(),
            widget: "input",
            input_type: "text",
            value: String::new(),
            hint: None,
            placeholder: None,
            required: false,
            options: None,
            multiple: false,
            span: 1,
            autocomplete: None,
            autofocus: false,
            disabled: false,
            maxlength: None,
            searchable: false,
            has_more: false,
            search_url: None,
            errors: vec![],
            target_model: None,
            checked: false,
        }
    }

    // ---- highlight_search_match -------------------------------------

    #[test]
    fn highlight_returns_none_when_no_match() {
        assert_eq!(highlight_search_match("Anna Lindqvist", "zzz"), None);
    }

    #[test]
    fn highlight_returns_none_for_empty_term() {
        // The caller has already short-circuited on empty term, but
        // make the function defensive anyway.
        assert_eq!(highlight_search_match("anything", ""), None);
    }

    #[test]
    fn highlight_wraps_ascii_case_insensitive() {
        let html = highlight_search_match("Anna Lindqvist", "anna").unwrap();
        assert_eq!(html, "<mark>Anna</mark> Lindqvist");
    }

    #[test]
    fn highlight_wraps_every_occurrence() {
        let html = highlight_search_match("abc ABC abC", "abc").unwrap();
        assert_eq!(html, "<mark>abc</mark> <mark>ABC</mark> <mark>abC</mark>");
    }

    #[test]
    fn highlight_escapes_html_around_marks() {
        // A cell containing literal HTML special chars must not
        // smuggle them into the rendered DOM. The mark wraps the
        // matched substring; everything else is escaped.
        let html = highlight_search_match("name<script>alert('x')</script>", "name").unwrap();
        assert!(html.starts_with("<mark>name</mark>"));
        assert!(html.contains("&lt;script&gt;"));
        assert!(html.contains("&#39;x&#39;"));
        assert!(!html.contains("<script>"));
    }

    #[test]
    fn highlight_escapes_inside_mark_when_term_contains_specials() {
        // Pathological but possible: an operator searches for a
        // literal `<`. The mark wraps the match, and the match
        // itself escapes the special char.
        let html = highlight_search_match("a<b<c", "<").unwrap();
        assert_eq!(html, "a<mark>&lt;</mark>b<mark>&lt;</mark>c");
    }

    #[test]
    fn highlight_preserves_non_ascii_bytes_around_match() {
        // `to_ascii_lowercase` leaves non-ASCII bytes untouched, so
        // byte offsets line up. A Swedish name with a Latin search
        // term should still highlight the ASCII portion that matched.
        let html = highlight_search_match("Anna Wåhlin", "ann").unwrap();
        assert_eq!(html, "<mark>Ann</mark>a Wåhlin");
    }

    #[test]
    fn highlight_handles_adjacent_matches() {
        let html = highlight_search_match("aaaa", "aa").unwrap();
        // Greedy non-overlapping match: positions 0..2 and 2..4.
        assert_eq!(html, "<mark>aa</mark><mark>aa</mark>");
    }

    // ---- extract_changes_from_metadata -----------------------------

    #[test]
    fn extract_changes_returns_empty_when_metadata_is_none() {
        let r = extract_changes_from_metadata(None);
        assert!(r.is_empty());
    }

    #[test]
    fn extract_changes_returns_empty_when_changes_key_missing() {
        let meta = serde_json::json!({ "actor_user_id": 42 });
        let r = extract_changes_from_metadata(Some(&meta));
        assert!(r.is_empty());
    }

    #[test]
    fn extract_changes_returns_empty_when_changes_not_array() {
        let meta = serde_json::json!({ "changes": "not-an-array" });
        let r = extract_changes_from_metadata(Some(&meta));
        assert!(r.is_empty());
    }

    #[test]
    fn extract_changes_round_trips_full_entry() {
        let meta = serde_json::json!({
            "changes": [
                { "field": "title", "label": "Title", "from": "Old", "to": "New" },
                { "field": "body",  "label": "Body",  "from": "",    "to": "Filled in" },
            ]
        });
        let r = extract_changes_from_metadata(Some(&meta));
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].field, "title");
        assert_eq!(r[0].label, "Title");
        assert_eq!(r[0].from, "Old");
        assert_eq!(r[0].to, "New");
        // Empty `from` survives — represents "was unset."
        assert_eq!(r[1].from, "");
        assert_eq!(r[1].to, "Filled in");
    }

    #[test]
    fn extract_changes_falls_back_to_field_when_label_missing() {
        // Old audit rows (or hand-edited entries) might omit `label`.
        // Fall back to the snake-case field name so the UI still
        // renders something — better than blanking the row.
        let meta = serde_json::json!({
            "changes": [
                { "field": "title", "from": "a", "to": "b" }
            ]
        });
        let r = extract_changes_from_metadata(Some(&meta));
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].label, "title");
    }

    #[test]
    fn extract_changes_skips_malformed_entries() {
        // Entries missing `field` are dropped silently — the
        // metadata is producer-controlled but we still defend.
        let meta = serde_json::json!({
            "changes": [
                { "field": "title", "from": "a", "to": "b" },
                { "label": "missing-field", "from": "x", "to": "y" },
                "not-an-object",
            ]
        });
        let r = extract_changes_from_metadata(Some(&meta));
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].field, "title");
    }
}