frust-native-widgets 0.5.2

Real native controls (Android Views, UIKit, AppKit) for Frust apps, written from pure Rust and hosted as platform views.
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
//! `DatePicker` — a real DATE-mode picker (no time), built and driven from
//! Rust: `android.widget.DatePicker` on Android, `UIDatePicker` (mode
//! `Date`) on iOS/iPadOS, `NSDatePicker` (elements `YearMonthDay`) on macOS.
//! A **shared** control: it sits in [`super::SHARED_KINDS`] and all three
//! arms register it.
//!
//! Date clamping is centralized in [`DatePickerProps::effective_date`], which
//! computes the app's date clamped into the arm's resolved range; both
//! `create` and `plan` use this single clamp implementation.
//!
//! Eight properties: the date, its optional `[min, max]` range, the
//! presentation style, enabled, a tint, a text colour, and the accessibility
//! label. [`Setter::Date`], [`Setter::Enabled`], [`Setter::DatePickerTint`],
//! [`Setter::DatePickerTextColor`] and [`Setter::ContentDescription`] are
//! [`Tier::Cheap`](super::Tier::Cheap); [`Setter::MinDate`],
//! [`Setter::MaxDate`] and [`Setter::DatePickerStyle`] are
//! [`Tier::Relayout`](super::Tier::Relayout) (a range change repopulates a
//! calendar's pages/year list; a style swap rebuilds the whole presentation).
//!
//! # `CivilDate`: a calendar date, validated at every boundary
//!
//! [`CivilDate`] is a proleptic-Gregorian year/month/day with no time and no
//! time zone — the value the app owns and the value every arm reports. Its
//! fields are crate-private behind [`CivilDate::new`], so an out-of-crate
//! caller can never hold an unvalidated one; it is additionally validated
//! wherever it crosses a boundary inside this crate: the params wire
//! ([`DatePickerProps::decode`] — an invalid date decodes as absent), the
//! event wire (`crate::events::unpack_date`), and the Apple arms'
//! `NSDate` conversion ([`foundation`]). Each date rides the params wire as
//! ONE integer — the exact `crate::events::pack_date` value the event wire
//! carries — so there is one codec for both directions, not two.
//!
//! # The controlled-component contract — `Switch`'s, date-valued
//!
//! Controlled exactly like `Switch`/`Slider` (`switch.rs`'s module doc is the
//! reference account): the platform reports the *requested* date through
//! [`crate::events::EVENT_KIND_DATE`], the app confirms it by feeding it back
//! as `date`.
//!
//! 1. **Write-back.** [`DatePickerProps::plan`] takes the date the platform
//!    last reported (`observed`) and re-plans [`Setter::Date`] when it
//!    disagrees with the app's, even though the props' own `date` did not
//!    change — a rejected pick snaps back on the next differing params (the
//!    same v1 limitation `switch.rs` documents applies).
//! 2. **Echo guard: the runtime's re-entrancy drop, and nothing else.** On
//!    Android `DatePicker.updateDate` (the write-back) and `setMinDate`/
//!    `setMaxDate` (when they clamp the current date) notify
//!    `OnDateChangedListener` **synchronously**, from inside `update` — which
//!    runs inside `crate::runtime::with_runtime`, so that echo re-enters the
//!    held runtime borrow and is dropped there before [`decode_event`] or any
//!    app callback sees it (`crate::controls`' module doc's *echo guard*).
//!    Setting the platform date from inside the change handler therefore
//!    never re-fires the handler. UIKit and AppKit send no action for a
//!    programmatic `setDate:`/`setDateValue:` at all. No per-instance
//!    suppression flag, on any arm.
//!
//! # Range: clamped on decode, never inverted or out of range on the platform
//!
//! A `date` outside `[min, max]` is clamped into it on decode (the platforms
//! clamp their own display anyway; clamping first keeps the write-back from
//! fighting them), and an inverted range (`min > max`) degrades to the
//! single day `min` rather than reaching a platform — Android's calendar
//! mode sizes its year list from `max - min`. This decode-time clamp is
//! necessarily platform-agnostic — [`DatePickerProps::decode`] runs once,
//! shared by all three arms, before any arm is known — so it only ever
//! catches an *explicit* `min > max`; it cannot see that a `None` bound
//! resolves to a different literal date per arm ([`CivilDate::MIN`]/
//! [`CivilDate::MAX`] for the Apple arms; the Android arm's own documented
//! 1900-01-01/2100-12-31 default), nor that an *explicit* bound — API-legal,
//! valid on the Apple arms — can fall outside a narrower arm's own range.
//!
//! [`DatePickerProps::plan`] therefore resolves each side (`old` and `new`)
//! against the calling arm's own [`Bounds`] and clamps the result into
//! `[Bounds::floor, Bounds::ceiling]` before it ever reaches a setter or a
//! widen-vs-narrow comparison: no arm ever receives an inverted range or a
//! date outside it; on Android, bounds outside 1900-01-01..2100-12-31 are
//! clamped to it (a LIMITATIONS entry follows). The two range setters are
//! then ordered against these CLAMPED, arm-resolved values — the bound that
//! *widens* the range is written first — so the ordering matches what the
//! platform will actually hold, never a platform-agnostic assumption; a
//! `min`/`max` whose clamped value did not change from `old` to `new` plans
//! no setter at all, even when the app's own raw value did (e.g. an
//! explicit bound moving from one out-of-range value to another that
//! clamps to the same arm ceiling/floor). When clamping altered an explicit
//! bound or the date, `plan` logs a warning (once per process) naming the slot,
//! the app's values, and the arm's range. A range change (by its clamped value)
//! also re-asserts [`Setter::Date`], because narrowing a range can move the
//! platform's date — the date itself is clamped into the same resolved
//! range so the platform is never asked for a date outside the range it
//! will hold. Both create-time init and update-time updateDate receive the
//! effective date (the app's date clamped into the arm's resolved range).
//!
//! # `style`: live on Apple, baked at construction on Android
//!
//! | [`DatePickerStyle`] | iOS (`preferredDatePickerStyle`) | macOS (`datePickerStyle`) | Android |
//! |---|---|---|---|
//! | `Compact` (default) | `.compact` | `textFieldAndStepper` + `presentsCalendarOverlay` | spinner mode |
//! | `Wheels` | `.wheels` | `textFieldAndStepper` (AppKit has no wheels) | spinner mode |
//! | `Inline` | `.inline` (iOS 14+, inside the 15.0 floor) | `clockAndCalendar` | calendar mode |
//!
//! Android's `datePickerMode` is a construction-time style attribute with no
//! setter, so that arm's `create` reads `props.style` directly to pick the
//! constructor style (the exact shape `spinner.rs`'s *`size_class`* section
//! describes) and a later style change is warned-and-ignored there
//! (`platform::warn_style_unsupported`).
//!
//! # Theme: `accent_ink` tint, `body_text` text colour
//!
//! `crate::api::theme` folds `accent_ink` into [`super::TINT`] (applied as
//! `UIDatePicker.tintColor`; `NSDatePicker` has no tint property — the
//! calendar's selection draws in the system accent colour — logged and
//! no-op'd) and `body_text` into [`super::TEXT_COLOR`] (applied as
//! `NSDatePicker.textColor`; UIKit exposes no public text colour on
//! `UIDatePicker`, logged and no-op'd). **Android's `DatePicker` has no tint
//! or text-colour API at all** — its colours come only from the theme it
//! was constructed against, so both fold to a logged no-op there and the
//! night-qualified construction `Context` (theme ladder L1) is the whole of
//! its theming. L1 rides the raw `dark` wire like every other control; iOS
//! re-pins `overrideUserInterfaceStyle` on every update (`crate::apple`'s
//! theme module), macOS its `NSAppearance`.

use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};

use super::{
    CONTENT_DESCRIPTION, ENABLED, Plan, Setter, TEXT_COLOR, TINT, color, owned_text, slot_of,
};
use crate::NativeWidgetError;
use crate::events::{EVENT_KIND_DATE, EventPayload, pack_date, unpack_date};
use crate::registry::SlotId;
use crate::runtime::{NativeEvent, Params};

/// The registered kind string the api layer injects as `__frustControl`.
pub(crate) const KIND: &str = "date_picker";

/// `"date"` — the app-owned date (controlled), packed with
/// `crate::events::pack_date`.
pub(crate) const DATE: &str = "date";
/// `"minDate"` — the earliest selectable date, packed like [`DATE`]; absent
/// for the platform's own floor.
pub(crate) const MIN_DATE: &str = "minDate";
/// `"maxDate"` — the latest selectable date, packed like [`DATE`]; absent
/// for the platform's own ceiling.
pub(crate) const MAX_DATE: &str = "maxDate";
/// `"style"` — [`DatePickerStyle`]'s wire spelling.
pub(crate) const STYLE: &str = "style";

/// A calendar date — year, month, day — with no time of day and no time
/// zone: what a native date picker shows and what its change handler
/// reports.
///
/// Proleptic Gregorian, `year` 1–9999, `month` **1-based** (1 = January),
/// `day` 1–31 and real for its month (no 31 April, 29 February only in a
/// leap year). [`CivilDate::new`] is the only public constructor, and the
/// only way to build one outside this crate — it refuses anything that is
/// not a real date in range, so an out-of-crate caller can never hold an
/// invalid value. Read the components back with [`Self::year`],
/// [`Self::month`] and [`Self::day`].
///
/// Ordered chronologically (`year`, then `month`, then `day`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CivilDate {
    // Crate-visible, not public: every direct field read/construction stays
    // inside `frust_native_widgets` (`crate::events`'s wire codec and
    // `crate::android::ctx`'s JNI calls both read these three directly), but
    // `CivilDate::new` is the only constructor this crate's own public API
    // (`native_date_picker`, `NativeDatePickerView::min`/`max`,
    // `Self::on_change`'s callback) ever exposes to an app crate, so an
    // out-of-crate caller can never assemble an invalid literal.
    pub(crate) year: i32,
    pub(crate) month: u8,
    pub(crate) day: u8,
}

impl CivilDate {
    /// The earliest date this crate represents: 1 January of year 1.
    pub const MIN: Self = Self::from_parts(1, 1, 1);

    /// The latest date this crate represents: 31 December 9999.
    pub const MAX: Self = Self::from_parts(9999, 12, 31);

