autumn-web 0.10.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
//! Search widgets: active search and autocomplete.
//!
//! Needs the `widgets-search` feature (on by default).

use super::selector_to_id;

/// HTTP method for an [`ActiveSearchConfig`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum SearchMethod {
    /// `GET` request — the default. Safe, idempotent, bookmarkable.
    #[default]
    Get,
    /// `POST` request — opt-in for handlers that need a request body.
    Post,
}

/// Configuration for an [`active_search_input`] widget.
///
/// Build with [`ActiveSearchConfig::new`] and chain builder methods for
/// optional overrides.
///
/// # Example
///
/// ```rust,ignore
/// use autumn_web::widgets::{ActiveSearchConfig, active_search};
///
/// let config = ActiveSearchConfig::new("/users/search", "#user-results")
///     .debounce(500)
///     .min_length(2)
///     .placeholder("Search users…");
///
/// let widget = active_search("user-search", "Search users", &config);
/// ```
#[derive(Debug, Clone)]
pub struct ActiveSearchConfig<'a> {
    /// URL of the server-side search handler.
    pub action: &'a str,
    /// HTTP method (default: [`SearchMethod::Get`]).
    pub method: SearchMethod,
    /// CSS selector for the element that receives rendered results.
    pub target: &'a str,
    /// CSS selector for an element shown while the request is in flight.
    pub indicator: Option<&'a str>,
    /// Debounce delay in milliseconds (default: `300`).
    pub debounce_ms: u32,
    /// Minimum character count before triggering a search (default: `1`).
    pub min_length: u32,
    /// Query parameter name sent to the handler (default: `"q"`).
    pub param_name: &'a str,
    /// Whether to fire the search immediately on page load (default: `false`).
    pub initial_load: bool,
    /// Optional placeholder text for the search input.
    pub placeholder: Option<&'a str>,
}

impl<'a> ActiveSearchConfig<'a> {
    /// Create a new active search configuration with sensible defaults.
    ///
    /// - `action` — URL of the search handler
    /// - `target` — CSS selector for the results container, e.g. `"#search-results"`
    #[must_use]
    pub const fn new(action: &'a str, target: &'a str) -> Self {
        Self {
            action,
            method: SearchMethod::Get,
            target,
            indicator: None,
            debounce_ms: 300,
            min_length: 1,
            param_name: "q",
            initial_load: false,
            placeholder: None,
        }
    }

    /// Use `POST` instead of the default `GET` for the search request.
    #[must_use]
    pub const fn post(mut self) -> Self {
        self.method = SearchMethod::Post;
        self
    }

    /// Set the debounce delay in milliseconds (default: `300`).
    #[must_use]
    pub const fn debounce(mut self, ms: u32) -> Self {
        self.debounce_ms = ms;
        self
    }

    /// Set the minimum query length before a search is triggered (default: `1`).
    #[must_use]
    pub const fn min_length(mut self, n: u32) -> Self {
        self.min_length = n;
        self
    }

    /// Set a CSS selector for the htmx loading indicator element.
    #[must_use]
    pub const fn indicator(mut self, selector: &'a str) -> Self {
        self.indicator = Some(selector);
        self
    }

    /// Trigger a search on initial page load (useful for pre-populated results).
    #[must_use]
    pub const fn initial_load(mut self) -> Self {
        self.initial_load = true;
        self
    }

    /// Set placeholder text for the search input.
    #[must_use]
    pub const fn placeholder(mut self, text: &'a str) -> Self {
        self.placeholder = Some(text);
        self
    }

    /// Set a custom query parameter name (default: `"q"`).
    #[must_use]
    pub const fn param_name(mut self, name: &'a str) -> Self {
        self.param_name = name;
        self
    }
}

/// Configuration for an [`autocomplete_input`] widget.
///
/// Build with [`AutocompleteConfig::new`] and chain builder methods for
/// optional overrides.
#[derive(Debug, Clone)]
pub struct AutocompleteConfig<'a> {
    /// URL of the server-side autocomplete handler.
    pub action: &'a str,
    /// CSS selector for an element shown while the request is in flight.
    pub indicator: Option<&'a str>,
    /// Debounce delay in milliseconds (default: `300`).
    pub debounce_ms: u32,
    /// Minimum character count before triggering autocomplete (default: `1`).
    pub min_length: u32,
    /// Query parameter name sent to the handler and used as the visible input's
    /// `name` (default: `"q"`).
    pub query_param: &'a str,
    /// `name` attribute of the hidden input that holds the selected value.
    /// In multiple mode, each chip's hidden input has this name.
    pub value_name: &'a str,
    /// Optional placeholder text for the visible input.
    pub placeholder: Option<&'a str>,
    /// Static `(value, label)` pairs for the `<noscript>` `<select>` fallback.
    pub fallback_options: Option<&'a [(&'a str, &'a str)]>,
    /// When `true`, the hidden field is kept in sync with whatever the user
    /// types, so submitting without picking an option sends the typed text.
    ///
    /// Use this for tag-style fields where the submitted value is the text
    /// itself (e.g. `name="tag"` with `autocomplete_option(tag, tag)`). Leave
    /// `false` (the default) for ID-based lookups where the hidden field should
    /// only carry a value selected from the option list.
    ///
    /// In multiple mode, Enter adds the typed text as a chip when no option
    /// is active. A form submit also adds the typed text as a chip.
    pub free_text: bool,
    /// Pre-fill the widget from a previous submission (e.g. re-rendering a
    /// form after a validation error), so free-text input the user already
    /// typed isn't silently dropped. Seeds both the visible query input's
    /// `value` and the hidden field's `value`. Leave unset (the default) for a
    /// blank widget. Multiple mode does not use it. Use
    /// [`selected`](Self::selected) there.
    pub initial_value: Option<&'a str>,
    /// Multi-value (tags) mode (issue #3410). Each pick is a removable
    /// chip. Each chip submits one hidden `{value_name}={value}` input, so a
    /// `Vec<T>` field decodes the repeated keys. Default: `false`.
    pub multiple: bool,
    /// The `(value, label)` chips that show first in multiple mode, for
    /// example from the database on an edit form. Default: none.
    ///
    /// [`autocomplete_input_for`] uses these pairs only to find labels.
    pub selected: &'a [(&'a str, &'a str)],
    /// The `aria-label` of each chip's remove button. `{label}` is replaced
    /// by the chip label. Default: `"Remove {label}"`.
    pub remove_label: &'a str,
    /// The status text after a chip is added. `{label}` is replaced by the
    /// chip label. Default: `"{label} added"`.
    pub added_message: &'a str,
    /// The status text after a chip is removed. `{label}` is replaced by the
    /// chip label. Default: `"{label} removed"`.
    pub removed_message: &'a str,
}

impl<'a> AutocompleteConfig<'a> {
    /// Create a new autocomplete configuration with sensible defaults.
    ///
    /// - `action` — URL of the autocomplete handler
    /// - `value_name` — `name` attribute for the hidden selected-ID input
    #[must_use]
    pub const fn new(action: &'a str, value_name: &'a str) -> Self {
        Self {
            action,
            indicator: None,
            debounce_ms: 300,
            min_length: 1,
            query_param: "q",
            value_name,
            placeholder: None,
            fallback_options: None,
            free_text: false,
            initial_value: None,
            multiple: false,
            selected: &[],
            remove_label: "Remove {label}",
            added_message: "{label} added",
            removed_message: "{label} removed",
        }
    }

    /// Set the debounce delay in milliseconds (default: `300`).
    #[must_use]
    pub const fn debounce(mut self, ms: u32) -> Self {
        self.debounce_ms = ms;
        self
    }

    /// Set the minimum query length before autocomplete triggers (default: `1`).
    #[must_use]
    pub const fn min_length(mut self, n: u32) -> Self {
        self.min_length = n;
        self
    }

    /// Set a CSS selector for the htmx loading indicator element.
    #[must_use]
    pub const fn indicator(mut self, selector: &'a str) -> Self {
        self.indicator = Some(selector);
        self
    }

    /// Set a custom query parameter name (default: `"q"`).
    #[must_use]
    pub const fn query_param(mut self, name: &'a str) -> Self {
        self.query_param = name;
        self
    }

    /// Set placeholder text for the visible input.
    #[must_use]
    pub const fn placeholder(mut self, text: &'a str) -> Self {
        self.placeholder = Some(text);
        self
    }

    /// Set static `(value, label)` pairs for the no-JavaScript `<select>` fallback.
    #[must_use]
    pub const fn fallback_options(mut self, options: &'a [(&'a str, &'a str)]) -> Self {
        self.fallback_options = Some(options);
        self
    }