    /// `year`-`month`-`day`, or `None` when that is not a real calendar date
    /// in the supported range (see the type doc).
    pub fn new(year: i32, month: u8, day: u8) -> Option<Self> {
        let date = Self::from_parts(year, month, day);
        date.is_valid().then_some(date)
    }

    /// Whether this is a real calendar date in the supported range.
    pub fn is_valid(self) -> bool {
        (Self::MIN.year..=Self::MAX.year).contains(&self.year)
            && (1..=12).contains(&self.month)
            && self.day >= 1
            && self.day <= days_in_month(self.year, self.month)
    }

    /// The year, 1–9999.
    pub const fn year(&self) -> i32 {
        self.year
    }

    /// The month, 1-based: 1 = January … 12 = December.
    pub const fn month(&self) -> u8 {
        self.month
    }

    /// The day of the month, 1–31 (and no more than the month has).
    pub const fn day(&self) -> u8 {
        self.day
    }

    /// Build a literal without going through [`Self::new`]'s validation —
    /// never exposed publicly. Sanctioned only for this module's own
    /// well-known constants ([`Self::MIN`]/[`Self::MAX`] here, the Android
    /// arm's `PLATFORM_MIN`/`PLATFORM_MAX`), each a literal known valid by
    /// inspection; every other construction path, in this crate or out of
    /// it, goes through [`Self::new`].
    const fn from_parts(year: i32, month: u8, day: u8) -> Self {
        Self { year, month, day }
    }
}

impl fmt::Display for CivilDate {
    /// ISO 8601 calendar-date form, `YYYY-MM-DD`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }
}

/// Whether `year` is a proleptic-Gregorian leap year.
fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

/// How many days `month` (1-based) of `year` has; `0` for a month outside
/// 1–12, so [`CivilDate::is_valid`] refuses every day of it.
fn days_in_month(year: i32, month: u8) -> u8 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 if is_leap_year(year) => 29,
        2 => 28,
        _ => 0,
    }
}

/// How the picker presents itself — see the module doc's *`style`* table
/// for each arm's mapping.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum DatePickerStyle {
    /// The smallest footprint the platform offers.
    #[default]
    Compact,
    /// Spinning wheels.
    Wheels,
    /// A full, always-visible calendar.
    Inline,
}

impl DatePickerStyle {
    /// The wire spelling the api layer writes into [`STYLE`].
    fn from_wire(raw: &str) -> Option<Self> {
        match raw {
            "compact" => Some(Self::Compact),
            "wheels" => Some(Self::Wheels),
            "inline" => Some(Self::Inline),
            _ => None,
        }
    }
}

/// What a `None` `min`/`max` resolves to on one platform's own control —
/// supplied to [`DatePickerProps::plan`] so its widening-vs-narrowing
/// ordering decision (module doc's *Range*) compares against the date the
/// platform will *actually* hold, never a platform-agnostic assumption.
/// Both Apple arms simply clear the bound for `nil`, which is this crate's
/// own unbounded [`CivilDate::MIN`]/[`CivilDate::MAX`] ([`Self::APPLE`]);
/// the Android arm substitutes `DatePicker`'s own documented
/// 1900-01-01/2100-12-31 default (its `platform` module's own `BOUNDS`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Bounds {
    floor: CivilDate,
    ceiling: CivilDate,
}

impl Bounds {
    /// Both Apple arms: `setMinimumDate:`/`setMaximumDate:` and
    /// `setMinDate:`/`setMaxDate:` simply clear the bound for `nil` — there
    /// is no platform default narrower than this crate's own unbounded
    /// ends to substitute.
    pub(crate) const APPLE: Self = Self {
        floor: CivilDate::MIN,
        ceiling: CivilDate::MAX,
    };

    /// `min`, or this platform's own floor when it is `None`.
    fn resolve_min(self, min: Option<CivilDate>) -> CivilDate {
        min.unwrap_or(self.floor)
    }

    /// `max`, or this platform's own ceiling when it is `None`.
    fn resolve_ceiling(self, max: Option<CivilDate>) -> CivilDate {
        max.unwrap_or(self.ceiling)
    }

    /// The range this arm will actually hold for `min`/`max`: each resolved
    /// bound ([`Self::resolve_min`]/[`Self::resolve_ceiling`]) clamped into
    /// this arm's own `[floor, ceiling]` — module doc's *Range*. An explicit
    /// bound outside that range (API-legal, valid on the Apple arms) is
    /// clamped here rather than reaching the platform's own setter as an
    /// out-of-range or inverted pair; if the clamp still crosses (only
    /// possible when both bounds are explicit and inverted, which
    /// [`DatePickerProps::decode`] already prevents) the floor collapses
    /// onto the ceiling rather than risk an inverted pair reaching a
    /// setter.
    fn effective_range(
        self,
        min: Option<CivilDate>,
        max: Option<CivilDate>,
    ) -> (CivilDate, CivilDate) {
        let floor = self.resolve_min(min).clamp(self.floor, self.ceiling);
        let ceiling = self.resolve_ceiling(max).clamp(self.floor, self.ceiling);
        if floor > ceiling {
            (ceiling, ceiling)
        } else {
            (floor, ceiling)
        }
    }
}

/// The marker type registered under [`KIND`] — by all three arms.
pub(crate) struct DatePicker;

/// Everything a `DatePicker` slot can be told, as one Rust-diffed value.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct DatePickerProps {
    /// The differ's slot id — **not a property**; `create` needs it for the
    /// listener/target it attaches.
    pub(crate) slot: SlotId,
    /// The app-owned date (controlled), clamped into `[min, max]` on decode;
    /// `None` leaves the platform on its own initial date (today).
    pub(crate) date: Option<CivilDate>,
    /// The earliest selectable date, `None` for the platform's own floor.
    pub(crate) min: Option<CivilDate>,
    /// The latest selectable date, `None` for the platform's own ceiling;
    /// never before `min` (normalized on decode).
    pub(crate) max: Option<CivilDate>,
    /// The presentation — module doc's *`style`* table.
    pub(crate) style: DatePickerStyle,
    /// `View.setEnabled` / `UIControl.enabled` / `NSControl.enabled`.
    pub(crate) enabled: bool,
    /// Packed ARGB tint, or `None` for the platform's own.
    pub(crate) tint: Option<i32>,
    /// Packed ARGB text colour, or `None` for the platform's own.
    pub(crate) text_color: Option<i32>,
    /// The TalkBack/VoiceOver label.
    pub(crate) content_description: Option<String>,
}

impl DatePickerProps {
    /// The state every arm's `create` diffs its first plan against: the
    /// platform's own date and range, [`DatePickerStyle::Compact`], enabled,
    /// no tint/text colour/label. Each arm reaches this state at construction
    /// (its own `create` normalizes the style on Apple and bakes it on
    /// Android — module doc).
    pub(crate) fn platform_default(slot: SlotId) -> Self {
        Self {
            slot,
            date: None,
            min: None,
            max: None,
            style: DatePickerStyle::Compact,
            enabled: true,
            tint: None,
            text_color: None,
            content_description: None,
        }
    }

    /// The app's `date` clamped into the effective range this arm will hold —
    /// the date that an arm's `create` and `update` both pass to platform calls
    /// (module doc's *Range*). `None` when the app's date is absent, leaving
    /// the platform on its own initial date (today).
    pub(crate) fn effective_date(&self, bounds: Bounds) -> Option<CivilDate> {
        let (min, max) = bounds.effective_range(self.min, self.max);
        self.date.map(|date| date.clamp(min, max))
    }

    /// Decode a `DatePicker` slot's params (module doc's *Range* for the
    /// normalization).
    ///
    /// # Errors
    /// [`NativeWidgetError::Params`] when the reserved identity keys are
    /// missing.
    pub(crate) fn decode(params: &Params<'_>) -> Result<Self, NativeWidgetError> {
        let min = date_field(params, MIN_DATE);
        let max = match (min, date_field(params, MAX_DATE)) {
            (Some(min), Some(max)) if max < min => Some(min),
            (_, max) => max,
        };
        let date = date_field(params, DATE).map(|date| clamp(date, min, max));
        Ok(Self {
            slot: slot_of(params)?,
            date,
            min,
            max,
            style: params
                .string(STYLE)
                .and_then(|raw| DatePickerStyle::from_wire(&raw))
                .unwrap_or_default(),
            enabled: params.flag(ENABLED).unwrap_or(true),
            tint: color(params, TINT),
            text_color: color(params, TEXT_COLOR),
            content_description: owned_text(params, CONTENT_DESCRIPTION),
        })
    }

    /// The setter-call plan for `old` → `new`, given the date the platform
    /// last reported (`observed`, `None` until the user has picked one) and
    /// `bounds` — the calling arm's own [`Bounds`], module doc's *Range*.
    ///
    /// Order is load-bearing: the style first; then the two range bounds,
    /// the *widening* one first (compared through `bounds`'
    /// [`Bounds::effective_range`], so a `None` resolves to — and an
    /// out-of-range explicit bound clamps to — what this specific platform
    /// will hold) so the platform never holds an inverted or out-of-range
    /// pair; then the date, itself clamped into the same resolved range and
    /// re-planned when the app's date changed, when the platform drifted
    /// from it (the write-back), or when either bound's CLAMPED value
    /// changed (a narrowed range can have moved the platform's date).
    pub(crate) fn plan<'a>(
        old: &Self,
        new: &'a Self,
        observed: Option<CivilDate>,
        bounds: Bounds,
    ) -> Plan<'a> {
        let (new_min, new_max) = bounds.effective_range(new.min, new.max);
        let (old_min, old_max) = bounds.effective_range(old.min, old.max);
        let clamped_date = new.effective_date(bounds);
        warn_if_clamped(new, new_min, new_max, clamped_date, bounds);

        let mut plan = Plan::new();
        if old.style != new.style {
            plan.push(Setter::DatePickerStyle(new.style));
        }
        // A `min`/`max` setter is planned from the CLAMPED, arm-resolved
        // value, never the app's own raw one: an explicit bound that
        // resolves to the same clamped value as before is a no-op for this
        // platform even when the raw value changed (module doc's *Range*).
        let min_changed = old_min != new_min;
        let max_changed = old_max != new_max;
        let min_setter = min_changed.then(|| Setter::MinDate(new.min.map(|_| new_min)));
        let max_setter = max_changed.then(|| Setter::MaxDate(new.max.map(|_| new_max)));
        // Growing (or keeping) the effective ceiling widens the range
        // upward, so write it before the floor; otherwise the floor moves
        // down first — compared through the CLAMPED effective values, so
        // the ordering matches what the platform will actually hold.
        if new_max >= old_max {
            plan.extend(max_setter);
            plan.extend(min_setter);
        } else {
            plan.extend(min_setter);
            plan.extend(max_setter);
        }
        if let Some(date) = clamped_date {
            let drifted = observed.is_some_and(|platform| platform != date);
            if old.date != new.date || drifted || min_changed || max_changed {
                plan.push(Setter::Date(date));
            }
        }
        if old.enabled != new.enabled {
            plan.push(Setter::Enabled(new.enabled));
        }
        if old.tint != new.tint {
            plan.push(Setter::DatePickerTint(new.tint));
        }
        if old.text_color != new.text_color {
            plan.push(Setter::DatePickerTextColor(new.text_color));
        }
        if old.content_description != new.content_description {
            plan.push(Setter::ContentDescription(
                new.content_description.as_deref(),
            ));
        }
        plan
    }
}