    /// Enable free-text mode: the hidden field is kept in sync with whatever
    /// the user types, so submitting without choosing an option sends the typed
    /// text as the field value.
    ///
    /// Use for tag-style fields (`name="tag"`) where creating new values by
    /// typing is allowed. Leave disabled (the default) for ID-based foreign-key
    /// lookups where only values from the option list are valid.
    #[must_use]
    pub const fn free_text(mut self) -> Self {
        self.free_text = true;
        self
    }

    /// Pre-fill the widget from a previous submission (e.g. re-rendering after
    /// a validation error), so already-typed input isn't silently dropped.
    #[must_use]
    pub const fn initial_value(mut self, value: &'a str) -> Self {
        self.initial_value = Some(value);
        self
    }

    /// Turn on multi-value (tags) mode. See [`AutocompleteConfig::multiple`]
    /// (the field).
    ///
    /// With [`free_text`](Self::free_text), Enter adds the typed text as a
    /// chip when no option is active.
    #[must_use]
    pub const fn multiple(mut self) -> Self {
        self.multiple = true;
        self
    }

    /// Show these `(value, label)` chips first (multiple mode).
    ///
    /// To pre-fill from a [`Changeset`](crate::form::Changeset), use
    /// [`autocomplete_input_for`]. It uses these pairs to find labels, in
    /// both modes.
    #[must_use]
    pub const fn selected(mut self, chips: &'a [(&'a str, &'a str)]) -> Self {
        self.selected = chips;
        self
    }

    /// Set the `aria-label` of each remove button (default:
    /// `"Remove {label}"`). `{label}` is replaced by the chip label. Use it
    /// to translate the widget, for example `"{label} を削除"`.
    #[must_use]
    pub const fn remove_label(mut self, template: &'a str) -> Self {
        self.remove_label = template;
        self
    }

    /// Set the status text after a chip is added (default:
    /// `"{label} added"`). A screen reader speaks it.
    #[must_use]
    pub const fn added_message(mut self, template: &'a str) -> Self {
        self.added_message = template;
        self
    }

    /// Set the status text after a chip is removed (default:
    /// `"{label} removed"`). A screen reader speaks it.
    #[must_use]
    pub const fn removed_message(mut self, template: &'a str) -> Self {
        self.removed_message = template;
        self
    }
}

/// Build the `hx-trigger` value for active search / autocomplete inputs.
///
/// The canonical form is `input changed delay:{n}ms[, load]`.
/// No filter expressions are emitted; `min_length` is enforced server-side so
/// the trigger works under Autumn's default `script-src 'self'` CSP (no `unsafe-eval`).
fn build_trigger(debounce_ms: u32, initial_load: bool) -> String {
    let mut trigger = format!("input changed delay:{debounce_ms}ms");
    if initial_load {
        trigger.push_str(", load");
    }
    trigger
}

/// The `hx-trigger` of a tags-mode input: `input delay:{n}ms`.
///
/// It has no `changed` modifier. The runtime clears the input after each
/// pick, and the clear fires no `input` event. With `changed`, htmx then
/// keeps the old query, and the same query again sends no request.
fn build_tags_trigger(debounce_ms: u32) -> String {
    format!("input delay:{debounce_ms}ms")
}

/// Render a labeled `<input type="search">` with htmx active-search attributes.
///
/// Fires debounced GET (or POST) requests as the user types and on Enter,
/// targeting `config.target`. An accessible `<label>` and `aria-controls`
/// pointing at the results container are included automatically.
///
/// Pair with [`active_search_results`] for the results container, or use
/// [`active_search`] to emit the complete widget (input + results + noscript).
///
/// # htmx attributes emitted
///
/// | Attribute | Value |
/// |-----------|-------|
/// | `hx-get` / `hx-post` | `config.action` |
/// | `hx-trigger` | `input changed delay:{n}ms[, load]` |
/// | `hx-target` | `config.target` |
/// | `hx-indicator` | `config.indicator` (only when set) |
#[must_use]
pub fn active_search_input(id: &str, label: &str, config: &ActiveSearchConfig<'_>) -> maud::Markup {
    let trigger = build_trigger(config.debounce_ms, config.initial_load);
    let aria_controls = selector_to_id(config.target);
    let (hx_get, hx_post) = match config.method {
        SearchMethod::Get => (Some(config.action), None::<&str>),
        SearchMethod::Post => (None, Some(config.action)),
    };

    maud::html! {
        div class="autumn-search" {
            label for=(id) class="autumn-search__label" { (label) }
            input
                type="search"
                id=(id)
                name=(config.param_name)
                autocomplete="off"
                aria-controls=(aria_controls)
                placeholder=[config.placeholder]
                class="autumn-search__input"
                data-ac-min-length=(config.min_length)
                hx-get=[hx_get]
                hx-post=[hx_post]
                hx-trigger=(trigger)
                hx-target=(config.target)
                hx-indicator=[config.indicator];
        }
    }
}

/// Render the results container element targeted by [`active_search_input`].
///
/// Uses `role="status"` and `aria-live="polite"` so screen readers announce
/// result updates without moving keyboard focus.
#[must_use]
pub fn active_search_results(id: &str) -> maud::Markup {
    maud::html! {
        div
            id=(id)
            role="status"
            aria-live="polite"
            aria-atomic="true" {}
    }
}

/// Render a complete active search widget.
///
/// Emits:
/// - A labeled search input with htmx active-search attributes.
/// - A results container whose `id` is derived from `config.target`.
/// - A `<noscript>` fallback form that works without JavaScript.
///
/// **`config.target` must be a `#id` selector** (e.g. `"#bookmark-search-results"`).
/// This function derives the results container `id` by stripping the leading `#`, so
/// class selectors (`.foo`) or other forms produce an invalid HTML `id` attribute.
/// Use [`active_search_input`] + [`active_search_results`] directly if you need a
/// non-id htmx target.
///
/// # Example
///
/// ```rust,ignore
/// use autumn_web::widgets::{ActiveSearchConfig, active_search};
///
/// let config = ActiveSearchConfig::new("/bookmarks/search", "#bookmark-search-results")
///     .placeholder("Search bookmarks…");
///
/// html! {
///     (active_search("bookmark-search", "Search bookmarks", &config))
/// }
/// ```
#[must_use]
pub fn active_search(id: &str, label: &str, config: &ActiveSearchConfig<'_>) -> maud::Markup {
    debug_assert!(
        config.target.starts_with('#'),
        "active_search: config.target must be a #id selector (e.g. \"#my-results\"), got {:?}. \
         Use active_search_input + active_search_results directly for other selectors.",
        config.target
    );
    // Derive the results container ID from the configured target selector so the
    // rendered container always matches what the input's hx-target points at.
    let results_id = selector_to_id(config.target).to_string();
    let noscript_method = match config.method {
        SearchMethod::Get => "get",
        SearchMethod::Post => "post",
    };

    maud::html! {
        div id=(format!("{id}-wrapper")) {
            (active_search_input(id, label, config))
            (active_search_results(&results_id))
            noscript {
                form action=(config.action) method=(noscript_method) {
                    label for=(format!("{id}-noscript")) { (label) }
                    input
                        type="search"
                        id=(format!("{id}-noscript"))
                        name=(config.param_name)
                        placeholder=[config.placeholder];
                    button type="submit" { "Search" }
                }
            }
        }
    }
}

/// Render an active search empty-state partial.
///
/// Return this from your search handler when no results match the query.
/// The `role="status"` and `aria-live="polite"` attributes ensure screen
/// readers announce the empty state.
#[must_use]
pub fn active_search_empty_state(message: &str) -> maud::Markup {
    maud::html! {
        div
            role="status"
            aria-live="polite"
            class="autumn-search-empty" {
            (message)
        }
    }
}