/// One-time warning that clamping into `bounds` (module doc's *Range*)
/// altered an explicit `min`/`max` or the date — logged at most once per
/// process, not once per call.
static WARN_CLAMPED: AtomicBool = AtomicBool::new(false);

/// Log at most once per process when clamping into `bounds` (module doc's
/// *Range*) actually changed an explicit `min`/`max` or the date — never once
/// per field, and never when nothing was out of range to begin with.
fn warn_if_clamped(
    new: &DatePickerProps,
    new_min: CivilDate,
    new_max: CivilDate,
    clamped_date: Option<CivilDate>,
    bounds: Bounds,
) {
    let mut clamped: Vec<String> = Vec::new();
    if let Some(min) = new.min
        && min != new_min
    {
        clamped.push(format!("min {min} -> {new_min}"));
    }
    if let Some(max) = new.max
        && max != new_max
    {
        clamped.push(format!("max {max} -> {new_max}"));
    }
    if let (Some(date), Some(clamped_date)) = (new.date, clamped_date)
        && date != clamped_date
    {
        clamped.push(format!("date {date} -> {clamped_date}"));
    }
    if clamped.is_empty() {
        return;
    }
    if !WARN_CLAMPED.swap(true, Ordering::Relaxed) {
        log::warn!(
            "frust-native-widgets: date_picker slot {} — {} outside this platform's own range \
             {}..{}, clamped into it (this warning is logged once per process)",
            new.slot,
            clamped.join(", "),
            bounds.floor,
            bounds.ceiling
        );
    }
}

/// A packed date field (`crate::events::pack_date`'s layout), `None` when
/// absent or not a real date — degrade, never a dead slot
/// (`crate::controls`' rule).
fn date_field(params: &Params<'_>, key: &str) -> Option<CivilDate> {
    params.int(key).and_then(unpack_date)
}

/// `date` clamped into the (already non-inverted) `[min, max]`.
fn clamp(date: CivilDate, min: Option<CivilDate>, max: Option<CivilDate>) -> CivilDate {
    let floored = min.map_or(date, |min| date.max(min));
    max.map_or(floored, |max| floored.min(max))
}

/// The wire value of `date` for a params body — the same packed integer the
/// event wire carries (module doc).
pub(crate) fn wire(date: CivilDate) -> i64 {
    pack_date(date)
}

/// Decode an [`EVENT_KIND_DATE`] firing into the typed vocabulary: records
/// the write-back drift signal (`observed`) and decodes to an
/// [`EventPayload::Date`].
///
/// `None` when `event.kind` is not the date kind (defensive — the listener/
/// target is only ever attached for this one kind), or when `detail` is not
/// a real date (`crate::events::unpack_date`), in which case `observed` is
/// left untouched.
///
/// Pure and host-testable, and the ONE decoder all three arms' `on_event`
/// call — kind/detail parity by construction.
pub(crate) fn decode_event(
    observed: &mut Option<CivilDate>,
    event: NativeEvent,
) -> Option<EventPayload> {
    if event.kind != EVENT_KIND_DATE {
        return None;
    }
    let date = unpack_date(event.detail)?;
    *observed = Some(date);
    Some(EventPayload::Date(date))
}

/// `NSDate` ↔ [`CivilDate`] for the two Apple arms — both the controls'
/// setters and the two target classes (`crate::apple::events`,
/// `crate::appkit::events`) convert through here, so the arms cannot map a
/// date differently.
///
/// Conversion runs in a **Gregorian** `NSCalendar` in the current time zone,
/// deliberately not `NSCalendar.currentCalendar`: [`CivilDate`] is a
/// Gregorian date on every arm (Android's `DatePicker` reports Gregorian
/// fields whatever the user's locale), and a user whose system calendar is,
/// say, Buddhist or Japanese would otherwise report a different year for the
/// same absolute day. The picker itself keeps displaying the user's own
/// calendar — only the Rust-side mapping is pinned. A date becomes an
/// `NSDate` at local **noon**, so no DST transition at midnight can push it
/// onto a neighbouring day.
#[cfg(any(target_os = "ios", target_os = "macos"))]
pub(crate) mod foundation {
    use objc2::rc::Retained;
    use objc2_foundation::{
        NSCalendar, NSCalendarIdentifierGregorian, NSCalendarUnit, NSDate, NSDateComponents,
    };

    use super::CivilDate;

    /// A Gregorian calendar in the current time zone (module doc).
    fn gregorian() -> Option<Retained<NSCalendar>> {
        // SAFETY: `NSCalendarIdentifierGregorian` is an immutable
        // Foundation-exported `NSString` constant, initialized before any
        // Rust code runs; reading the extern static is sound.
        let identifier = unsafe { NSCalendarIdentifierGregorian };
        NSCalendar::calendarWithIdentifier(identifier)
    }

    /// `date` at local noon, or `None` if Foundation cannot build it (it
    /// can for every valid [`CivilDate`]; the `Option` is Foundation's).
    pub(crate) fn ns_date(date: CivilDate) -> Option<Retained<NSDate>> {
        let calendar = gregorian()?;
        let components = NSDateComponents::new();
        components.setYear(date.year as isize);
        components.setMonth(isize::from(date.month));
        components.setDay(isize::from(date.day));
        components.setHour(12);
        calendar.dateFromComponents(&components)
    }

    /// The civil date `date` falls on in the current time zone, or `None`
    /// when it is outside [`CivilDate`]'s range (before year 1 — a BC era —
    /// or after 9999).
    pub(crate) fn civil_date(date: &NSDate) -> Option<CivilDate> {
        let calendar = gregorian()?;
        // Era 1 is AD in the Gregorian calendar; era 0 years count backwards.
        if calendar.component_fromDate(NSCalendarUnit::Era, date) != 1 {
            return None;
        }
        let year = calendar.component_fromDate(NSCalendarUnit::Year, date);
        let month = calendar.component_fromDate(NSCalendarUnit::Month, date);
        let day = calendar.component_fromDate(NSCalendarUnit::Day, date);
        CivilDate::new(
            i32::try_from(year).ok()?,
            u8::try_from(month).ok()?,
            u8::try_from(day).ok()?,
        )
    }

    /// `date` as an `NSDate`, `None` staying `None` — the nullable-range
    /// setters' argument (`nil` restores the platform's own bound).
    pub(crate) fn optional_ns_date(date: Option<CivilDate>) -> Option<Retained<NSDate>> {
        date.and_then(ns_date)
    }
}

#[cfg(target_os = "android")]
pub(crate) mod platform {
    //! The Android half: build the `DatePicker` in the mode `props.style`
    //! asks for, apply the shared plan, and attach the ONE listener through
    //! `DatePicker.init(year, month, day, listener)`.
    //!
    //! # Construction: the mode is a style resource, not a setter
    //!
    //! `android:datePickerMode` is read once, in the constructor, from the
    //! style it is handed — there is no setter and no `ContextThemeWrapper`
    //! is involved. So `create` calls the four-argument constructor
    //! `DatePicker(context, null, 0, <style>)` with a framework style
    //! resolved from `android.R.style` at runtime (never a hard-coded id):
    //!
    //! - `Inline` → `Widget_Material_DatePicker`, whose `datePickerMode` is
    //!   `calendar`;
    //! - `Compact`/`Wheels` → `Widget_DatePicker`, which sets no
    //!   `datePickerMode`, so the constructor's own default — spinner mode —
    //!   applies; its legacy `calendarViewShown` is then switched off and the
    //!   spinners on explicitly (`setCalendarViewShown`/`setSpinnersShown`,
    //!   both meaningful in spinner mode only).
    //!
    //! Both styles resolve their colours against the night-qualified
    //! construction `Context` (theme ladder L1), exactly as the one-argument
    //! constructor would. Should the style field ever be missing from a
    //! device's framework, `create` falls back to that one-argument
    //! constructor (the theme's own default mode) with one warning, rather
    //! than a dead slot.
    //!
    //! # Months are 0-based on this side of the wire only
    //!
    //! `DatePicker.init`/`updateDate`/`getMonth` and `java.util.Calendar`
    //! count months from 0; [`CivilDate`] and the event wire count from 1.
    //! Every conversion is in this module (and in the Kotlin listener's
    //! `onDateChanged`, for events) — nothing else sees a 0-based month.
    //!
    //! # Range bounds are local-midnight millis
    //!
    //! `setMinDate`/`setMaxDate` take epoch milliseconds, which `DatePicker`
    //! turns back into a day in the device's default time zone; the bound is
    //! therefore built through `java.util.Calendar.getInstance()` (the same
    //! default zone) at local midnight, not computed from UTC in Rust. An
    //! absent bound restores `DatePicker`'s own documented default (1900-01-01
    //! / 2100-12-31).

    use std::sync::Once;

    use jni::objects::{JObject, JValue};
    use jni::refs::Global;
    use jni::{jni_sig, jni_str};

    use super::{Bounds, CivilDate, DatePicker, DatePickerProps, DatePickerStyle, decode_event};
    use crate::NativeWidgetError;
    use crate::android::{NativeCtx, NativeView};
    use crate::controls::platform::{FRAME_CAPACITY, apply as apply_shared};
    use crate::controls::{Plan, Setter};
    use crate::events::EventPayload;
    use crate::runtime::{NativeEvent, NativeWidget, Params};

    /// `android.widget.DatePicker` — the framework class.
    const CLASS: &str = "android.widget.DatePicker";
    /// `android.R$style` — the framework's public style ids, read at runtime
    /// (module doc's *Construction*).
    const R_STYLE_CLASS: &str = "android.R$style";
    /// `java.util.Calendar` — the range bounds' millis (module doc).
    const CALENDAR_CLASS: &str = "java.util.Calendar";

    /// `DatePicker`'s own default floor when no `min` is set.
    const PLATFORM_MIN: CivilDate = CivilDate::from_parts(1900, 1, 1);
    /// `DatePicker`'s own default ceiling when no `max` is set.
    const PLATFORM_MAX: CivilDate = CivilDate::from_parts(2100, 12, 31);
    /// This arm's [`Bounds`] — module doc's *Range*: a `None` `min`/`max`
    /// resolves to [`PLATFORM_MIN`]/[`PLATFORM_MAX`] here, never this
    /// crate's unbounded [`Bounds::APPLE`].
    const BOUNDS: Bounds = Bounds {
        floor: PLATFORM_MIN,
        ceiling: PLATFORM_MAX,
    };

    /// Build the picker for `style` — module doc's *Construction*.
    fn new_date_picker<'local>(
        ctx: &mut NativeCtx<'local, '_>,
        style: DatePickerStyle,
    ) -> Result<JObject<'local>, NativeWidgetError> {
        let (field, spinner) = match style {
            DatePickerStyle::Inline => (jni_str!("Widget_Material_DatePicker"), false),
            DatePickerStyle::Compact | DatePickerStyle::Wheels => {
                (jni_str!("Widget_DatePicker"), true)
            }
        };
        let styles = ctx.class(R_STYLE_CLASS)?;
        let style_res = match ctx.run_jni(&format!("android.R.style.{field}"), |env| {
            env.get_static_field(&styles, field, jni_sig!("I"))?.i()
        }) {
            Ok(style_res) => style_res,
            Err(error) => {
                log::warn!(
                    "frust-native-widgets: {error} — building the DatePicker with the theme's own \
                     default mode instead"
                );
                return ctx.new_view(CLASS);
            }
        };
        let class = ctx.class(CLASS)?;
        let context = ctx.context()?;
        let view = ctx.run_jni("new DatePicker(Context, AttributeSet, int, int)", |env| {
            env.new_object(
                &class,
                jni_sig!("(Landroid/content/Context;Landroid/util/AttributeSet;II)V"),
                &[
                    JValue::Object(context),
                    JValue::Object(&JObject::null()),
                    JValue::Int(0),
                    JValue::Int(style_res),
                ],
            )
        })?;
        if spinner {
            ctx.call_void(
                &view,
                jni_str!("setCalendarViewShown"),
                jni_sig!("(Z)V"),
                &[JValue::Bool(false)],
            )?;
            ctx.call_void(
                &view,
                jni_str!("setSpinnersShown"),
                jni_sig!("(Z)V"),
                &[JValue::Bool(true)],
            )?;
        }
        Ok(view)
    }

    /// The picker's current date, read back through `getYear`/`getMonth`/
    /// `getDayOfMonth` — `init`'s argument when the app supplied no date.
    fn current_date(
        ctx: &mut NativeCtx<'_, '_>,
        view: &JObject<'_>,
    ) -> Result<CivilDate, NativeWidgetError> {
        let (year, month0, day) = ctx.run_jni("DatePicker.get{Year,Month,DayOfMonth}", |env| {
            let year = env
                .call_method(view, jni_str!("getYear"), jni_sig!("()I"), &[])?
                .i()?;
            let month0 = env
                .call_method(view, jni_str!("getMonth"), jni_sig!("()I"), &[])?
                .i()?;
            let day = env
                .call_method(view, jni_str!("getDayOfMonth"), jni_sig!("()I"), &[])?
                .i()?;
            Ok((year, month0, day))
        })?;
        u8::try_from(month0 + 1)
            .ok()
            .zip(u8::try_from(day).ok())
            .and_then(|(month, day)| CivilDate::new(year, month, day))
            .ok_or_else(|| {
                NativeWidgetError::Platform(format!(
                    "android native-widgets: DatePicker reported {year}-{month0}(0-based)-{day}, \
                     not a supported date"
                ))
            })
    }

    /// `date` at local midnight as epoch millis, through
    /// `java.util.Calendar` (module doc's *Range bounds*).
    fn epoch_millis(
        ctx: &mut NativeCtx<'_, '_>,
        date: CivilDate,
    ) -> Result<i64, NativeWidgetError> {
        let class = ctx.class(CALENDAR_CLASS)?;
        ctx.run_jni("Calendar.getTimeInMillis", |env| {
            let calendar = env
                .call_static_method(
                    &class,
                    jni_str!("getInstance"),
                    jni_sig!("()Ljava/util/Calendar;"),
                    &[],
                )?
                .l()?;
            env.call_method(&calendar, jni_str!("clear"), jni_sig!("()V"), &[])?
                .v()?;
            env.call_method(
                &calendar,
                jni_str!("set"),
                jni_sig!("(III)V"),
                &[
                    JValue::Int(date.year),
                    JValue::Int(i32::from(date.month) - 1),
                    JValue::Int(i32::from(date.day)),
                ],
            )?
            .v()?;
            env.call_method(&calendar, jni_str!("getTimeInMillis"), jni_sig!("()J"), &[])?
                .j()
        })
    }

    /// A live picker's retained state.
    pub(crate) struct DatePickerState {
        /// The picker's own global reference (the second one — see
        /// `button.rs`'s note).
        view: Global<JObject<'static>>,
        /// The date the platform last reported, `None` while untouched —
        /// [`DatePickerProps::plan`]'s write-back drift signal. Written from
        /// [`NativeWidget::on_event`] via [`decode_event`].
        observed: Option<CivilDate>,
    }

    impl NativeWidget for DatePicker {
        type Props = DatePickerProps;
        type State = DatePickerState;

        fn decode_props(params: &Params<'_>) -> Result<Self::Props, NativeWidgetError> {
            DatePickerProps::decode(params)
        }

        fn create(
            ctx: &mut NativeCtx<'_, '_>,
            props: &Self::Props,
        ) -> Result<(NativeView, Self::State), NativeWidgetError> {
            let view = new_date_picker(ctx, props.style)?;
            // The style is baked by the constructor and the date is set by
            // `init` below, so the diffed plan must not re-report either
            // (`spinner.rs`'s create, the same shape).
            let mut default = DatePickerProps::platform_default(props.slot);
            default.style = props.style;
            default.date = props.date;
            let plan = DatePickerProps::plan(&default, props, None, BOUNDS);
            ctx.with_frame(FRAME_CAPACITY, |ctx| apply_all(ctx, &view, &plan))?;
            // Read after the range setters ran, so an app that supplied no
            // date still hands `init` the platform's own. The effective date
            // is clamped into the resolved range for this arm.
            let date = match props.effective_date(BOUNDS) {
                Some(date) => date,
                None => current_date(ctx, &view)?,
            };
            // Attached last, the other controls' create order: nothing above
            // can reach the runtime as an event.
            let listener = ctx.new_listener(props.slot)?;
            ctx.init_date_picker(&view, date, &listener)?;
            let handle = ctx.retain(&view)?;
            let retained = ctx.retain(&view)?;
            let listener_ref = ctx.retain(&listener)?;
            Ok((
                NativeView::with_extra(handle, vec![listener_ref]),
                DatePickerState {
                    view: retained,
                    observed: None,
                },
            ))
        }

        fn update(
            ctx: &mut NativeCtx<'_, '_>,
            state: &mut Self::State,
            old: &Self::Props,
            new: &Self::Props,
        ) -> Result<(), NativeWidgetError> {
            let plan = DatePickerProps::plan(old, new, state.observed, BOUNDS);
            // `updateDate`/`setMinDate`/`setMaxDate` echo synchronously into
            // the listener; that echo re-enters `with_runtime` mid-borrow and
            // is dropped there (module doc's *Echo guard*) — no suppression
            // state is held across this call.
            let applied = ctx.with_frame(FRAME_CAPACITY, |ctx| apply_all(ctx, &state.view, &plan));
            if applied.is_ok() {
                state.observed = None;
            }
            applied
        }

        fn on_event(state: &mut Self::State, event: NativeEvent) -> Option<EventPayload> {
            decode_event(&mut state.observed, event)
        }

        fn dispose(
            ctx: &mut NativeCtx<'_, '_>,
            state: Self::State,
        ) -> Result<(), NativeWidgetError> {
            // Detach so a stray in-flight change can't fire after this
            // slot's instance is gone; dropping `state` releases its global
            // reference either way.
            ctx.set_on_date_changed_listener(&state.view, &JObject::null())
        }
    }

    /// Execute a whole [`Plan`], front to back — the range bounds before the
    /// date, the order the shared plan already guarantees.
    fn apply_all(
        ctx: &mut NativeCtx<'_, '_>,
        view: &JObject<'_>,
        plan: &Plan<'_>,
    ) -> Result<(), NativeWidgetError> {
        for setter in plan {
            apply(ctx, view, setter)?;
        }
        Ok(())
    }

    /// Execute one planned property write — this control's own setters
    /// here, the shared ones (`Enabled`, `ContentDescription`) through
    /// `crate::controls::platform::apply`.
    fn apply(
        ctx: &mut NativeCtx<'_, '_>,
        view: &JObject<'_>,
        setter: &Setter<'_>,
    ) -> Result<(), NativeWidgetError> {
        match *setter {
            Setter::Date(date) => ctx.call_void(
                view,
                jni_str!("updateDate"),
                jni_sig!("(III)V"),
                &[
                    JValue::Int(date.year),
                    JValue::Int(i32::from(date.month) - 1),
                    JValue::Int(i32::from(date.day)),
                ],
            ),
            Setter::MinDate(min) => {
                let millis = epoch_millis(ctx, min.unwrap_or(PLATFORM_MIN))?;
                ctx.call_void(
                    view,
                    jni_str!("setMinDate"),
                    jni_sig!("(J)V"),
                    &[JValue::Long(millis)],
                )
            }
            Setter::MaxDate(max) => {
                let millis = epoch_millis(ctx, max.unwrap_or(PLATFORM_MAX))?;
                ctx.call_void(
                    view,
                    jni_str!("setMaxDate"),
                    jni_sig!("(J)V"),
                    &[JValue::Long(millis)],
                )
            }
            Setter::DatePickerStyle(style) => {
                warn_style_unsupported(style);
                Ok(())
            }
            Setter::DatePickerTint(_) | Setter::DatePickerTextColor(_) => {
                log_no_colour_api();
                Ok(())
            }
            Setter::Enabled(_) | Setter::ContentDescription(_) => apply_shared(ctx, view, setter),
            ref other => {
                log::warn!(
                    "frust-native-widgets: control 'date_picker' planned a setter its Android \
                     arm does not implement ({other:?}) — ignored"
                );
                Ok(())
            }
        }
    }

    /// One-time warning that a post-create style change is not applied —
    /// module doc's *Construction*: the mode is baked into the constructor
    /// style, so only a rebuilt view could change it.
    pub(crate) fn warn_style_unsupported(style: DatePickerStyle) {
        static ONCE: Once = Once::new();
        ONCE.call_once(|| {
            log::warn!(
                "frust-native-widgets: Android's DatePicker bakes its spinner/calendar mode into \
                 the style it was constructed with, so a later style change to {style:?} is not \
                 applied — the picker keeps the mode it was created in"
            );
        });
    }

    /// One-time note that `DatePicker` has no tint or text-colour API — the
    /// module doc's *Theme* section: a documented platform gap, not a
    /// defect, so debug level.
    fn log_no_colour_api() {
        static ONCE: Once = Once::new();
        ONCE.call_once(|| {
            log::debug!(
                "frust-native-widgets: Android's DatePicker exposes no tint or text-colour setter \
                 — its colours come from the (night-qualified) construction theme only"
            );
        });
    }
}