/// Render an autocomplete input widget.
///
/// Emits:
/// - A visible `<input type="search" role="combobox">` for typing.
/// - A hidden `<input>` for storing the selected record's ID (single mode),
///   or a chip list (multiple mode).
/// - A `<div role="listbox">` where the server renders option partials.
/// - A `<noscript>` fallback `<select>`.
///
/// # Keyboard (with `autumn-widgets.js`)
///
/// The listbox binds the keyboard core (`data-autumn-activedescendant`,
/// `data-autumn-dismiss`). Focus stays on the input. `ArrowDown`/`ArrowUp` move
/// `aria-activedescendant` (wrapping) and open a closed popup. `Enter` selects
/// the active option. `Escape`, a click outside, or `Tab` closes the popup.
/// `aria-expanded` is `"true"` only while the popup shows an option.
///
/// Set [`AutocompleteConfig::initial_value`] to pre-fill both inputs — e.g.
/// re-rendering a form with this widget after a validation error, so text the
/// user already typed isn't silently dropped.
///
/// # Multiple (tags) mode
///
/// With [`AutocompleteConfig::multiple`], each pick is a chip with a remove
/// button. Each chip holds one hidden `{value_name}={value}` input, so a
/// `#[serde(default)] Vec<T>` field gets every value. The single hidden
/// input is not rendered. The `<noscript>` fallback is a `<select multiple>`.
/// The widget skips an empty value and a value that is already a chip.
///
/// The server renders the chip list `hidden` and the chip inputs
/// `disabled`. The runtime shows and enables them, and disables the
/// `<noscript>` select. Thus only one of them submits, and the form sends
/// each value one time.
///
/// Keys (with `autumn-widgets.js`): `Enter` adds the active option.
/// `Backspace` in an empty input removes the last chip. `ArrowLeft` at the
/// start of the input moves the focus to the last chip (`ArrowRight` in
/// RTL). In the chip list, the arrow keys, `Home` and `End` move the focus.
/// `Delete`, `Backspace`, `Enter` or `Space` removes the chip. `ArrowRight`
/// on the last chip moves the focus to the input. The chip list is one tab stop. A status
/// region tells a screen reader which chip was added or removed.
///
/// Use [`autocomplete_option`] and [`autocomplete_empty_state`] to render
/// option partials returned by your handler. Use
/// [`autocomplete_create_option`] for a "create new" entry.
///
/// # Example
///
/// ```rust,ignore
/// use autumn_web::widgets::{AutocompleteConfig, autocomplete_input};
///
/// let config = AutocompleteConfig::new("/tags/autocomplete", "tag_id")
///     .placeholder("Search tags…");
///
/// html! {
///     (autocomplete_input("tag-picker", "Tag", &config))
/// }
/// ```
#[must_use]
pub fn autocomplete_input(id: &str, label: &str, config: &AutocompleteConfig<'_>) -> maud::Markup {
    let value = config.initial_value;
    let seed = Seed {
        query: if config.multiple {
            ""
        } else {
            value.unwrap_or("")
        },
        value,
        chips: config.selected,
        errors: &[],
    };
    render_autocomplete(id, label, config, &seed)
}

/// Render an [`autocomplete_input`] that is pre-filled from `changeset`.
///
/// The field is [`AutocompleteConfig::value_name`]. The changeset is the
/// source of the values. Thus a user who removes every chip gets no chips
/// after a 422.
///
/// - In multiple mode, each
///   [`Changeset::field_values`](crate::form::Changeset::field_values)
///   entry is a chip.
/// - In single mode,
///   [`Changeset::field_value`](crate::form::Changeset::field_value) fills
///   the hidden input. The visible input shows its label.
///
/// The label of a value comes from [`AutocompleteConfig::selected`], then
/// from [`AutocompleteConfig::fallback_options`]. If no label is found, the
/// label is the value. This is correct for tags.
///
/// The field errors show below the input, as in the form helpers. The
/// input gets `aria-invalid` and `aria-describedby`.
///
/// # Example
///
/// ```rust,ignore
/// use autumn_web::widgets::{AutocompleteConfig, autocomplete_input_for};
///
/// // `PostForm { #[serde(default)] tags: Vec<String>, .. }`
/// let config = AutocompleteConfig::new("/tags/autocomplete", "tags")
///     .multiple()
///     .free_text();
/// html! { (autocomplete_input_for(&changeset, "tags", "Tags", &config)) }
/// ```
#[must_use]
pub fn autocomplete_input_for<T: serde::Serialize>(
    changeset: &crate::form::Changeset<T>,
    id: &str,
    label: &str,
    config: &AutocompleteConfig<'_>,
) -> maud::Markup {
    let errors = changeset.errors_for(config.value_name);
    if config.multiple {
        let values = changeset.field_values(config.value_name);
        let chips: Vec<(&str, &str)> = values
            .iter()
            .map(|value| (value.as_str(), label_of(config, value)))
            .collect();
        let seed = Seed {
            query: "",
            value: None,
            chips: &chips,
            errors,
        };
        return render_autocomplete(id, label, config, &seed);
    }
    let value = changeset.field_value(config.value_name);
    let seed = Seed {
        query: value.as_deref().map_or("", |v| label_of(config, v)),
        value: value.as_deref(),
        chips: &[],
        errors,
    };
    render_autocomplete(id, label, config, &seed)
}

/// The label of `value`: from `selected`, then `fallback_options`, else
/// the value.
fn label_of<'v>(config: &AutocompleteConfig<'v>, value: &'v str) -> &'v str {
    config
        .selected
        .iter()
        .chain(config.fallback_options.unwrap_or(&[]))
        .find(|(v, _)| *v == value)
        .map_or(value, |(_, label)| label)
}

/// The values that an autocomplete widget shows first.
struct Seed<'s> {
    /// Text of the visible query input.
    query: &'s str,
    /// Value of the single hidden input (single mode).
    value: Option<&'s str>,
    /// `(value, label)` chips (multiple mode).
    chips: &'s [(&'s str, &'s str)],
    /// Field errors from a changeset.
    errors: &'s [String],
}

/// `chips` with no empty value and no value two times. The first wins.
fn unique_chips<'c>(chips: &[(&'c str, &'c str)]) -> Vec<(&'c str, &'c str)> {
    let mut out: Vec<(&str, &str)> = Vec::with_capacity(chips.len());
    for &(value, label) in chips {
        if !value.is_empty() && !out.iter().any(|(v, _)| *v == value) {
            out.push((value, label));
        }
    }
    out
}