#[cfg(target_os = "ios")]
pub(crate) mod platform {
    //! The iOS half: build a `UIDatePicker` in `Date` mode and apply the
    //! shared plan — no echo guard of its own (UIKit sends no `ValueChanged`
    //! for a programmatic `setDate:`; `switch.rs`'s module doc is the
    //! reference account).
    //!
    //! # Construction-time normalization
    //!
    //! `create` pins `datePickerMode = Date` (a fresh picker is
    //! `DateAndTime`) and `preferredDatePickerStyle = Compact` — the
    //! [`DatePickerProps::platform_default`] style, rather than UIKit's own
    //! `.automatic`, so the diffed create plan starts from the truth.

    use objc2::MainThreadMarker;
    use objc2::rc::Retained;
    use objc2_ui_kit::{UIDatePicker, UIDatePickerMode, UIDatePickerStyle};

    use super::foundation::{ns_date, optional_ns_date};
    use super::{Bounds, DatePicker, DatePickerProps, DatePickerStyle, KIND, decode_event};
    use crate::NativeWidgetError;
    use crate::apple::{FrustNativeControlTarget, NativeCtx, NativeView};
    use crate::controls::platform;
    use crate::controls::{Plan, Setter};
    use crate::events::EventPayload;
    use crate::runtime::{NativeEvent, NativeWidget, Params};

    /// A live picker's retained state — `SwitchState`'s shape.
    pub(crate) struct DatePickerState {
        view: Retained<UIDatePicker>,
        /// The target `create` attached as the `ValueChanged` action.
        /// `UIControl` holds targets weakly, so this is its only retain
        /// (`crate::apple::events`' *Target retention*).
        target: Retained<FrustNativeControlTarget>,
        /// The date the platform last reported, `None` while untouched —
        /// [`DatePickerProps::plan`]'s write-back drift signal.
        observed: Option<super::CivilDate>,
    }

    impl NativeWidget for DatePicker {
        type Props = DatePickerProps;
        type State = DatePickerState;

        fn decode_props(params: &Params<'_>) -> Result<Self::Props, NativeWidgetError> {
            DatePickerProps::decode(params)
        }

        fn create(
            ctx: &mut NativeCtx<'_, '_>,
            props: &Self::Props,
        ) -> Result<(NativeView, Self::State), NativeWidgetError> {
            let mtm = ctx.mtm();
            let view = UIDatePicker::new(mtm);
            let default = DatePickerProps::platform_default(props.slot);
            // Module doc's *Construction-time normalization*.
            view.setDatePickerMode(UIDatePickerMode::Date);
            view.setPreferredDatePickerStyle(ui_style(default.style));
            let plan = DatePickerProps::plan(&default, props, None, Bounds::APPLE);
            apply_all(mtm, &view, &plan);
            // Attached after the initial plan, the other controls' order.
            let target = FrustNativeControlTarget::attach_date_picker(mtm, props.slot, &view);
            let handle = NativeView::new(Retained::clone(&view).into_super().into_super(), mtm);
            Ok((
                handle,
                DatePickerState {
                    view,
                    target,
                    observed: None,
                },
            ))
        }

        fn update(
            ctx: &mut NativeCtx<'_, '_>,
            state: &mut Self::State,
            old: &Self::Props,
            new: &Self::Props,
        ) -> Result<(), NativeWidgetError> {
            let plan = DatePickerProps::plan(old, new, state.observed, Bounds::APPLE);
            apply_all(ctx.mtm(), &state.view, &plan);
            // Nothing on this arm can fail, so the drift signal is cleared
            // unconditionally (`Switch`'s iOS arm).
            state.observed = None;
            Ok(())
        }

        fn on_event(state: &mut Self::State, event: NativeEvent) -> Option<EventPayload> {
            decode_event(&mut state.observed, event)
        }

        fn dispose(
            _ctx: &mut NativeCtx<'_, '_>,
            state: Self::State,
        ) -> Result<(), NativeWidgetError> {
            // Detach so a stray in-flight action can't reach a torn-down
            // slot; dropping `state` afterwards releases the target's retain.
            state.target.detach_date_picker(&state.view);
            Ok(())
        }
    }

    /// The `UIDatePickerStyle` for `style` — module doc's table (top of file).
    fn ui_style(style: DatePickerStyle) -> UIDatePickerStyle {
        match style {
            DatePickerStyle::Compact => UIDatePickerStyle::Compact,
            DatePickerStyle::Wheels => UIDatePickerStyle::Wheels,
            DatePickerStyle::Inline => UIDatePickerStyle::Inline,
        }
    }

    /// Execute a whole [`Plan`], front to back.
    fn apply_all(mtm: MainThreadMarker, view: &UIDatePicker, plan: &Plan<'_>) {
        for setter in plan {
            apply(mtm, view, setter);
        }
    }

    /// Execute one planned property write against `view`.
    fn apply(mtm: MainThreadMarker, view: &UIDatePicker, setter: &Setter<'_>) {
        match *setter {
            // No action is sent for a programmatic date (module doc), so the
            // write-back's snap-back is a plain write.
            Setter::Date(date) => match ns_date(date) {
                Some(ns) => view.setDate(&ns),
                None => log::warn!(
                    "frust-native-widgets: iOS could not build an NSDate for {date} — not applied"
                ),
            },
            Setter::MinDate(min) => view.setMinimumDate(optional_ns_date(min).as_deref()),
            Setter::MaxDate(max) => view.setMaximumDate(optional_ns_date(max).as_deref()),
            Setter::DatePickerStyle(style) => view.setPreferredDatePickerStyle(ui_style(style)),
            Setter::Enabled(enabled) => view.setEnabled(enabled),
            Setter::DatePickerTint(argb) => {
                let color = platform::optional_ui_color(argb);
                // SAFETY: objc2 marks `setTintColor:` unsafe only because the
                // header leaves the argument's nullability unannotated;
                // passing `None` is `UIView`'s own documented "restore the
                // inherited tint" behaviour, exactly `DatePickerTint(None)`'s
                // meaning (`crate::controls::platform::set_image_tint`
                // closes the same question for `UIImageView`).
                unsafe { view.setTintColor(color.as_deref()) };
            }
            Setter::DatePickerTextColor(argb) => {
                log::debug!(
                    "frust-native-widgets: iOS DatePickerTextColor({argb:?}) not applied — \
                     UIDatePicker exposes no public text colour"
                );
            }
            Setter::ContentDescription(label) => {
                platform::set_accessibility_label(view, label, mtm);
            }
            ref other => platform::warn_unexpected_setter(KIND, other),
        }
    }
}

#[cfg(target_os = "macos")]
pub(crate) mod platform {
    //! The macOS half: build an `NSDatePicker` showing year/month/day only
    //! and apply the shared plan — no echo guard of its own (AppKit sends no
    //! action for a programmatic `setDateValue:`; `crate::appkit::events`'
    //! *No echo guard*).
    //!
    //! # Construction-time normalization
    //!
    //! `create` pins single-date mode, the `YearMonthDay` elements (no
    //! time), and the [`DatePickerProps::platform_default`] `Compact`
    //! presentation (`textFieldAndStepper` with the calendar overlay on)
    //! before the diffed create plan runs.
    //!
    //! # One action, one kind
    //!
    //! The picker's single target/action pair is wired with
    //! [`crate::events::EVENT_KIND_DATE`]; `frustAction:` reads the sender's
    //! `dateValue`, converts it through [`super::foundation`] and packs it
    //! with [`crate::events::pack_date`], and `on_event` decodes it through
    //! the SAME [`decode_event`] the other two arms call.

    use objc2::rc::Retained;
    use objc2_app_kit::{
        NSColor, NSDatePicker, NSDatePickerElementFlags, NSDatePickerMode,
        NSDatePickerStyle as AppKitStyle,
    };

    use super::foundation::{ns_date, optional_ns_date};
    use super::{Bounds, DatePicker, DatePickerProps, DatePickerStyle, KIND, decode_event};
    use crate::NativeWidgetError;
    use crate::appkit::{FrustNativeControlTarget, NativeCtx, NativeView};
    use crate::controls::platform;
    use crate::controls::{Plan, Setter};
    use crate::events::{EVENT_KIND_DATE, EventPayload};
    use crate::runtime::{NativeEvent, NativeWidget, Params};

    /// A live picker's retained state — the iOS arm's shape.
    pub(crate) struct DatePickerState {
        /// The picker, kept typed for its own date/range setters.
        view: Retained<NSDatePicker>,
        /// The target `create` attached. `NSControl.target` is weak, so this
        /// field is its only retain (`crate::appkit::events`' *Target
        /// retention*).
        target: Retained<FrustNativeControlTarget>,
        /// The date the platform last reported, `None` while untouched —
        /// [`DatePickerProps::plan`]'s write-back drift signal.
        observed: Option<super::CivilDate>,
    }

    impl NativeWidget for DatePicker {
        type Props = DatePickerProps;
        type State = DatePickerState;

        fn decode_props(params: &Params<'_>) -> Result<Self::Props, NativeWidgetError> {
            DatePickerProps::decode(params)
        }

        fn create(
            ctx: &mut NativeCtx<'_, '_>,
            props: &Self::Props,
        ) -> Result<(NativeView, Self::State), NativeWidgetError> {
            let mtm = ctx.mtm();
            let view = NSDatePicker::new(mtm);
            let default = DatePickerProps::platform_default(props.slot);
            // Module doc's *Construction-time normalization*.
            view.setDatePickerMode(NSDatePickerMode::Single);
            view.setDatePickerElements(NSDatePickerElementFlags::YearMonthDay);
            set_style(&view, default.style);
            let plan = DatePickerProps::plan(&default, props, None, Bounds::APPLE);
            apply_all(&view, &plan);
            // Attached after the initial plan, the other controls' order.
            let target = FrustNativeControlTarget::attach(mtm, &view, props.slot, EVENT_KIND_DATE);
            let handle = NativeView::new(Retained::clone(&view).into_super().into_super(), mtm);
            Ok((
                handle,
                DatePickerState {
                    view,
                    target,
                    observed: None,
                },
            ))
        }

        fn update(
            _ctx: &mut NativeCtx<'_, '_>,
            state: &mut Self::State,
            old: &Self::Props,
            new: &Self::Props,
        ) -> Result<(), NativeWidgetError> {
            apply_all(
                &state.view,
                &DatePickerProps::plan(old, new, state.observed, Bounds::APPLE),
            );
            // Cleared unconditionally, as on iOS: nothing here can fail.
            state.observed = None;
            Ok(())
        }

        fn on_event(state: &mut Self::State, event: NativeEvent) -> Option<EventPayload> {
            decode_event(&mut state.observed, event)
        }

        fn dispose(
            _ctx: &mut NativeCtx<'_, '_>,
            state: Self::State,
        ) -> Result<(), NativeWidgetError> {
            // Detach so a stray in-flight action can't reach a torn-down
            // slot; dropping `state` afterwards releases the target's retain.
            state.target.detach(&state.view);
            Ok(())
        }
    }

    /// Apply `style` — module doc's table (top of file): AppKit has no
    /// wheels, so `Wheels` is the plain text field and stepper, and
    /// `Compact` adds the click-to-open calendar overlay.
    fn set_style(view: &NSDatePicker, style: DatePickerStyle) {
        let (appkit, overlay) = match style {
            DatePickerStyle::Compact => (AppKitStyle::TextFieldAndStepper, true),
            DatePickerStyle::Wheels => (AppKitStyle::TextFieldAndStepper, false),
            DatePickerStyle::Inline => (AppKitStyle::ClockAndCalendar, false),
        };
        view.setDatePickerStyle(appkit);
        view.setPresentsCalendarOverlay(overlay);
    }

    /// Execute a whole [`Plan`], front to back.
    fn apply_all(view: &NSDatePicker, plan: &Plan<'_>) {
        for setter in plan {
            apply(view, setter);
        }
    }