#[allow(
    clippy::too_many_lines,
    reason = "one maud template for both modes; the parts share ids"
)]
fn render_autocomplete(
    id: &str,
    label: &str,
    config: &AutocompleteConfig<'_>,
    seed: &Seed<'_>,
) -> maud::Markup {
    let query_id = format!("{id}-query");
    let options_id = format!("{id}-options");
    let error_id = format!("{id}-error");
    let multiple = config.multiple;
    let trigger = if multiple {
        build_tags_trigger(config.debounce_ms)
    } else {
        build_trigger(config.debounce_ms, false)
    };
    let target = format!("#{options_id}");
    let label_id = multiple.then(|| format!("{id}-label"));
    let value_id = (!multiple).then(|| format!("{id}-value"));
    let fallback = config.fallback_options.unwrap_or(&[]);
    let chips = unique_chips(seed.chips);
    let invalid = !seed.errors.is_empty();
    let class = if multiple {
        "autumn-autocomplete autumn-autocomplete--multiple"
    } else {
        "autumn-autocomplete"
    };

    // autumn-widgets.js reads these data-* attributes:
    //
    //  data-ac-value-id     — id of the single hidden input (single mode)
    //  data-ac-multiple     — tags mode: chips, one hidden input each
    //  data-ac-value-name   — form field name of the hidden input(s)
    //  data-ac-remove-label — aria-label of a remove button; `{label}` is the chip
    //  data-ac-added / data-ac-removed — status text; `{label}` is the chip
    //  data-ac-free-text    — typed text is a value (see free_text())
    //  data-ac-query        — marks the visible search input
    //  data-ac-min-length   — minimum characters before htmx fires a request
    //
    // With JS off, only the <noscript><select> submits. The single hidden
    // input has no name, and the chip inputs are disabled, until the
    // runtime runs. The runtime then disables the <select>: htmx parses a
    // swap with scripts off, so a swapped-in <noscript> is live markup.

    maud::html! {
        div
            id=(format!("{id}-wrapper"))
            class=(class)
            data-ac-value-id=[value_id.as_deref()]
            data-ac-multiple[multiple]
            data-ac-value-name=(config.value_name)
            data-ac-remove-label=[multiple.then_some(config.remove_label)]
            data-ac-added=[multiple.then_some(config.added_message)]
            data-ac-removed=[multiple.then_some(config.removed_message)]
            data-ac-free-text[config.free_text] {
            label id=[label_id.as_deref()] for=(query_id) class="autumn-autocomplete__label" { (label) }
            @if let Some(label_id) = &label_id {
                ul
                    id=(format!("{id}-chips"))
                    class="autumn-autocomplete__chips"
                    aria-labelledby=(label_id)
                    data-ac-chips
                    data-autumn-roving="[data-ac-chip-remove]"
                    data-autumn-orientation="horizontal"
                    data-autumn-wrap="false"
                    hidden {
                    @for (value, text) in &chips {
                        (chip(config, value, text, true))
                    }
                }
                template data-ac-chip-template { (chip(config, "", "", false)) }
                span class="autumn-visually-hidden" role="status" data-ac-status {}
            }
            input
                type="search"
                id=(query_id)
                name=(config.query_param)
                autocomplete="off"
                role="combobox"
                aria-expanded="false"
                aria-autocomplete="list"
                aria-controls=(options_id)
                aria-invalid=[invalid.then_some("true")]
                aria-describedby=[invalid.then_some(error_id.as_str())]
                value=(seed.query)
                placeholder=[config.placeholder]
                class="autumn-autocomplete__input"
                data-ac-query
                data-ac-min-length=(config.min_length)
                hx-get=(config.action)
                hx-trigger=(trigger)
                hx-target=(target)
                hx-indicator=[config.indicator];
            @if let Some(value_id) = &value_id {
                input type="hidden" id=(value_id) value=(seed.value.unwrap_or(""));
            }
            div
                id=(options_id)
                role="listbox"
                aria-label=(label)
                aria-live="polite"
                class="autumn-autocomplete__options"
                data-autumn-activedescendant
                data-autumn-orientation="vertical"
                data-autumn-dismiss {}
            @if invalid {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in seed.errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
            noscript {
                @if multiple {
                    select name=(config.value_name) aria-label=(label) multiple {
                        @for (val, lbl) in fallback {
                            option value=(val) selected[chips.iter().any(|(v, _)| v == val)] { (lbl) }
                        }
                        // A chip with no fallback option (a new tag) keeps its value.
                        @for (val, lbl) in &chips {
                            @if !fallback.iter().any(|(v, _)| v == val) {
                                option value=(val) selected { (lbl) }
                            }
                        }
                    }
                } @else {
                    select name=(config.value_name) aria-label=(label) {
                        option value="" { "— select —" }
                        @for (val, lbl) in fallback {
                            option value=(val) selected[seed.value == Some(*val)] { (lbl) }
                        }
                    }
                }
            }
        }
    }
}

/// The mark in a text template that the chip label replaces.
const LABEL_MARK: &str = concat!("{", "label", "}");

/// One chip: its label, its hidden input and its remove button.
///
/// A server chip's input is `disabled` until the runtime runs. A template
/// chip is a clone source, so its input is live. The runtime sets its
/// label and `aria-label`.
fn chip(config: &AutocompleteConfig<'_>, value: &str, label: &str, server: bool) -> maud::Markup {
    let remove = config.remove_label.replace(LABEL_MARK, label);
    maud::html! {
        li class="autumn-chip" data-ac-chip {
            span class="autumn-chip__label" data-ac-chip-label { (label) }
            input type="hidden" name=(config.value_name) value=(value) disabled[server];
            button
                type="button"
                class="autumn-chip__remove"
                tabindex="-1"
                aria-label=(remove.trim())
                data-ac-chip-remove {
                span aria-hidden="true" { "×" }
            }
        }
    }
}

/// Render a single autocomplete option partial returned by the server.
///
/// The `data-value` attribute carries the record ID (or the value to submit).
/// The `autumn-widgets.js` runtime handles clicks on the listbox and keys on
/// the input, and uses `data-value` to populate the hidden field. The option
/// has `tabindex="-1"`: focus stays on the input. The runtime gives the
/// active option an `id` if it has none.
///
/// # Example response fragment
///
/// ```rust,ignore
/// use autumn_web::widgets::autocomplete_option;
///
/// html! {
///     @for tag in &tags {
///         (autocomplete_option(&tag.id.to_string(), &tag.name))
///     }
/// }
/// ```
#[must_use]
pub fn autocomplete_option(value: &str, label: &str) -> maud::Markup {
    maud::html! {
        div
            role="option"
            tabindex="-1"
            class="autumn-autocomplete__option"
            data-value=(value) {
            (label)
        }
    }
}

/// Render a "create new" option partial for tags mode (issue #3410).
///
/// Return it from your handler, after the matches, when no record has the
/// typed text. `value` is the new value. `label` is the visible text, for
/// example `Create “zig”`. A pick adds a chip that shows `value`, not
/// `label`. Check the new value on the server, as for all input.
///
/// # Example response fragment
///
/// ```rust,ignore
/// use autumn_web::widgets::{autocomplete_create_option, autocomplete_option};
///
/// html! {
///     @for tag in &tags { (autocomplete_option(&tag.name, &tag.name)) }
///     @if !tags.iter().any(|t| t.name == q) {
///         (autocomplete_create_option(q, &format!("Create “{q}”")))
///     }
/// }
/// ```
#[must_use]
pub fn autocomplete_create_option(value: &str, label: &str) -> maud::Markup {
    maud::html! {
        div
            role="option"
            tabindex="-1"
            class="autumn-autocomplete__option autumn-autocomplete__option--create"
            data-value=(value)
            data-label=(value)
            data-ac-create {
            (label)
        }
    }
}

/// Render an autocomplete empty-state partial.
///
/// Return this from your autocomplete handler when no records match the query.
#[must_use]
pub fn autocomplete_empty_state(message: &str) -> maud::Markup {
    maud::html! {
        div
            role="status"
            aria-live="polite"
            class="autumn-autocomplete-empty" {
            (message)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widgets::{
        AlertConfig, AlertVariant, CardConfig, alert_with, card, nav_link, stat_card,
    };

    // ── build_trigger ──────────────────────────────────────────────────

    #[test]
    fn trigger_has_debounce() {
        let t = build_trigger(300, false);
        assert!(t.contains("delay:300ms"), "{t}");
    }

    #[test]
    fn trigger_has_changed_modifier() {
        let t = build_trigger(300, false);
        assert!(t.contains("changed"), "{t}");
    }

    #[test]
    fn trigger_has_no_filter_expressions() {
        // No [condition] filters are emitted — min_length is server-side only.
        // This ensures the trigger works under Autumn's default CSP (no unsafe-eval).
        let t = build_trigger(300, false);
        assert!(!t.contains("this.value.length"), "{t}");
        assert!(!t.contains('['), "{t}");
    }

    #[test]
    fn trigger_initial_load_appends_load() {
        let t = build_trigger(300, true);
        assert!(t.contains(", load"), "{t}");
    }

    #[test]
    fn trigger_no_initial_load_by_default() {
        let t = build_trigger(300, false);
        assert!(!t.contains("load"), "{t}");
    }

    #[test]
    fn trigger_custom_debounce() {
        let t = build_trigger(750, false);
        assert!(t.contains("delay:750ms"), "{t}");
    }

    // ── ActiveSearchConfig builder ─────────────────────────────────────

    #[test]
    fn config_defaults() {
        let c = ActiveSearchConfig::new("/s", "#r");
        assert_eq!(c.method, SearchMethod::Get);
        assert_eq!(c.debounce_ms, 300);
        assert_eq!(c.min_length, 1);
        assert_eq!(c.param_name, "q");
        assert!(!c.initial_load);
        assert!(c.indicator.is_none());
        assert!(c.placeholder.is_none());
    }

    #[test]
    fn config_post_builder() {
        assert_eq!(
            ActiveSearchConfig::new("/s", "#r").post().method,
            SearchMethod::Post
        );
    }

    #[test]
    fn config_debounce_builder() {
        assert_eq!(
            ActiveSearchConfig::new("/s", "#r")
                .debounce(500)
                .debounce_ms,
            500
        );
    }

    #[test]
    fn config_min_length_builder() {
        assert_eq!(
            ActiveSearchConfig::new("/s", "#r").min_length(3).min_length,
            3
        );
    }

    #[test]
    fn config_initial_load_builder() {
        assert!(
            ActiveSearchConfig::new("/s", "#r")
                .initial_load()
                .initial_load
        );
    }

    #[test]
    fn config_indicator_builder() {
        assert_eq!(
            ActiveSearchConfig::new("/s", "#r")
                .indicator("#spin")
                .indicator,
            Some("#spin")
        );
    }

    #[test]
    fn config_placeholder_builder() {
        assert_eq!(
            ActiveSearchConfig::new("/s", "#r")
                .placeholder("hint")
                .placeholder,
            Some("hint")
        );
    }

    #[test]
    fn config_param_name_builder() {
        assert_eq!(
            ActiveSearchConfig::new("/s", "#r")
                .param_name("query")
                .param_name,
            "query"
        );
    }

    // ── active_search_input ────────────────────────────────────────────

    #[test]
    fn input_defaults_to_hx_get() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains(r#"hx-get="/search""#), "{html}");
        assert!(!html.contains("hx-post"), "{html}");
    }

    #[test]
    fn input_uses_hx_post_when_configured() {
        let config = ActiveSearchConfig::new("/search", "#results").post();
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains(r#"hx-post="/search""#), "{html}");
        assert!(!html.contains("hx-get"), "{html}");
    }

    #[test]
    fn input_trigger_has_default_debounce() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains("delay:300ms"), "{html}");
    }

    #[test]
    fn input_configurable_debounce() {
        let config = ActiveSearchConfig::new("/search", "#results").debounce(500);
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains("delay:500ms"), "{html}");
    }

    #[test]
    fn input_configurable_min_length() {
        let config = ActiveSearchConfig::new("/search", "#results").min_length(3);
        let html = active_search_input("q", "Search", &config).into_string();
        // min_length is enforced server-side; no filter expression in the trigger
        assert!(html.contains("hx-trigger"), "{html}");
        assert!(!html.contains("this.value.length"), "{html}");
    }

    #[test]
    fn input_no_filter_when_min_length_zero() {
        let config = ActiveSearchConfig::new("/search", "#results").min_length(0);
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(!html.contains("this.value.length"), "{html}");
    }

    #[test]
    fn input_initial_load_in_trigger() {
        let config = ActiveSearchConfig::new("/search", "#results").initial_load();
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains(", load"), "{html}");
    }

    #[test]
    fn input_no_initial_load_by_default() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(!html.contains(", load"), "{html}");
    }

    #[test]
    fn input_target_selector() {
        let config = ActiveSearchConfig::new("/search", "#my-results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains("hx-target=\"#my-results\""), "{html}");
    }

    #[test]
    fn input_indicator_when_configured() {
        let config = ActiveSearchConfig::new("/search", "#results").indicator("#spinner");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains("hx-indicator=\"#spinner\""), "{html}");
    }

    #[test]
    fn input_no_indicator_by_default() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(!html.contains("hx-indicator"), "{html}");
    }

    #[test]
    fn input_renders_label() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("q", "Search Posts", &config).into_string();
        assert!(html.contains("Search Posts"), "{html}");
        assert!(html.contains("<label"), "{html}");
    }

    #[test]
    fn input_label_for_matches_id() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("my-search", "Search", &config).into_string();
        assert!(html.contains(r#"for="my-search""#), "{html}");
        assert!(html.contains(r#"id="my-search""#), "{html}");
    }

    #[test]
    fn input_has_aria_controls() {
        let config = ActiveSearchConfig::new("/search", "#my-results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains("aria-controls"), "{html}");
        assert!(html.contains("my-results"), "{html}");
    }

    #[test]
    fn input_type_is_search() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains(r#"type="search""#), "{html}");
    }

    #[test]
    fn input_placeholder_when_configured() {
        let config = ActiveSearchConfig::new("/search", "#results").placeholder("Type to search…");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains("Type to search"), "{html}");
    }

    #[test]
    fn input_no_placeholder_by_default() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(!html.contains("placeholder"), "{html}");
    }

    #[test]
    fn input_custom_param_name() {
        let config = ActiveSearchConfig::new("/search", "#results").param_name("query");
        let html = active_search_input("q", "Search", &config).into_string();
        assert!(html.contains(r#"name="query""#), "{html}");
    }

    // ── active_search_results ──────────────────────────────────────────

    #[test]
    fn results_correct_id() {
        let html = active_search_results("my-results").into_string();
        assert!(html.contains(r#"id="my-results""#), "{html}");
    }

    #[test]
    fn results_role_status() {
        let html = active_search_results("r").into_string();
        assert!(html.contains(r#"role="status""#), "{html}");
    }

    #[test]
    fn results_aria_live_polite() {
        let html = active_search_results("r").into_string();
        assert!(html.contains(r#"aria-live="polite""#), "{html}");
    }

    #[test]
    fn results_aria_atomic() {
        let html = active_search_results("r").into_string();
        assert!(html.contains(r#"aria-atomic="true""#), "{html}");
    }

    // ── active_search (full widget) ────────────────────────────────────

    #[test]
    fn widget_includes_input_and_results() {
        let config = ActiveSearchConfig::new("/search", "#s-results");
        let html = active_search("s", "Search", &config).into_string();
        assert!(html.contains(r#"type="search""#), "{html}");
        assert!(html.contains(r#"id="s-results""#), "{html}");
    }

    #[test]
    fn widget_results_id_matches_target_selector() {
        // Callers pass any target; the generated container must match.
        let config = ActiveSearchConfig::new("/search", "#custom-results");
        let html = active_search("search-widget", "Search", &config).into_string();
        assert!(html.contains(r#"id="custom-results""#), "{html}");
    }

    #[test]
    fn widget_has_noscript_fallback() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search("s", "Search", &config).into_string();
        assert!(html.contains("<noscript>"), "{html}");
        assert!(html.contains("<form"), "{html}");
        assert!(html.contains(r#"type="submit""#), "{html}");
    }

    #[test]
    fn widget_noscript_get_by_default() {
        let config = ActiveSearchConfig::new("/search", "#results");
        let html = active_search("s", "Search", &config).into_string();
        assert!(html.contains(r#"method="get""#), "{html}");
    }

    #[test]
    fn widget_noscript_post_when_configured() {
        let config = ActiveSearchConfig::new("/search", "#results").post();
        let html = active_search("s", "Search", &config).into_string();
        assert!(html.contains(r#"method="post""#), "{html}");
    }

    // ── autocomplete_input ─────────────────────────────────────────────

    #[test]
    fn autocomplete_visible_search_input() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"type="search""#), "{html}");
        // visible input uses query_param (default "q") so htmx sends ?q=...
        assert!(html.contains(r#"name="q""#), "{html}");
    }

    #[test]
    fn autocomplete_visible_input_uses_query_param() {
        let config = AutocompleteConfig::new("/ac", "value_field").query_param("search");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"name="search""#), "{html}");
    }

    #[test]
    fn autocomplete_hidden_value_field() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"type="hidden""#), "{html}");
        // The hidden input has no name in HTML; name is set by JS on first interaction
        // so no-JS forms don't see a duplicate field alongside the noscript <select>.
        assert!(html.contains(r#"id="x-value""#), "{html}");
    }

    #[test]
    fn autocomplete_hidden_field_empty_initial_value() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"type="hidden""#), "{html}");
        assert!(html.contains(r#"value="""#), "{html}");
    }

    #[test]
    fn autocomplete_listbox_container() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"role="listbox""#), "{html}");
    }

    #[test]
    fn autocomplete_wrapper_has_data_attributes_for_runtime() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        // The external autumn-widgets.js reads these to wire up interactions.
        assert!(html.contains(r#"data-ac-value-id="x-value""#), "{html}");
        assert!(
            html.contains(r#"data-ac-value-name="value_field""#),
            "{html}"
        );
        assert!(html.contains("data-ac-query"), "{html}");
        assert!(html.contains("data-ac-min-length"), "{html}");
    }

    #[test]
    fn autocomplete_free_text_mode_sets_data_attribute() {
        let config = AutocompleteConfig::new("/ac", "value_field").free_text();
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("data-ac-free-text"), "{html}");
    }

    #[test]
    fn autocomplete_id_mode_no_free_text_attribute() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(!html.contains("data-ac-free-text"), "{html}");
    }

    #[test]
    fn autocomplete_combobox_role() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"role="combobox""#), "{html}");
    }

    #[test]
    fn autocomplete_aria_expanded_false() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"aria-expanded="false""#), "{html}");
    }

    #[test]
    fn autocomplete_aria_autocomplete_list() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"aria-autocomplete="list""#), "{html}");
    }

    #[test]
    fn autocomplete_has_aria_controls() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("aria-controls"), "{html}");
    }

    #[test]
    fn autocomplete_renders_label() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "My Label", &config).into_string();
        assert!(html.contains("My Label"), "{html}");
        assert!(html.contains("<label"), "{html}");
    }

    #[test]
    fn autocomplete_label_for_matches_query_input_id() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("tag", "Tag", &config).into_string();
        assert!(html.contains(r#"for="tag-query""#), "{html}");
        assert!(html.contains(r#"id="tag-query""#), "{html}");
    }

    #[test]
    fn autocomplete_has_noscript_fallback() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("<noscript>"), "{html}");
        assert!(html.contains("<select"), "{html}");
    }

    #[test]
    fn autocomplete_noscript_select_uses_value_name() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"name="value_field""#), "{html}");
    }

    #[test]
    fn autocomplete_fallback_options_rendered_in_noscript() {
        let opts: &[(&str, &str)] = &[("1", "Alpha"), ("2", "Beta")];
        let config = AutocompleteConfig::new("/ac", "value_field").fallback_options(opts);
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("Alpha"), "{html}");
        assert!(html.contains("Beta"), "{html}");
        assert!(html.contains(r#"value="1""#), "{html}");
        assert!(html.contains(r#"value="2""#), "{html}");
    }

    #[test]
    fn autocomplete_noscript_select_marks_initial_value_selected() {
        // ID-mode (default, non-free-text): a prior selection seeded via
        // `initial_value` must survive a no-JS resubmission too, not just the
        // JS-driven hidden-input path.
        let opts: &[(&str, &str)] = &[("1", "Alpha"), ("2", "Beta")];
        let config = AutocompleteConfig::new("/ac", "value_field")
            .fallback_options(opts)
            .initial_value("2");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(
            html.contains(r#"value="2" selected"#),
            "the option matching initial_value must be marked selected: {html}"
        );
        assert!(
            !html.contains(r#"value="1" selected"#),
            "only the matching option should be selected: {html}"
        );
    }

    #[test]
    fn autocomplete_has_hx_get() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains(r#"hx-get="/ac""#), "{html}");
    }

    #[test]
    fn autocomplete_hx_trigger_has_debounce() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("hx-trigger"), "{html}");
        assert!(html.contains("delay:300ms"), "{html}");
    }

    #[test]
    fn autocomplete_configurable_debounce() {
        let config = AutocompleteConfig::new("/ac", "value_field").debounce(600);
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("delay:600ms"), "{html}");
    }

    #[test]
    fn autocomplete_configurable_min_length() {
        let config = AutocompleteConfig::new("/ac", "value_field").min_length(2);
        let html = autocomplete_input("x", "Label", &config).into_string();
        // min_length is carried as a data attribute for the autumn-widgets.js runtime
        // to enforce client-side (via htmx:configRequest) and server-side.
        assert!(html.contains(r#"data-ac-min-length="2""#), "{html}");
        assert!(!html.contains("this.value.length"), "{html}");
    }

    #[test]
    fn autocomplete_indicator_when_configured() {
        let config = AutocompleteConfig::new("/ac", "value_field").indicator("#ld");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("hx-indicator=\"#ld\""), "{html}");
    }

    #[test]
    fn autocomplete_no_indicator_by_default() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(!html.contains("hx-indicator"), "{html}");
    }

    #[test]
    fn autocomplete_listbox_has_aria_live() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(html.contains("aria-live"), "{html}");
    }

    #[test]
    fn autocomplete_listbox_has_no_inline_handlers() {
        // All interaction is wired by autumn-widgets.js, not inline hx-on:* attributes.
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        assert!(!html.contains("hx-on:keydown"), "{html}");
        assert!(!html.contains("hx-on:click"), "{html}");
        assert!(!html.contains("hx-on:input"), "{html}");
        assert!(!html.contains("oninput"), "{html}");
    }

    // ── autocomplete_option ────────────────────────────────────────────

    #[test]
    fn option_renders_label_and_value() {
        let html = autocomplete_option("42", "My Tag").into_string();
        assert!(html.contains("My Tag"), "{html}");
        assert!(html.contains(r#"data-value="42""#), "{html}");
    }

    #[test]
    fn option_has_role_option() {
        let html = autocomplete_option("1", "Option").into_string();
        assert!(html.contains(r#"role="option""#), "{html}");
    }

    #[test]
    fn option_is_keyboard_focusable() {
        let html = autocomplete_option("1", "Option").into_string();
        assert!(html.contains("tabindex"), "{html}");
    }

    #[test]
    fn option_is_not_a_tab_stop() {
        // APG combobox: focus stays on the input. Options are not tab stops.
        let html = autocomplete_option("1", "Option").into_string();
        assert!(html.contains(r#"tabindex="-1""#), "{html}");
    }

    #[test]
    fn autocomplete_listbox_binds_keyboard_core() {
        let config = AutocompleteConfig::new("/ac", "value_field");
        let html = autocomplete_input("x", "Label", &config).into_string();
        let listbox = html
            .split(r#"id="x-options""#)
            .nth(1)
            .and_then(|rest| rest.split('>').next())
            .expect("listbox tag");
        assert!(listbox.contains("data-autumn-activedescendant"), "{html}");
        assert!(listbox.contains("data-autumn-dismiss"), "{html}");
        // The core finds the controller through `aria-controls`.
        assert!(html.contains(r#"aria-controls="x-options""#), "{html}");
    }

    // ── multiple mode (#3410) ──────────────────────────────────────────

    /// The markup of the first element that has `marker`, up to its `>`.
    fn tag_with<'h>(html: &'h str, marker: &str) -> &'h str {
        let at = html
            .find(marker)
            .unwrap_or_else(|| panic!("no {marker}: {html}"));
        let start = html[..=at].rfind('<').expect("tag start");
        let end = at + html[at..].find('>').expect("tag end");
        &html[start..=end]
    }

    /// The `<li>` chips of the chip list. The `<template>` is not a chip.
    fn chips(html: &str) -> Vec<&str> {
        let list = html
            .split("data-ac-chips")
            .nth(1)
            .and_then(|rest| rest.split("</ul>").next())
            .expect("chip list");
        list.split("<li").skip(1).collect()
    }

    const PICKED: &[(&str, &str)] = &[("42", "rust"), ("7", "web")];

    #[test]
    fn multiple_defaults_off() {
        let c = AutocompleteConfig::new("/ac", "tags");
        assert!(!c.multiple);
        assert!(c.selected.is_empty());
        assert_eq!(c.remove_label, "Remove {label}");
        assert_eq!(c.added_message, "{label} added");
        assert_eq!(c.removed_message, "{label} removed");
    }

    #[test]
    fn single_mode_has_no_chip_markup() {
        let config = AutocompleteConfig::new("/ac", "tag_id");
        let html = autocomplete_input("x", "Tag", &config).into_string();
        assert!(!html.contains("data-ac-multiple"), "{html}");
        assert!(!html.contains("data-ac-chips"), "{html}");
        assert!(!html.contains("<template"), "{html}");
        assert!(!html.contains("multiple"), "{html}");
        // Single-mode markup is unchanged: no label id, no status region.
        assert!(html.contains(r#"<label for="x-query""#), "{html}");
        assert!(!html.contains("data-ac-status"), "{html}");
        assert!(html.contains("input changed delay:"), "{html}");
    }

    #[test]
    fn multiple_wrapper_has_runtime_data_attributes() {
        let config = AutocompleteConfig::new("/ac", "tags").multiple();
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let wrapper = tag_with(&html, r#"id="x-wrapper""#);
        assert!(wrapper.contains("data-ac-multiple"), "{wrapper}");
        assert!(
            wrapper.contains(r#"data-ac-value-name="tags""#),
            "{wrapper}"
        );
        assert!(
            wrapper.contains(r#"data-ac-remove-label="Remove {label}""#),
            "{wrapper}"
        );
        assert!(
            wrapper.contains(r#"data-ac-added="{label} added""#),
            "{wrapper}"
        );
        assert!(
            wrapper.contains(r#"data-ac-removed="{label} removed""#),
            "{wrapper}"
        );
        // The single-value hidden field is not rendered.
        assert!(!wrapper.contains("data-ac-value-id"), "{wrapper}");
        assert!(!html.contains(r#"id="x-value""#), "{html}");
    }

    #[test]
    fn multiple_chip_list_is_a_roving_list_named_by_the_label() {
        let config = AutocompleteConfig::new("/ac", "tags").multiple();
        let html = autocomplete_input("x", "Tags", &config).into_string();
        assert!(
            html.contains(r#"<label id="x-label" for="x-query""#),
            "{html}"
        );
        let list = tag_with(&html, "data-ac-chips");
        assert!(list.starts_with("<ul"), "{list}");
        assert!(list.contains(r#"id="x-chips""#), "{list}");
        assert!(list.contains(r#"aria-labelledby="x-label""#), "{list}");
        assert!(
            list.contains(r#"data-autumn-roving="[data-ac-chip-remove]""#),
            "{list}"
        );
        assert!(
            list.contains(r#"data-autumn-orientation="horizontal""#),
            "{list}"
        );
        assert!(list.contains(r#"data-autumn-wrap="false""#), "{list}");
        // Hidden until the runtime runs: with JS off, the select is the control.
        assert!(list.contains(" hidden"), "{list}");
    }

    #[test]
    fn multiple_renders_a_chip_for_each_selected_pair() {
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .selected(PICKED);
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let chips = chips(&html);
        assert_eq!(chips.len(), 2, "{html}");
        assert!(chips[0].contains(">rust<"), "{}", chips[0]);
        assert!(chips[1].contains(">web<"), "{}", chips[1]);
        assert!(chips[0].contains("data-ac-chip"), "{}", chips[0]);
        assert!(chips[0].contains(r#"class="autumn-chip""#), "{}", chips[0]);
    }

    #[test]
    fn each_chip_has_one_named_hidden_input_disabled_until_the_runtime_runs() {
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .selected(PICKED);
        let html = autocomplete_input("x", "Tags", &config).into_string();
        for (chip, value) in chips(&html).iter().zip(["42", "7"]) {
            let input = tag_with(chip, r#"type="hidden""#);
            assert!(input.contains(r#"name="tags""#), "{input}");
            assert!(input.contains(&format!(r#"value="{value}""#)), "{input}");
            // With JS off, only the <noscript> select submits.
            assert!(input.contains("disabled"), "{input}");
            assert_eq!(chip.matches(r#"type="hidden""#).count(), 1, "{chip}");
        }
    }

    #[test]
    fn each_chip_has_a_labelled_remove_button() {
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .selected(PICKED)
            .remove_label("{label} löschen");
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let chip = chips(&html)[0];
        let button = tag_with(chip, "data-ac-chip-remove");
        assert!(button.starts_with("<button"), "{button}");
        assert!(button.contains(r#"type="button""#), "{button}");
        // The template puts the label where the language needs it.
        assert!(button.contains(r#"aria-label="rust löschen""#), "{button}");
        assert!(button.contains(r#"tabindex="-1""#), "{button}");
        assert!(chip.contains(r#"aria-hidden="true""#), "{chip}");
    }

    #[test]
    fn chip_labels_and_values_are_escaped() {
        let pairs: &[(&str, &str)] = &[(r#"a"b"#, "<script>x</script>")];
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .selected(pairs);
        let html = autocomplete_input("x", "Tags", &config).into_string();
        assert!(!html.contains("<script>"), "{html}");
        assert!(html.contains("&lt;script&gt;x&lt;/script&gt;"), "{html}");
        assert!(html.contains(r#"value="a&quot;b""#), "{html}");
    }

    #[test]
    fn multiple_has_an_empty_chip_template_for_the_runtime() {
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .selected(PICKED);
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let template = html
            .split("<template data-ac-chip-template>")
            .nth(1)
            .and_then(|rest| rest.split("</template>").next())
            .expect("chip template");
        assert!(template.contains("data-ac-chip"), "{template}");
        assert!(template.contains("data-ac-chip-label"), "{template}");
        assert!(template.contains(r#"name="tags""#), "{template}");
        assert!(template.contains("data-ac-chip-remove"), "{template}");
        assert!(!template.contains("rust"), "{template}");
        // A clone is live at once, so the template input is not disabled.
        assert!(!template.contains("disabled"), "{template}");
    }

    #[test]
    fn multiple_noscript_is_a_select_multiple_with_the_selection() {
        let opts: &[(&str, &str)] = &[("42", "rust"), ("7", "web"), ("13", "axum")];
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .fallback_options(opts)
            .selected(&[("13", "axum"), ("42", "rust")]);
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let noscript = html
            .split("<noscript>")
            .nth(1)
            .and_then(|rest| rest.split("</noscript>").next())
            .expect("noscript");
        let select = tag_with(noscript, "<select");
        assert!(select.contains(r#"name="tags""#), "{select}");
        assert!(select.contains("multiple"), "{select}");
        assert!(noscript.contains(r#"value="42" selected"#), "{noscript}");
        assert!(noscript.contains(r#"value="13" selected"#), "{noscript}");
        assert!(!noscript.contains(r#"value="7" selected"#), "{noscript}");
        // No "— select —" placeholder: an empty multi-select posts nothing.
        assert!(!noscript.contains(r#"value="""#), "{noscript}");
    }

    #[test]
    fn multiple_noscript_keeps_a_selected_value_with_no_fallback_option() {
        // A created tag is not in `fallback_options`. A no-JS resubmit
        // must keep it.
        let opts: &[(&str, &str)] = &[("rust", "rust")];
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .fallback_options(opts)
            .selected(&[("brand-new", "brand-new")]);
        let html = autocomplete_input("x", "Tags", &config).into_string();
        assert!(
            html.contains(r#"<option value="brand-new" selected>brand-new</option>"#),
            "{html}"
        );
        assert!(!html.contains(r#"value="rust" selected"#), "{html}");
    }

    #[test]
    fn multiple_free_text_sets_its_data_attribute() {
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .free_text();
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let wrapper = tag_with(&html, r#"id="x-wrapper""#);
        assert!(wrapper.contains("data-ac-free-text"), "{wrapper}");
    }

    #[test]
    fn multiple_query_input_is_still_an_apg_combobox() {
        let config = AutocompleteConfig::new("/ac", "tags").multiple();
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let input = tag_with(&html, r#"id="x-query""#);
        assert!(input.contains(r#"role="combobox""#), "{input}");
        assert!(input.contains(r#"aria-controls="x-options""#), "{input}");
        assert!(input.contains(r#"value="""#), "{input}");
        assert!(html.contains(r##"hx-target="#x-options""##), "{html}");
        // The runtime clears the input with no `input` event after a pick.
        // With `changed`, the same query again would send no request.
        assert!(
            input.contains(r#"hx-trigger="input delay:300ms""#),
            "{input}"
        );
    }

    #[test]
    fn multiple_has_a_status_region_for_added_and_removed_chips() {
        let config = AutocompleteConfig::new("/ac", "tags").multiple();
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let status = tag_with(&html, "data-ac-status");
        assert!(status.contains(r#"role="status""#), "{status}");
        assert!(status.contains("autumn-visually-hidden"), "{status}");
    }

    #[test]
    fn multiple_skips_empty_and_duplicate_values() {
        let pairs: &[(&str, &str)] = &[("rust", "rust"), ("", "blank"), ("rust", "again")];
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .selected(pairs);
        let html = autocomplete_input("x", "Tags", &config).into_string();
        let chips = chips(&html);
        assert_eq!(chips.len(), 1, "{html}");
        assert!(chips[0].contains(">rust<"), "{}", chips[0]);
        assert_eq!(
            html.matches(r#"<option value="rust" selected>"#).count(),
            1,
            "{html}"
        );
        assert!(!html.contains("blank"), "{html}");
    }

    // ── autocomplete_input_for (#3410) ─────────────────────────────────

    #[derive(serde::Serialize)]
    struct Post {
        tags: Vec<String>,
        tag_ids: Vec<i64>,
        category_id: Option<i64>,
    }

    fn post() -> crate::form::Changeset<Post> {
        crate::form::Changeset::new(Post {
            tags: vec!["rust".to_owned(), "new-tag".to_owned()],
            tag_ids: vec![13, 42],
            category_id: Some(7),
        })
    }

    #[test]
    fn input_for_prefills_chips_from_a_sequence_field() {
        let config = AutocompleteConfig::new("/ac", "tags").multiple();
        let html = autocomplete_input_for(&post(), "x", "Tags", &config).into_string();
        let chips = chips(&html);
        assert_eq!(chips.len(), 2, "{html}");
        // No fallback label: the value is the label (tags mode).
        assert!(chips[0].contains(">rust<"), "{}", chips[0]);
        assert!(chips[0].contains(r#"value="rust""#), "{}", chips[0]);
        assert!(chips[1].contains(">new-tag<"), "{}", chips[1]);
    }

    #[test]
    fn input_for_finds_chip_labels_in_the_fallback_options() {
        let opts: &[(&str, &str)] = &[("42", "rust"), ("13", "axum")];
        let config = AutocompleteConfig::new("/ac", "tag_ids")
            .multiple()
            .fallback_options(opts);
        let html = autocomplete_input_for(&post(), "x", "Tags", &config).into_string();
        let chips = chips(&html);
        assert_eq!(chips.len(), 2, "{html}");
        assert!(chips[0].contains(">axum<"), "{}", chips[0]);
        assert!(chips[0].contains(r#"value="13""#), "{}", chips[0]);
        assert!(chips[1].contains(">rust<"), "{}", chips[1]);
        assert!(html.contains(r#"value="42" selected"#), "{html}");
    }

    #[test]
    fn input_for_finds_chip_labels_in_the_selected_pairs() {
        let config = AutocompleteConfig::new("/ac", "tag_ids")
            .multiple()
            .selected(&[("42", "rust")]);
        let html = autocomplete_input_for(&post(), "x", "Tags", &config).into_string();
        let chips = chips(&html);
        // The changeset is the source of truth: 13 and 42, not only 42.
        assert_eq!(chips.len(), 2, "{html}");
        assert!(chips[0].contains(">13<"), "{}", chips[0]);
        assert!(chips[1].contains(">rust<"), "{}", chips[1]);
    }

    #[test]
    fn input_for_an_empty_vec_ignores_the_selected_pairs() {
        // The user removed every chip, then the form came back with a 422.
        // The old chips must not come back.
        let empty = crate::form::Changeset::new(Post {
            tags: Vec::new(),
            tag_ids: Vec::new(),
            category_id: None,
        });
        let config = AutocompleteConfig::new("/ac", "tags")
            .multiple()
            .selected(&[("rust", "rust")]);
        let html = autocomplete_input_for(&empty, "x", "Tags", &config).into_string();
        assert!(chips(&html).is_empty(), "{html}");
    }

    #[test]
    fn input_for_shows_the_field_errors() {
        let mut errors = std::collections::HashMap::new();
        errors.insert("tags".to_owned(), vec!["Add a tag.".to_owned()]);
        let changeset = crate::form::Changeset::from_errors(
            Post {
                tags: Vec::new(),
                tag_ids: Vec::new(),
                category_id: None,
            },
            errors,
        );
        let config = AutocompleteConfig::new("/ac", "tags").multiple();
        let html = autocomplete_input_for(&changeset, "x", "Tags", &config).into_string();
        let input = tag_with(&html, r#"id="x-query""#);
        assert!(input.contains(r#"aria-invalid="true""#), "{input}");
        assert!(input.contains(r#"aria-describedby="x-error""#), "{input}");
        let alert = tag_with(&html, r#"id="x-error""#);
        assert!(alert.contains(r#"role="alert""#), "{alert}");
        assert!(
            html.contains(r#"<p class="autumn-field__error">Add a tag.</p>"#),
            "{html}"
        );
    }

    #[test]
    fn input_for_a_valid_field_has_no_error_markup() {
        let config = AutocompleteConfig::new("/ac", "tags").multiple();
        let html = autocomplete_input_for(&post(), "x", "Tags", &config).into_string();
        assert!(!html.contains("aria-invalid"), "{html}");
        assert!(!html.contains("x-error"), "{html}");
    }

    #[test]
    fn input_for_single_mode_with_no_value_is_blank() {
        let config = AutocompleteConfig::new("/ac", "missing").initial_value("old");
        let html = autocomplete_input_for(&post(), "x", "Category", &config).into_string();
        let hidden = tag_with(&html, r#"type="hidden" id="x-value""#);
        assert!(hidden.contains(r#"value="""#), "{hidden}");
    }

    #[test]
    fn input_for_an_empty_field_renders_no_chips() {
        let config = AutocompleteConfig::new("/ac", "missing").multiple();
        let html = autocomplete_input_for(&post(), "x", "Tags", &config).into_string();
        assert!(chips(&html).is_empty(), "{html}");
    }

    #[test]
    fn input_for_single_mode_prefills_the_value_and_its_label() {
        let opts: &[(&str, &str)] = &[("7", "News"), ("8", "Blog")];
        let config = AutocompleteConfig::new("/ac", "category_id").fallback_options(opts);
        let html = autocomplete_input_for(&post(), "x", "Category", &config).into_string();
        let hidden = tag_with(&html, r#"type="hidden" id="x-value""#);
        assert!(hidden.contains(r#"value="7""#), "{hidden}");
        let query = tag_with(&html, r#"id="x-query""#);
        assert!(query.contains(r#"value="News""#), "{query}");
        assert!(html.contains(r#"value="7" selected"#), "{html}");
    }

    // ── autocomplete_create_option (#3410) ─────────────────────────────

    #[test]
    fn create_option_is_an_option_with_the_new_value_as_its_label() {
        let html = autocomplete_create_option("go", "Create “go”").into_string();
        assert!(html.contains(r#"role="option""#), "{html}");
        assert!(html.contains(r#"tabindex="-1""#), "{html}");
        assert!(html.contains(r#"data-value="go""#), "{html}");
        assert!(html.contains(r#"data-label="go""#), "{html}");
        assert!(html.contains("data-ac-create"), "{html}");
        assert!(
            html.contains("autumn-autocomplete__option--create"),
            "{html}"
        );
        assert!(html.contains("Create “go”"), "{html}");
    }

    #[test]
    fn create_option_escapes_its_value() {
        let html = autocomplete_create_option(r#""><b>"#, "x").into_string();
        assert!(!html.contains("<b>"), "{html}");
    }

    // ── autocomplete_empty_state ───────────────────────────────────────

    #[test]
    fn ac_empty_state_renders_message() {
        let html = autocomplete_empty_state("No results found").into_string();
        assert!(html.contains("No results found"), "{html}");
    }

    #[test]
    fn ac_empty_state_announced_to_screen_readers() {
        let html = autocomplete_empty_state("No results").into_string();
        assert!(
            html.contains(r#"role="status""#) || html.contains("aria-live"),
            "{html}"
        );
    }

    // ── active_search_empty_state ──────────────────────────────────────

    #[test]
    fn search_empty_state_renders_message() {
        let html = active_search_empty_state("No matching posts").into_string();
        assert!(html.contains("No matching posts"), "{html}");
    }

    #[test]
    fn search_empty_state_announced_to_screen_readers() {
        let html = active_search_empty_state("Nothing found").into_string();
        assert!(
            html.contains(r#"role="status""#) || html.contains("aria-live"),
            "{html}"
        );
    }

    // ── widget class namespace (#2354) ──────────────────────────────────

    /// Every semantic class the renamed widgets emit must live in the
    /// `autumn-*` namespace, and the old unprefixed hooks must be gone:
    /// the standalone widget stylesheet only styles namespaced classes.
    #[test]
    fn renamed_widgets_emit_namespaced_classes_only() {
        let body = maud::html! { p { "hello" } };
        let html = card(
            &body,
            &CardConfig::new()
                .title("Posts")
                .header_action(maud::html! { a href="/new" { "New" } })
                .footer(maud::html! { span { "Save" } }),
        )
        .into_string();
        for class in [
            "autumn-card",
            "autumn-card__header",
            "autumn-card__title",
            "autumn-card__body",
            "autumn-card__footer",
        ] {
            assert!(html.contains(class), "missing {class}: {html}");
        }
        for stale in [
            r#"class="card""#,
            "card-header",
            "card-title",
            "card-body",
            "card-footer",
        ] {
            assert!(
                !html.contains(stale),
                "stale unprefixed hook {stale}: {html}"
            );
        }

        let html = stat_card("Users", "42", Some(("/users", "View all"))).into_string();
        for class in [
            "autumn-stat-card",
            "autumn-stat-card__label",
            "autumn-stat-card__value",
            "autumn-stat-card__link",
        ] {
            assert!(html.contains(class), "missing {class}: {html}");
        }
        for stale in [
            r#"class="stat-card""#,
            "stat-label",
            "stat-value",
            "stat-link",
        ] {
            assert!(
                !html.contains(stale),
                "stale unprefixed hook {stale}: {html}"
            );
        }

        let html = nav_link("/posts", "/posts", "Posts").into_string();
        assert!(html.contains(r#"class="autumn-active""#), "{html}");
        assert!(!html.contains(r#"class="active""#), "{html}");

        let html = active_search_empty_state("No results").into_string();
        assert!(html.contains(r#"class="autumn-search-empty""#), "{html}");
        assert!(!html.contains(r#"class="search-empty""#), "{html}");

        let html = autocomplete_empty_state("No matches").into_string();
        assert!(
            html.contains(r#"class="autumn-autocomplete-empty""#),
            "{html}"
        );
        assert!(!html.contains(r#"class="autocomplete-empty""#), "{html}");

        let html = alert_with(
            AlertVariant::Info,
            maud::html! { "hi" },
            &AlertConfig::new().icon(true),
        )
        .into_string();
        assert!(html.contains(r#"class="autumn-alert__icon-svg""#), "{html}");
        assert!(!html.contains(r#"class="alert__icon-svg""#), "{html}");
        // #3396: the glyph color comes from CSS (`--surface`), so it stays
        // visible on the light dark-scheme circle.
        assert!(
            html.contains(r#"class="autumn-alert__icon-glyph""#),
            "{html}"
        );
    }
}