    /// Execute one planned property write against `view`.
    fn apply(view: &NSDatePicker, setter: &Setter<'_>) {
        match *setter {
            // `setDateValue:` sends no action (module doc's echo guard).
            Setter::Date(date) => match ns_date(date) {
                Some(ns) => view.setDateValue(&ns),
                None => log::warn!(
                    "frust-native-widgets: macOS could not build an NSDate for {date} — not \
                     applied"
                ),
            },
            Setter::MinDate(min) => view.setMinDate(optional_ns_date(min).as_deref()),
            Setter::MaxDate(max) => view.setMaxDate(optional_ns_date(max).as_deref()),
            Setter::DatePickerStyle(style) => set_style(view, style),
            Setter::Enabled(enabled) => platform::set_enabled(view, enabled),
            // No AppKit tint on `NSDatePicker` — `set_tint`'s generic "this
            // view has no tint property" branch logs it (module doc's
            // *Theme*).
            Setter::DatePickerTint(argb) => platform::set_tint(view, "DatePickerTint", argb),
            Setter::DatePickerTextColor(argb) => {
                let color = argb.map_or_else(NSColor::controlTextColor, platform::ns_color);
                view.setTextColor(&color);
            }
            Setter::ContentDescription(label) => platform::set_accessibility_label(view, label),
            ref other => platform::warn_unexpected_setter(KIND, other),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::controls::Tier;
    use crate::runtime::with_identity;

    fn date(year: i32, month: u8, day: u8) -> CivilDate {
        CivilDate::new(year, month, day).expect("a real date")
    }

    fn decode(body: &str) -> DatePickerProps {
        let raw = with_identity(KIND, 5, body);
        DatePickerProps::decode(&Params::new(&raw)).expect("decodes")
    }

    fn field(key: &str, value: CivilDate) -> String {
        format!("\"{key}\":{}", wire(value))
    }

    /// The Android arm's own [`Bounds`] (`platform::BOUNDS`, compiled only
    /// under `target_os = "android"`) — duplicated here so the ordering
    /// fix is host-testable on every target, matching that module's
    /// documented 1900-01-01/2100-12-31 literal values.
    fn android_bounds() -> Bounds {
        Bounds {
            floor: date(1900, 1, 1),
            ceiling: date(2100, 12, 31),
        }
    }

    // --- CivilDate ------------------------------------------------------

    #[test]
    fn civil_date_validates_every_field_and_the_month_length() {
        assert!(CivilDate::new(1, 1, 1).is_some());
        assert!(CivilDate::new(9999, 12, 31).is_some());
        assert!(CivilDate::new(0, 1, 1).is_none(), "year 0");
        assert!(CivilDate::new(10_000, 1, 1).is_none(), "year 10000");
        assert!(CivilDate::new(-1, 1, 1).is_none(), "negative year");
        assert!(CivilDate::new(2026, 0, 1).is_none(), "month 0");
        assert!(CivilDate::new(2026, 13, 1).is_none(), "month 13");
        assert!(CivilDate::new(2026, 1, 0).is_none(), "day 0");
        assert!(CivilDate::new(2026, 1, 32).is_none(), "day 32");
        assert!(CivilDate::new(2026, 4, 31).is_none(), "31 April");
        assert!(CivilDate::new(2024, 2, 29).is_some(), "leap year");
        assert!(CivilDate::new(2000, 2, 29).is_some(), "400-year leap");
        assert!(CivilDate::new(1900, 2, 29).is_none(), "century non-leap");
        assert!(CivilDate::new(2026, 2, 29).is_none(), "common year");
        assert_eq!(CivilDate::MIN, date(1, 1, 1));
        assert_eq!(CivilDate::MAX, date(9999, 12, 31));
    }

    #[test]
    fn civil_dates_order_chronologically_and_display_as_iso_8601() {
        assert!(date(2026, 1, 31) < date(2026, 2, 1));
        assert!(date(2025, 12, 31) < date(2026, 1, 1));
        assert_eq!(date(7, 3, 9).to_string(), "0007-03-09");
        assert_eq!(date(2026, 9, 29).to_string(), "2026-09-29");
    }

    // --- decode ---------------------------------------------------------

    #[test]
    fn absent_fields_decode_to_the_platform_defaults_and_plan_nothing() {
        let props = decode("");
        assert_eq!(props, DatePickerProps::platform_default(5));
        assert!(
            DatePickerProps::plan(
                &DatePickerProps::platform_default(5),
                &props,
                None,
                Bounds::APPLE
            )
            .is_empty()
        );
    }

    #[test]
    fn dates_decode_from_their_packed_wire_integers() {
        let props = decode(&format!(
            "{},{},{},\"style\":\"inline\",\"enabled\":false,\"tint\":7,\"textColor\":8",
            field(DATE, date(2026, 9, 29)),
            field(MIN_DATE, date(2026, 1, 1)),
            field(MAX_DATE, date(2026, 12, 31)),
        ));
        assert_eq!(props.date, Some(date(2026, 9, 29)));
        assert_eq!(props.min, Some(date(2026, 1, 1)));
        assert_eq!(props.max, Some(date(2026, 12, 31)));
        assert_eq!(props.style, DatePickerStyle::Inline);
        assert!(!props.enabled);
        assert_eq!(props.tint, Some(7));
        assert_eq!(props.text_color, Some(8));
    }

    #[test]
    fn an_invalid_wire_date_decodes_as_absent() {
        // 31 April, packed by hand — never a date the platform is handed.
        let props = decode(&format!("\"date\":{}", (2026 << 16) | (4 << 8) | 31));
        assert_eq!(props.date, None);
        let negative = decode("\"minDate\":-5,\"maxDate\":0");
        assert_eq!((negative.min, negative.max), (None, None));
    }

    #[test]
    fn an_unknown_style_decodes_to_compact() {
        assert_eq!(
            decode("\"style\":\"sideways\"").style,
            DatePickerStyle::Compact
        );
        assert_eq!(
            decode("\"style\":\"wheels\"").style,
            DatePickerStyle::Wheels
        );
    }

    #[test]
    fn the_date_is_clamped_into_the_range_on_decode() {
        let before = decode(&format!(
            "{},{}",
            field(DATE, date(2020, 5, 5)),
            field(MIN_DATE, date(2026, 1, 1))
        ));
        assert_eq!(before.date, Some(date(2026, 1, 1)));
        let after = decode(&format!(
            "{},{}",
            field(DATE, date(2030, 5, 5)),
            field(MAX_DATE, date(2026, 12, 31))
        ));
        assert_eq!(after.date, Some(date(2026, 12, 31)));
    }

    #[test]
    fn an_inverted_range_degrades_to_the_single_day_min() {
        let props = decode(&format!(
            "{},{},{}",
            field(DATE, date(2026, 6, 1)),
            field(MIN_DATE, date(2026, 12, 1)),
            field(MAX_DATE, date(2026, 1, 1)),
        ));
        assert_eq!(props.min, Some(date(2026, 12, 1)));
        assert_eq!(props.max, Some(date(2026, 12, 1)));
        assert_eq!(props.date, Some(date(2026, 12, 1)));
    }

    // --- plan -----------------------------------------------------------

    #[test]
    fn the_create_plan_sets_exactly_the_non_default_fields_in_order() {
        let props = decode(&format!(
            "{},{},{},\"style\":\"wheels\",\"enabled\":false,\"tint\":1,\"textColor\":2,\
             \"contentDescription\":\"birthday\"",
            field(DATE, date(2026, 9, 29)),
            field(MIN_DATE, date(2000, 1, 1)),
            field(MAX_DATE, date(2030, 12, 31)),
        ));
        assert_eq!(
            DatePickerProps::plan(
                &DatePickerProps::platform_default(5),
                &props,
                None,
                Bounds::APPLE
            ),
            vec![
                Setter::DatePickerStyle(DatePickerStyle::Wheels),
                Setter::MinDate(Some(date(2000, 1, 1))),
                Setter::MaxDate(Some(date(2030, 12, 31))),
                Setter::Date(date(2026, 9, 29)),
                Setter::Enabled(false),
                Setter::DatePickerTint(Some(1)),
                Setter::DatePickerTextColor(Some(2)),
                Setter::ContentDescription(Some("birthday")),
            ]
        );
    }

    #[test]
    fn a_date_change_alone_plans_exactly_one_setter() {
        let old = decode(&field(DATE, date(2026, 9, 29)));
        let new = decode(&field(DATE, date(2026, 9, 30)));
        assert_eq!(
            DatePickerProps::plan(&old, &new, None, Bounds::APPLE),
            vec![Setter::Date(date(2026, 9, 30))]
        );
        assert!(
            DatePickerProps::plan(&new, &new, None, Bounds::APPLE).is_empty(),
            "unchanged props plan nothing — the zero-FFI property"
        );
    }

    #[test]
    fn a_pick_the_app_confirmed_writes_the_date_back_once() {
        let before = decode(&field(DATE, date(2026, 9, 29)));
        let after = decode(&field(DATE, date(2026, 10, 3)));
        assert_eq!(
            DatePickerProps::plan(&before, &after, Some(date(2026, 10, 3)), Bounds::APPLE),
            vec![Setter::Date(date(2026, 10, 3))]
        );
    }

    #[test]
    fn a_platform_drift_is_written_back_even_when_the_props_date_did_not_change() {
        // The user picked 3 October; the app kept 29 September and changed
        // something else — the picker must snap back.
        let old = decode(&field(DATE, date(2026, 9, 29)));
        let new = decode(&format!(
            "{},\"enabled\":false",
            field(DATE, date(2026, 9, 29))
        ));
        assert_eq!(
            DatePickerProps::plan(&old, &new, Some(date(2026, 10, 3)), Bounds::APPLE),
            vec![Setter::Date(date(2026, 9, 29)), Setter::Enabled(false)],
            "the app rejected the pick: the confirmed date is re-asserted"
        );
        assert_eq!(
            DatePickerProps::plan(&old, &new, Some(date(2026, 9, 29)), Bounds::APPLE),
            vec![Setter::Enabled(false)],
            "an observed date matching the app's is no drift"
        );
    }

    #[test]
    fn a_range_that_moves_later_writes_the_ceiling_first() {
        let old = decode(&format!(
            "{},{},{}",
            field(DATE, date(2026, 1, 15)),
            field(MIN_DATE, date(2026, 1, 1)),
            field(MAX_DATE, date(2026, 1, 31)),
        ));
        let new = decode(&format!(
            "{},{},{}",
            field(DATE, date(2026, 3, 15)),
            field(MIN_DATE, date(2026, 3, 1)),
            field(MAX_DATE, date(2026, 3, 31)),
        ));
        assert_eq!(
            DatePickerProps::plan(&old, &new, None, Bounds::APPLE),
            vec![
                Setter::MaxDate(Some(date(2026, 3, 31))),
                Setter::MinDate(Some(date(2026, 3, 1))),
                Setter::Date(date(2026, 3, 15)),
            ],
            "floor-first would pass through [March 1, January 31] — the \
             non-crossing case: the Apple bounds' unbounded ceiling never \
             enters the comparison"
        );
    }

    #[test]
    fn a_range_that_moves_earlier_writes_the_floor_first() {
        let old = decode(&format!(
            "{},{}",
            field(MIN_DATE, date(2026, 3, 1)),
            field(MAX_DATE, date(2026, 3, 31)),
        ));
        let new = decode(&format!(
            "{},{}",
            field(MIN_DATE, date(2026, 1, 1)),
            field(MAX_DATE, date(2026, 1, 31)),
        ));
        assert_eq!(
            DatePickerProps::plan(&old, &new, None, Bounds::APPLE),
            vec![
                Setter::MinDate(Some(date(2026, 1, 1))),
                Setter::MaxDate(Some(date(2026, 1, 31))),
            ],
            "ceiling-first would pass through [March 1, January 31]"
        );
    }

    #[test]
    fn a_none_ceiling_crosses_below_an_explicit_old_ceiling_on_android_only() {
        // `old.max` (2150-01-01) is explicit and, unclamped, ABOVE Android's
        // own ceiling — but `plan` now clamps every explicit bound into the
        // arm's own range (module doc's *Range*) before comparing, so the
        // platform never actually held 2150-01-01: it held the clamped
        // 2100-12-31, the exact value `new.max = None` resolves to on this
        // arm. The effective ceiling is therefore unchanged and only the
        // floor moves. The Apple bounds never clamp anything here
        // (2150-01-01 is inside `CivilDate::MIN..CivilDate::MAX`), so there
        // `None` genuinely widens the ceiling (resolving to
        // `CivilDate::MAX`, above the old explicit 2150-01-01) and it is
        // written first — the two arms disagree on order for the exact same
        // props.
        let old = decode(&format!(
            "{},{}",
            field(MIN_DATE, date(2095, 1, 1)),
            field(MAX_DATE, date(2150, 1, 1)),
        ));
        let new = decode(&field(MIN_DATE, date(2050, 1, 1)));
        assert_eq!(new.max, None);

        assert_eq!(
            DatePickerProps::plan(&old, &new, None, android_bounds()),
            vec![Setter::MinDate(Some(date(2050, 1, 1)))],
            "old.max's clamped ceiling (2100-12-31) equals new's resolved \
             None default — no MaxDate setter at all, only the floor moves"
        );
        assert_eq!(
            DatePickerProps::plan(&old, &new, None, Bounds::APPLE),
            vec![
                Setter::MaxDate(None),
                Setter::MinDate(Some(date(2050, 1, 1))),
            ],
            "Apple's None ceiling (CivilDate::MAX) is still >= the old one \
             — a widen, so the ceiling moves first; the two arms disagree \
             on order for the exact same props"
        );
    }

    #[test]
    fn planning_with_an_inverted_resolved_range_does_not_panic() {
        // An app setting min to 2150-01-01 with no max is valid API input
        // on Apple (ceiling 9999-12-31) but resolves inverted for Android's
        // own 1900-01-01..2100-12-31 default. `plan` clamps the explicit
        // bound into the arm's range rather than hand an inverted pair to
        // the platform's own setter.
        let old = DatePickerProps::platform_default(7);
        let new = decode(&field(MIN_DATE, date(2150, 1, 1)));
        let plan = DatePickerProps::plan(&old, &new, None, android_bounds());
        // The warning is logged but the plan proceeds with the clamped
        // setter.
        assert_eq!(plan, vec![Setter::MinDate(Some(date(2100, 12, 31)))]);
    }

    #[test]
    fn an_explicit_min_above_androids_ceiling_clamps_the_bound_and_the_date() {
        let old = DatePickerProps::platform_default(9);
        let new = decode(&format!(
            "{},{}",
            field(MIN_DATE, date(2150, 1, 1)),
            field(DATE, date(2150, 6, 1)),
        ));
        assert_eq!(
            DatePickerProps::plan(&old, &new, None, android_bounds()),
            vec![
                Setter::MinDate(Some(date(2100, 12, 31))),
                Setter::Date(date(2100, 12, 31)),
            ],
            "an explicit min above Android's own ceiling clamps into it, \
             and a date later than the clamped ceiling clamps with it — the \
             platform is never asked for a date outside the range it will \
             hold"
        );
    }

    #[test]
    fn an_explicit_max_below_androids_floor_clamps_the_bound() {
        let old = DatePickerProps::platform_default(9);
        let new = decode(&field(MAX_DATE, date(1850, 1, 1)));
        assert_eq!(
            DatePickerProps::plan(&old, &new, None, android_bounds()),
            vec![Setter::MaxDate(Some(date(1900, 1, 1)))],
            "an explicit max below Android's own floor clamps up into it"
        );
    }

    #[test]
    fn the_same_out_of_androids_range_bounds_are_not_clamped_on_apple() {
        let old = DatePickerProps::platform_default(9);
        let min_only = decode(&field(MIN_DATE, date(2150, 1, 1)));
        assert_eq!(
            DatePickerProps::plan(&old, &min_only, None, Bounds::APPLE),
            vec![Setter::MinDate(Some(date(2150, 1, 1)))],
            "2150-01-01 is well inside CivilDate::MIN..CivilDate::MAX — \
             Apple's own unbounded range — so nothing clamps it"
        );
        let max_only = decode(&field(MAX_DATE, date(1850, 1, 1)));
        assert_eq!(
            DatePickerProps::plan(&old, &max_only, None, Bounds::APPLE),
            vec![Setter::MaxDate(Some(date(1850, 1, 1)))],
            "1850-01-01 is well inside CivilDate::MIN..CivilDate::MAX, so \
             nothing clamps it on Apple either"
        );
    }

    #[test]
    fn a_range_change_reasserts_an_unchanged_date() {
        let old = decode(&format!(
            "{},{}",
            field(DATE, date(2026, 6, 15)),
            field(MIN_DATE, date(2026, 1, 1))
        ));
        let new = decode(&format!(
            "{},{}",
            field(DATE, date(2026, 6, 15)),
            field(MIN_DATE, date(2026, 6, 1))
        ));
        assert_eq!(
            DatePickerProps::plan(&old, &new, None, Bounds::APPLE),
            vec![
                Setter::MinDate(Some(date(2026, 6, 1))),
                Setter::Date(date(2026, 6, 15)),
            ]
        );
    }

    #[test]
    fn clearing_a_bound_and_the_colours_plans_the_nullable_setters() {
        let set = decode(&format!(
            "{},\"tint\":1,\"textColor\":2",
            field(MAX_DATE, date(2026, 12, 31))
        ));
        let cleared = decode("");
        assert_eq!(
            DatePickerProps::plan(&set, &cleared, None, Bounds::APPLE),
            vec![
                Setter::MaxDate(None),
                Setter::DatePickerTint(None),
                Setter::DatePickerTextColor(None),
            ]
        );
    }

    #[test]
    fn every_planned_setter_reports_its_documented_tier() {
        let props = decode(&format!(
            "{},{},{},\"style\":\"inline\",\"enabled\":false,\"tint\":1,\"textColor\":2,\
             \"contentDescription\":\"d\"",
            field(DATE, date(2026, 9, 29)),
            field(MIN_DATE, date(2000, 1, 1)),
            field(MAX_DATE, date(2030, 12, 31)),
        ));
        for setter in DatePickerProps::plan(
            &DatePickerProps::platform_default(5),
            &props,
            None,
            Bounds::APPLE,
        ) {
            let expected = if matches!(
                setter,
                Setter::MinDate(_) | Setter::MaxDate(_) | Setter::DatePickerStyle(_)
            ) {
                Tier::Relayout
            } else {
                Tier::Cheap
            };
            assert_eq!(setter.tier(), expected, "{setter:?}");
        }
    }

    // --- effective_date --------------------------------------------------

    #[test]
    fn effective_date_with_android_bounds_clamps_out_of_range_dates() {
        let props = decode(&field(DATE, date(2150, 6, 1)));
        let clamped = props.effective_date(android_bounds());
        assert_eq!(
            clamped,
            Some(date(2100, 12, 31)),
            "2150-06-01 is outside Android's 1900-01-01..2100-12-31 range, \
             clamped to the ceiling"
        );
    }

    #[test]
    fn effective_date_with_android_bounds_and_explicit_min_still_clamps() {
        let props = decode(&format!(
            "{},{}",
            field(DATE, date(2150, 6, 1)),
            field(MIN_DATE, date(2050, 1, 1))
        ));
        let clamped = props.effective_date(android_bounds());
        assert_eq!(
            clamped,
            Some(date(2100, 12, 31)),
            "with an explicit min, the date 2150-06-01 still clamps to \
             Android's ceiling 2100-12-31"
        );
    }

    #[test]
    fn effective_date_is_identity_with_apple_bounds() {
        let date_to_test = date(2150, 6, 1);
        let props = decode(&field(DATE, date_to_test));
        let result = props.effective_date(Bounds::APPLE);
        assert_eq!(
            result,
            Some(date_to_test),
            "2150-06-01 is inside Apple's CivilDate::MIN..CivilDate::MAX, \
             so effective_date returns it unchanged"
        );
    }

    #[test]
    fn effective_date_equals_the_date_setter_in_plan_table_driven() {
        // Test structure: (bounds_name, bounds, min, max, date, description)
        // Each case tests both dates inside and outside the effective range.
        struct TestCase {
            name: &'static str,
            bounds: Bounds,
            min: Option<CivilDate>,
            max: Option<CivilDate>,
            date_in_range: CivilDate,
            date_out_of_range: CivilDate,
        }

        let test_cases = vec![
            // Android bounds cases
            TestCase {
                name: "android_no_bounds",
                bounds: android_bounds(),
                min: None,
                max: None,
                date_in_range: date(2026, 6, 1),
                date_out_of_range: date(2150, 6, 1), // above ceiling
            },
            TestCase {
                name: "android_min_only",
                bounds: android_bounds(),
                min: Some(date(2050, 1, 1)),
                max: None,
                date_in_range: date(2050, 6, 1),
                date_out_of_range: date(1950, 6, 1), // below min
            },
            TestCase {
                name: "android_max_only",
                bounds: android_bounds(),
                min: None,
                max: Some(date(2050, 12, 31)),
                date_in_range: date(2050, 6, 1),
                date_out_of_range: date(2150, 6, 1), // above max
            },
            TestCase {
                name: "android_both_explicit",
                bounds: android_bounds(),
                min: Some(date(2050, 1, 1)),
                max: Some(date(2050, 12, 31)),
                date_in_range: date(2050, 6, 1),
                date_out_of_range: date(2150, 6, 1), // above max
            },
            TestCase {
                name: "android_floor_collapsed",
                bounds: android_bounds(),
                min: Some(date(2150, 1, 1)), // above ceiling, collapses to ceiling
                max: None,
                date_in_range: date(2100, 12, 31), // at the collapsed floor/ceiling
                date_out_of_range: date(2026, 6, 1), // below the collapsed range
            },
            // Apple bounds cases
            TestCase {
                name: "apple_no_bounds",
                bounds: Bounds::APPLE,
                min: None,
                max: None,
                date_in_range: date(2026, 6, 1),
                date_out_of_range: date(9999, 12, 31), // at the ceiling (still in range for Apple)
            },
            TestCase {
                name: "apple_min_only",
                bounds: Bounds::APPLE,
                min: Some(date(2050, 1, 1)),
                max: None,
                date_in_range: date(2050, 6, 1),
                date_out_of_range: date(1950, 6, 1), // below min
            },
            TestCase {
                name: "apple_max_only",
                bounds: Bounds::APPLE,
                min: None,
                max: Some(date(2050, 12, 31)),
                date_in_range: date(2050, 6, 1),
                date_out_of_range: date(2150, 6, 1), // above max
            },
            TestCase {
                name: "apple_both_explicit",
                bounds: Bounds::APPLE,
                min: Some(date(2050, 1, 1)),
                max: Some(date(2050, 12, 31)),
                date_in_range: date(2050, 6, 1),
                date_out_of_range: date(2150, 6, 1), // above max
            },
            TestCase {
                name: "apple_floor_collapsed",
                bounds: Bounds::APPLE,
                min: Some(date(2150, 1, 1)), // inverted with max below
                max: Some(date(2050, 12, 31)),
                date_in_range: date(2050, 12, 31), // at the collapsed floor/ceiling
                date_out_of_range: date(2026, 6, 1), // below the collapsed range
            },
        ];

        for tc in test_cases {
            // Test date inside effective range
            let props_in = decode(&format!(
                "{}{}{}",
                tc.min
                    .map(|m| format!("\"minDate\":{},", wire(m)))
                    .unwrap_or_default(),
                tc.max
                    .map(|m| format!("\"maxDate\":{},", wire(m)))
                    .unwrap_or_default(),
                field(DATE, tc.date_in_range)
            ));

            let effective_in = props_in.effective_date(tc.bounds);
            let plan_in = DatePickerProps::plan(
                &DatePickerProps::platform_default(5),
                &props_in,
                None,
                tc.bounds,
            );

            let date_setter_in = plan_in.iter().find_map(|s| {
                if let Setter::Date(d) = s {
                    Some(*d)
                } else {
                    None
                }
            });

            assert_eq!(
                date_setter_in, effective_in,
                "{}: plan's Date setter matches effective_date for date inside range",
                tc.name
            );

            // Test date outside effective range (gets clamped)
            let props_out = decode(&format!(
                "{}{}{}",
                tc.min
                    .map(|m| format!("\"minDate\":{},", wire(m)))
                    .unwrap_or_default(),
                tc.max
                    .map(|m| format!("\"maxDate\":{},", wire(m)))
                    .unwrap_or_default(),
                field(DATE, tc.date_out_of_range)
            ));

            let effective_out = props_out.effective_date(tc.bounds);
            let plan_out = DatePickerProps::plan(
                &DatePickerProps::platform_default(5),
                &props_out,
                None,
                tc.bounds,
            );

            let date_setter_out = plan_out.iter().find_map(|s| {
                if let Setter::Date(d) = s {
                    Some(*d)
                } else {
                    None
                }
            });

            assert_eq!(
                date_setter_out, effective_out,
                "{}: plan's Date setter matches effective_date for date outside range (clamped)",
                tc.name
            );

            // Test that unchanged date from old props does not emit a Date setter
            let old_with_date = decode(&format!(
                "{}{}{}",
                tc.min
                    .map(|m| format!("\"minDate\":{},", wire(m)))
                    .unwrap_or_default(),
                tc.max
                    .map(|m| format!("\"maxDate\":{},", wire(m)))
                    .unwrap_or_default(),
                field(DATE, tc.date_in_range)
            ));
            let new_with_same_date = old_with_date.clone();

            let plan_unchanged =
                DatePickerProps::plan(&old_with_date, &new_with_same_date, None, tc.bounds);

            let has_date_setter = plan_unchanged.iter().any(|s| matches!(s, Setter::Date(_)));
            assert!(
                !has_date_setter,
                "{}: unchanged date should not emit Date setter",
                tc.name
            );
        }
    }

    // --- events ---------------------------------------------------------

    fn picked(date: CivilDate) -> NativeEvent {
        NativeEvent {
            kind: EVENT_KIND_DATE,
            detail: pack_date(date),
        }
    }

    #[test]
    fn a_user_pick_decodes_and_updates_the_drift_signal() {
        let mut observed = None;
        assert_eq!(
            decode_event(&mut observed, picked(date(2026, 10, 3))),
            Some(EventPayload::Date(date(2026, 10, 3)))
        );
        assert_eq!(observed, Some(date(2026, 10, 3)));
    }

    #[test]
    fn an_invalid_report_decodes_to_nothing_and_leaves_observed_untouched() {
        let mut observed = Some(date(2026, 1, 1));
        let corrupt = NativeEvent {
            kind: EVENT_KIND_DATE,
            detail: (2026 << 16) | (2 << 8) | 30,
        };
        assert_eq!(decode_event(&mut observed, corrupt), None);
        assert_eq!(observed, Some(date(2026, 1, 1)));
    }

    #[test]
    fn a_misrouted_kind_decodes_to_nothing() {
        let mut observed = None;
        let selection = NativeEvent {
            kind: crate::events::EVENT_KIND_SELECTION,
            detail: pack_date(date(2026, 1, 1)),
        };
        assert_eq!(decode_event(&mut observed, selection), None);
        assert_eq!(observed, None);
    }

    // There is no per-instance suppression parameter to test an echo
    // against: `DatePicker.updateDate`'s listener notification is
    // synchronous, so the ONLY guard against a `Setter::Date` echo is
    // `crate::runtime::with_runtime`'s re-entrancy drop one layer up
    // (module doc's *Echo guard*) — pinned by
    // `runtime::tests::the_thread_local_runtime_is_reentrancy_tolerant`,
    // exactly as `slider.rs`'s tests note for `Setter::Progress`.
}