voxel-framework 0.12.3

A reusable voxel engine framework built on Bevy
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
//! Optional pause menu with a settings submenu for FOV and SFX volume.
//!
//! This module implements a self-contained pause flow driven by the
//! [`PauseMenuState`] state machine. Add [`PauseMenuPlugin`] to wire it up;
//! then gate your own gameplay systems on [`PauseMenuState::Playing`] so they
//! freeze automatically when the player pauses.
//!
//! # State machine
//!
//! ```text
//!                  Escape
//! ┌─────────┐ ──────────────► ┌────────┐
//! │ Playing │                 │ Paused │ ◄─────────────────┐
//! └─────────┘ ◄────────────── └────────┘                   │
//!                Resume btn /       │ Settings btn          │
//!                Escape             ▼                       │
//!                             ┌──────────┐  ← Back btn     │
//!                             │ Settings │ ────────────────►┘
//!                             └──────────┘
//! ```
//!
//! **Cursor management:** entering `Paused` releases the primary window's
//! cursor (`CursorGrabMode::None`, visible). Returning to `Playing` re-locks
//! it (`CursorGrabMode::Locked`, hidden) when the window is focused.
//!
//! This plugin does not capture the cursor on the first click or release it
//! when the window loses focus. Add
//! [`PlayerPlugin`](crate::player::PlayerPlugin), or
//! [`player_cursor_system`](crate::player::player_cursor_system) on its own,
//! for that: when this plugin is installed the cursor system leaves Escape to
//! the pause menu, so the two work together.
//!
//! # Integration
//!
//! [`PlayerPlugin`](crate::player::PlayerPlugin) pauses with the menu on its
//! own. Gate your other gameplay systems on [`PauseMenuState::Playing`]:
//!
//! ```rust,no_run
//! use bevy::prelude::*;
//! use voxel_framework::prelude::*;
//! use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
//!
//! fn my_gameplay_system() {}
//!
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
//!     .add_plugins(PauseMenuPlugin)
//!     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
//!     .add_systems(Update, my_gameplay_system.run_if(in_state(PauseMenuState::Playing)));
//! ```

use bevy::asset::embedded_asset;
use bevy::prelude::*;

use crate::audio::{SfxConfig, SfxEvent, SfxRequest};
use crate::player::{Player, PlayerConfig};
use crate::world::{ChunkManager, WorldConfig};

/// Asset path of the NotoSans font embedded into the framework binary.
///
/// The `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin`
/// (part of `AssetPlugin` / `DefaultPlugins`). The path format is
/// `embedded://{crate_name}/{path relative to the crate's `src/` dir}`, where
/// the crate name uses underscores. See [`PauseMenuPlugin`] for how this font
/// becomes the default value of [`PauseMenuConfig::font`].
pub const EMBEDDED_NOTO_SANS_PATH: &str = "embedded://voxel_framework/ui/NotoSans-Regular.ttf";

/// Asset path of the NotoSansSymbols2 font embedded into the framework binary.
///
/// Used exclusively to render symbol glyphs (e.g. `◀`, `▶`) that are absent
/// from the subset of NotoSans shipped at [`EMBEDDED_NOTO_SANS_PATH`]. The
/// `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin` (part
/// of `AssetPlugin` / `DefaultPlugins`).
pub const EMBEDDED_NOTO_SYMBOLS_PATH: &str =
    "embedded://voxel_framework/ui/NotoSansSymbols2-Regular.ttf";

// ─── State ────────────────────────────────────────────────────────────────────

/// Bevy state enum that drives the pause menu lifecycle.
///
/// [`PauseMenuPlugin`] registers this as a Bevy `State` and transitions between
/// variants automatically. Your own systems should use `run_if(in_state(…))`
/// to participate in the pause flow.
///
/// # Variant transitions
///
/// | From | Trigger | To |
/// |------|---------|-----|
/// | `Playing` | Escape key | `Paused` |
/// | `Paused` | Resume button or Escape | `Playing` |
/// | `Paused` | Settings button | `Settings` |
/// | `Settings` | Back button | `Paused` |
///
/// # Gating gameplay systems
///
/// ```rust,no_run
/// # use bevy::prelude::*;
/// # use voxel_framework::ui::PauseMenuState;
/// # fn my_gameplay_system() {}
/// App::new()
///     .add_systems(Update,
///         my_gameplay_system.run_if(in_state(PauseMenuState::Playing)),
///     );
/// ```
#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum PauseMenuState {
    /// The game is running normally. Player input is active and the pause
    /// menu is not visible. This is the default starting state.
    #[default]
    Playing,
    /// The game is paused. The pause menu overlay is displayed and gameplay
    /// systems gated on `Playing` are inactive. The cursor is free.
    Paused,
    /// The settings submenu is open. The pause menu overlay is replaced by the
    /// settings panel. FOV and SFX volume can be adjusted here.
    Settings,
}

// ─── Theme ────────────────────────────────────────────────────────────────────

/// Colors of one kind of menu button, per interaction state.
///
/// Used by [`PauseMenuTheme::button`] and
/// [`PauseMenuTheme::secondary_button`]. The default is the dark blue-grey
/// button with white text that the pause menu has always drawn.
///
/// | Field     | Default                         |
/// |-----------|---------------------------------|
/// | `normal`  | `Color::srgb(0.15, 0.15, 0.20)` |
/// | `hovered` | `Color::srgb(0.25, 0.25, 0.35)` |
/// | `pressed` | `Color::srgb(0.35, 0.35, 0.50)` |
/// | `text`    | `Color::WHITE`                  |
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ButtonColors {
    /// Background while the pointer is elsewhere.
    pub normal: Color,
    /// Background while the pointer is over the button.
    pub hovered: Color,
    /// Background while the button is held down.
    pub pressed: Color,
    /// Color of the button's label. It does not change with the interaction
    /// state.
    pub text: Color,
}

impl ButtonColors {
    /// Background color for an interaction state: `normal` for
    /// [`Interaction::None`], `hovered` for [`Interaction::Hovered`] and
    /// `pressed` for [`Interaction::Pressed`].
    pub fn background(&self, interaction: Interaction) -> Color {
        match interaction {
            Interaction::None => self.normal,
            Interaction::Hovered => self.hovered,
            Interaction::Pressed => self.pressed,
        }
    }
}

impl Default for ButtonColors {
    fn default() -> Self {
        Self {
            normal: Color::srgb(0.15, 0.15, 0.20),
            hovered: Color::srgb(0.25, 0.25, 0.35),
            pressed: Color::srgb(0.35, 0.35, 0.50),
            text: Color::WHITE,
        }
    }
}

/// Colors and panel layout of the pause menu and its settings submenu.
///
/// Insert this resource to restyle the menus drawn by [`PauseMenuPlugin`];
/// the plugin initializes it with [`Default`] when the game has not inserted
/// one, and never replaces one that is already there. The default reproduces
/// the look the menu had before this resource existed: white text and dark
/// buttons straight on a dimmed scene, with an invisible panel that is as
/// large as its content.
///
/// Both menus share the same structure: a full-screen overlay
/// ([`overlay`](Self::overlay)) that dims the scene, and a centered panel
/// ([`panel`](Self::panel), [`panel_width`](Self::panel_width),
/// [`panel_padding`](Self::panel_padding)) that holds the title and the
/// controls. Fonts stay in [`PauseMenuConfig`].
///
/// The theme is read when a menu is opened and when a button changes
/// interaction state. Changing it while a menu is open restyles the buttons
/// as they are next hovered or pressed and everything else the next time the
/// menu is opened.
///
/// Build it with struct-update syntax (`..Default::default()`) so that fields
/// added later do not break your code.
///
/// # Default values
///
/// | Field              | Default                             |
/// |--------------------|-------------------------------------|
/// | `overlay`          | `Color::srgba(0.0, 0.0, 0.0, 0.78)` |
/// | `panel`            | `Color::NONE` (invisible)           |
/// | `header`           | `Color::WHITE`                      |
/// | `text`             | `Color::WHITE`                      |
/// | `label`            | `Color::srgb(0.8, 0.8, 0.8)`        |
/// | `button`           | default [`ButtonColors`]            |
/// | `secondary_button` | default [`ButtonColors`]            |
/// | `corner_radius`    | `0.0`                               |
/// | `panel_width`      | `Val::Auto` (fits its content)      |
/// | `panel_padding`    | `UiRect::ZERO`                      |
///
/// # Example
///
/// A light card with dark text over a dimmed scene:
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .insert_resource(PauseMenuTheme {
///         overlay: Color::srgba(0.0, 0.0, 0.0, 0.5),
///         panel: Color::srgb(0.95, 0.95, 0.92),
///         header: Color::srgb(0.1, 0.1, 0.1),
///         text: Color::srgb(0.1, 0.1, 0.1),
///         label: Color::srgb(0.3, 0.3, 0.3),
///         button: ButtonColors {
///             normal: Color::srgb(0.2, 0.2, 0.2),
///             hovered: Color::srgb(0.3, 0.3, 0.3),
///             pressed: Color::srgb(0.1, 0.1, 0.1),
///             text: Color::WHITE,
///         },
///         secondary_button: ButtonColors {
///             normal: Color::srgb(0.8, 0.8, 0.78),
///             hovered: Color::srgb(0.7, 0.7, 0.68),
///             pressed: Color::srgb(0.6, 0.6, 0.58),
///             text: Color::srgb(0.1, 0.1, 0.1),
///         },
///         corner_radius: 8.0,
///         panel_width: Val::Px(520.0),
///         panel_padding: UiRect::all(Val::Px(32.0)),
///         ..Default::default()
///     })
///     .add_plugins(PauseMenuPlugin)
///     .run();
/// ```
#[derive(Resource, Debug, Clone, PartialEq)]
pub struct PauseMenuTheme {
    /// Color of the full-screen overlay behind the panel. Its alpha decides
    /// how much the scene is dimmed.
    pub overlay: Color,
    /// Background of the centered panel (the "card") that holds the title and
    /// the controls. `Color::NONE` by default, so the controls appear
    /// directly on the overlay.
    pub panel: Color,
    /// Color of the menu title (`PAUSED`, `SETTINGS`).
    pub header: Color,
    /// Color of the current value shown between the two arrow buttons of
    /// each settings row.
    pub text: Color,
    /// Color of the name at the start of each settings row (`Field of View`,
    /// `SFX Volume`, …).
    pub label: Color,
    /// Colors of the primary buttons: `Resume` in the pause menu and `Back`
    /// in the settings submenu.
    pub button: ButtonColors,
    /// Colors of every other button: `Settings` and `Quit` in the pause menu
    /// and the arrow buttons of the settings rows.
    pub secondary_button: ButtonColors,
    /// Corner radius, in logical pixels, of the panel and of every button.
    /// `0.0` gives square corners.
    pub corner_radius: f32,
    /// Width of the panel. `Val::Auto` makes it as wide as its content: 280
    /// logical pixels in the pause menu and about 400 in the settings submenu.
    /// The content does not shrink, so a narrower value lets it overflow.
    pub panel_width: Val,
    /// Space between the edges of the panel and its content.
    pub panel_padding: UiRect,
}

impl Default for PauseMenuTheme {
    fn default() -> Self {
        Self {
            overlay: Color::srgba(0.0, 0.0, 0.0, 0.78),
            panel: Color::NONE,
            header: Color::WHITE,
            text: Color::WHITE,
            label: Color::srgb(0.8, 0.8, 0.8),
            button: ButtonColors::default(),
            secondary_button: ButtonColors::default(),
            corner_radius: 0.0,
            panel_width: Val::Auto,
            panel_padding: UiRect::ZERO,
        }
    }
}

/// The theme to draw with: the game's resource, or the default look when the
/// resource is absent (systems run without [`PauseMenuPlugin`]).
fn current_theme(theme: Option<Res<PauseMenuTheme>>) -> PauseMenuTheme {
    theme.as_deref().cloned().unwrap_or_default()
}

/// A menu button action that knows which [`ButtonColors`] of the theme it is
/// drawn with.
trait ThemedButton {
    fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors;
}

// ─── Markers ─────────────────────────────────────────────────────────────────

#[derive(Component)]
struct PauseMenuRoot;
#[derive(Component)]
struct SettingsMenuRoot;
/// The centered panel of either menu; child of the overlay root.
#[derive(Component)]
struct PauseMenuPanel;
#[derive(Component)]
struct FovLabel;
#[derive(Component)]
struct VolumeLabel;
#[derive(Component)]
struct RenderDistLabel;
#[derive(Component)]
struct SensitivityLabel;

#[derive(Component)]
enum PauseButton {
    Resume,
    Settings,
    Quit,
}

#[derive(Component)]
enum SettingsButton {
    FovInc,
    FovDec,
    VolumeInc,
    VolumeDec,
    RenderDistInc,
    RenderDistDec,
    SensitivityInc,
    SensitivityDec,
    Back,
}

impl ThemedButton for PauseButton {
    fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
        match self {
            PauseButton::Resume => theme.button,
            PauseButton::Settings | PauseButton::Quit => theme.secondary_button,
        }
    }
}

impl ThemedButton for SettingsButton {
    fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
        match self {
            SettingsButton::Back => theme.button,
            _ => theme.secondary_button,
        }
    }
}

// ─── Messages ─────────────────────────────────────────────────────────────────

/// Emitted when the player clicks Back in the Settings submenu.
///
/// The host game should listen for this message and persist the current
/// settings (FOV, volume, render distance, sensitivity) to disk using
/// [`crate::settings::PersistedSettings`].
#[derive(Message, Debug, Clone)]
pub struct SaveSettingsRequest;

// ─── Config ───────────────────────────────────────────────────────────────────

/// Font configuration for [`PauseMenuPlugin`]. Colors and panel layout are in
/// [`PauseMenuTheme`].
///
/// Insert this resource before adding [`PauseMenuPlugin`] to supply a custom
/// font. If omitted, [`PauseMenuPlugin`] populates `font` with the framework's
/// embedded [NotoSans](https://fonts.google.com/noto/specimen/Noto+Sans)
/// regular TTF — a unicode-capable font that renders the settings submenu's
/// arrow glyphs (`←`, `◀`, `▶`) without tofu.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::ui::PauseMenuConfig;
///
/// fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
///     commands.insert_resource(PauseMenuConfig {
///         font: asset_server.load("fonts/MyFont.ttf"),
///         symbol_font: asset_server.load("fonts/MyFont.ttf"),
///     });
/// }
/// ```
#[derive(Resource, Clone)]
pub struct PauseMenuConfig {
    /// Font handle used for every text element in both the pause menu and the
    /// settings submenu (title, button labels, slider values).
    ///
    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
    /// replaces the default handle with the embedded NotoSans font during
    /// `Startup` (see `EMBEDDED_NOTO_SANS_PATH`) so games inherit a legible
    /// unicode-capable font without loading any asset themselves. To override,
    /// insert [`PauseMenuConfig`] with a custom `font` handle before the menu is
    /// first spawned.
    pub font: Handle<Font>,
    /// Font handle used for symbol-only glyphs that are absent from the main
    /// [`font`](Self::font) subset — specifically the `◀` and `▶` triangle
    /// glyphs used on the settings slider inc/dec buttons.
    ///
    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
    /// replaces the default handle with the embedded NotoSansSymbols2 font
    /// during `Startup` (see `EMBEDDED_NOTO_SYMBOLS_PATH`). To override,
    /// insert [`PauseMenuConfig`] with a custom `symbol_font` handle before the
    /// menu is first spawned.
    pub symbol_font: Handle<Font>,
}

impl Default for PauseMenuConfig {
    fn default() -> Self {
        Self {
            font: Handle::default(),
            symbol_font: Handle::default(),
        }
    }
}

// ─── Plugin ───────────────────────────────────────────────────────────────────

/// Plugin that adds a full-screen pause menu with a settings submenu.
///
/// Registers [`PauseMenuState`] and wires all transitions, UI spawning, and
/// cursor management. The settings submenu exposes real-time controls for FOV
/// (±5° per click, clamped to `50°`–`120°`) and SFX volume (±10% per click,
/// clamped to `0%`–`100%`).
///
/// Colors and panel layout come from the [`PauseMenuTheme`] resource; fonts
/// from [`PauseMenuConfig`].
///
/// Handles cursor releasing and locking as part of the `Playing ↔ Paused`
/// transition. First-click capture and focus-loss release come from
/// [`player_cursor_system`](crate::player::player_cursor_system), which
/// [`PlayerPlugin`](crate::player::PlayerPlugin) registers and which defers
/// Escape to this plugin when both are present.
///
/// # Simple usage
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
///     .add_plugins(PauseMenuPlugin)
///     .run();
/// ```
///
/// # With hand-registered player systems
///
/// Include [`player_cursor_system`](crate::player::player_cursor_system) so the
/// first click captures the cursor and focus loss releases it:
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
/// use voxel_framework::player::{spawn_player, player_cursor_system, player_look,
///     player_move, player_resolve_collision};
/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
///     .add_plugins(PauseMenuPlugin)
///     .add_systems(Startup, spawn_player)
///     .add_systems(Update,
///         (player_cursor_system, player_look, player_move::<DefaultVoxel>,
///             player_resolve_collision::<DefaultVoxel>)
///             .chain()
///             .run_if(in_state(PauseMenuState::Playing)),
///     );
/// ```
pub struct PauseMenuPlugin;

impl Plugin for PauseMenuPlugin {
    fn build(&self, app: &mut App) {
        // Embed the NotoSans TTF into the framework binary. The resulting asset
        // is reachable from any `AssetServer::load(...)` call via the
        // `embedded://` scheme — see [`EMBEDDED_NOTO_SANS_PATH`].
        embedded_asset!(app, "NotoSans-Regular.ttf");
        embedded_asset!(app, "NotoSansSymbols2-Regular.ttf");

        app.init_resource::<PauseMenuConfig>();
        app.init_resource::<PauseMenuTheme>();
        app.init_state::<PauseMenuState>();
        app.add_message::<SaveSettingsRequest>();

        // Populate `PauseMenuConfig::font` with the embedded NotoSans handle
        // when the user hasn't supplied their own font. Runs once on `Startup`,
        // which fires before any `OnEnter(Paused)` transition can spawn the
        // menu, so the handle is always ready by the time the menu is built.
        app.add_systems(Startup, load_default_font);

        // Playing — toggle on Escape
        app.add_systems(
            Update,
            toggle_pause.run_if(in_state(PauseMenuState::Playing)),
        );

        // Paused
        app.add_systems(
            OnEnter(PauseMenuState::Paused),
            (spawn_pause_menu, release_cursor),
        );
        app.add_systems(OnExit(PauseMenuState::Paused), despawn_pause_menu);
        app.add_systems(
            Update,
            (handle_pause_buttons, escape_to_resume).run_if(in_state(PauseMenuState::Paused)),
        );

        // Settings
        app.add_systems(OnEnter(PauseMenuState::Settings), spawn_settings_menu);
        app.add_systems(OnExit(PauseMenuState::Settings), despawn_settings_menu);
        app.add_systems(
            Update,
            handle_settings_buttons.run_if(in_state(PauseMenuState::Settings)),
        );
    }
}

// ─── Default font loader ──────────────────────────────────────────────────────

/// Populates [`PauseMenuConfig::font`] with the embedded NotoSans font on
/// startup if the game has not supplied a custom font.
///
/// `Default` can't access the [`AssetServer`], so we use a startup sentinel:
/// when `font == Handle::default()` (the weak, uninitialised handle produced
/// by [`PauseMenuConfig::default()`]), we load the embedded font and overwrite
/// the field. Games that insert their own [`PauseMenuConfig`] before this
/// plugin — or before `Startup` runs — keep their custom handle untouched.
fn load_default_font(mut cfg: ResMut<PauseMenuConfig>, asset_server: Res<AssetServer>) {
    if cfg.font == Handle::default() {
        cfg.font = asset_server.load(EMBEDDED_NOTO_SANS_PATH);
    }
    if cfg.symbol_font == Handle::default() {
        cfg.symbol_font = asset_server.load(EMBEDDED_NOTO_SYMBOLS_PATH);
    }
}

// ─── Cursor helpers ───────────────────────────────────────────────────────────

/// Releases the cursor when entering [`PauseMenuState::Paused`].
///
/// Called via `OnEnter(Paused)`. Sets `CursorGrabMode::None` on the primary
/// window and makes the cursor visible so the player can interact with the
/// menu buttons.
fn release_cursor(mut windows: PrimaryCursor) {
    for (_, mut cursor) in &mut windows {
        cursor.grab_mode = bevy::window::CursorGrabMode::None;
        cursor.visible = true;
    }
}

/// The primary window and its cursor options: the only cursor the pause menu
/// manages.
type PrimaryCursor<'w, 's> = Query<
    'w,
    's,
    (&'static Window, &'static mut bevy::window::CursorOptions),
    With<bevy::window::PrimaryWindow>,
>;

/// Re-locks the cursor when returning to [`PauseMenuState::Playing`].
///
/// Called as a plain function (not a system) from [`escape_to_resume`] and
/// [`handle_pause_buttons`] so that cursor re-lock and state transition happen
/// in the same frame without a one-frame gap.
///
/// An unfocused window is left alone: a window must be focused before its
/// cursor is captured, and a click captures it later.
fn lock_cursor(windows: &mut PrimaryCursor) {
    for (window, mut cursor) in windows.iter_mut() {
        if !window.focused {
            continue;
        }
        cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
        cursor.visible = false;
    }
}

// ─── Toggle pause ─────────────────────────────────────────────────────────────

/// Transitions from `Playing` → `Paused` when Escape is pressed.
///
/// Runs only in [`PauseMenuState::Playing`]. Also fires a
/// [`SfxEvent::PauseOpen`] sound request.
fn toggle_pause(
    keys: Res<ButtonInput<KeyCode>>,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut sfx: MessageWriter<SfxRequest>,
) {
    if keys.just_pressed(KeyCode::Escape) {
        next.set(PauseMenuState::Paused);
        sfx.write(SfxRequest {
            event: SfxEvent::PauseOpen,
            position: None,
        });
    }
}

/// Transitions from `Paused` → `Playing` when Escape is pressed.
///
/// Runs only in [`PauseMenuState::Paused`]. Re-locks the cursor via
/// [`lock_cursor`] in the same frame and fires [`SfxEvent::PauseClose`].
fn escape_to_resume(
    keys: Res<ButtonInput<KeyCode>>,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut windows: PrimaryCursor,
    mut sfx: MessageWriter<SfxRequest>,
) {
    if keys.just_pressed(KeyCode::Escape) {
        next.set(PauseMenuState::Playing);
        lock_cursor(&mut windows);
        sfx.write(SfxRequest {
            event: SfxEvent::PauseClose,
            position: None,
        });
    }
}

// ─── Spawn helpers ────────────────────────────────────────────────────────────

fn spawn_btn<C: Component + ThemedButton>(
    parent: &mut ChildSpawnerCommands,
    label: &str,
    action: C,
    width: f32,
    height: f32,
    font: Handle<Font>,
    theme: &PauseMenuTheme,
) {
    let colors = action.colors(theme);
    parent
        .spawn((
            action,
            Button,
            Node {
                width: Val::Px(width),
                height: Val::Px(height),
                justify_content: JustifyContent::Center,
                align_items: AlignItems::Center,
                border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
                ..default()
            },
            BackgroundColor(colors.normal),
        ))
        .with_children(|b| {
            b.spawn((
                Text::new(label),
                TextFont {
                    font,
                    font_size: 20.0,
                    ..default()
                },
                TextColor(colors.text),
            ));
        });
}

fn overlay_node(theme: &PauseMenuTheme) -> (Node, BackgroundColor) {
    (
        Node {
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            flex_direction: FlexDirection::Column,
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            row_gap: Val::Px(14.0),
            ..default()
        },
        BackgroundColor(theme.overlay),
    )
}

/// The centered panel that holds a menu's title and controls.
///
/// It lays its children out exactly as the overlay used to (centered column,
/// 14 px gap), so with the default theme (no background, automatic width, no
/// padding) the menu looks as it did when the overlay held them directly.
fn panel_node(theme: &PauseMenuTheme) -> (PauseMenuPanel, Node, BackgroundColor) {
    (
        PauseMenuPanel,
        Node {
            width: theme.panel_width,
            padding: theme.panel_padding,
            flex_direction: FlexDirection::Column,
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            row_gap: Val::Px(14.0),
            border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
            ..default()
        },
        BackgroundColor(theme.panel),
    )
}

// ─── Pause menu ───────────────────────────────────────────────────────────────

/// Spawns the pause menu overlay when entering [`PauseMenuState::Paused`].
///
/// Builds a full-screen semi-transparent overlay with a centered panel that
/// holds the title and three buttons: Resume, Settings, and Quit. Colors and
/// panel layout come from [`PauseMenuTheme`]. Runs via `OnEnter(Paused)`.
fn spawn_pause_menu(
    mut commands: Commands,
    config: Res<PauseMenuConfig>,
    theme: Option<Res<PauseMenuTheme>>,
) {
    let theme = current_theme(theme);
    let (node, bg) = overlay_node(&theme);
    commands
        .spawn((PauseMenuRoot, node, bg))
        .with_children(|overlay| {
            overlay.spawn(panel_node(&theme)).with_children(|p| {
                p.spawn((
                    Text::new("PAUSED"),
                    TextFont {
                        font: config.font.clone(),
                        font_size: 52.0,
                        ..default()
                    },
                    TextColor(theme.header),
                    Node {
                        margin: UiRect::bottom(Val::Px(28.0)),
                        ..default()
                    },
                ));
                spawn_btn(
                    p,
                    "Resume",
                    PauseButton::Resume,
                    280.0,
                    52.0,
                    config.font.clone(),
                    &theme,
                );
                spawn_btn(
                    p,
                    "Settings",
                    PauseButton::Settings,
                    280.0,
                    52.0,
                    config.font.clone(),
                    &theme,
                );
                spawn_btn(
                    p,
                    "Quit",
                    PauseButton::Quit,
                    280.0,
                    52.0,
                    config.font.clone(),
                    &theme,
                );
            });
        });
}

/// Despawns the pause menu overlay when leaving [`PauseMenuState::Paused`].
///
/// Runs via `OnExit(Paused)`, which fires for both `Paused → Playing` and
/// `Paused → Settings` transitions.
fn despawn_pause_menu(mut commands: Commands, q: Query<Entity, With<PauseMenuRoot>>) {
    for e in &q {
        commands.entity(e).despawn();
    }
}

/// Handles hover/press styling and click actions for pause menu buttons.
///
/// Runs every frame in [`PauseMenuState::Paused`]. Updates button background
/// colors on hover and press from [`PauseMenuTheme`], then on `Pressed`
/// dispatches: Resume → `Playing` (re-locks cursor), Settings → `Settings`,
/// Quit → [`AppExit`].
fn handle_pause_buttons(
    mut q: Query<
        (&Interaction, &mut BackgroundColor, &PauseButton),
        (Changed<Interaction>, With<Button>),
    >,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut windows: PrimaryCursor,
    mut app_exit: MessageWriter<AppExit>,
    mut sfx: MessageWriter<SfxRequest>,
    theme: Option<Res<PauseMenuTheme>>,
) {
    let theme = current_theme(theme);
    for (interaction, mut bg, action) in &mut q {
        *bg = BackgroundColor(action.colors(&theme).background(*interaction));
        if *interaction != Interaction::Pressed {
            continue;
        }
        match action {
            PauseButton::Resume => {
                next.set(PauseMenuState::Playing);
                lock_cursor(&mut windows);
                sfx.write(SfxRequest {
                    event: SfxEvent::PauseClose,
                    position: None,
                });
            }
            PauseButton::Settings => next.set(PauseMenuState::Settings),
            PauseButton::Quit => {
                app_exit.write(AppExit::Success);
            }
        }
    }
}

// ─── Settings menu ────────────────────────────────────────────────────────────

/// Spawns the settings overlay when entering [`PauseMenuState::Settings`].
///
/// Reads the current FOV from the [`Camera3d`] projection, the current SFX
/// volume from [`SfxConfig`], the render distance from [`WorldConfig`], and the
/// mouse sensitivity from [`PlayerConfig`] to initialise the slider labels.
/// Runs via `OnEnter(Settings)`.
fn spawn_settings_menu(
    mut commands: Commands,
    sfx_config: Res<SfxConfig>,
    world_config: Option<Res<WorldConfig>>,
    player_config: Option<Res<PlayerConfig>>,
    camera_q: Query<&Projection, With<Camera3d>>,
    config: Res<PauseMenuConfig>,
    theme: Option<Res<PauseMenuTheme>>,
) {
    let fov_deg = camera_q
        .single()
        .ok()
        .and_then(|p| {
            if let Projection::Perspective(pp) = p {
                Some(pp.fov.to_degrees())
            } else {
                None
            }
        })
        .unwrap_or(90.0);
    let volume_pct = sfx_config.volume * 100.0;
    let render_dist_chunks = world_config
        .as_ref()
        .map(|wc| ((wc.load_distance / 16.0).round() as i32).clamp(4, 32) as i32)
        .unwrap_or(10);
    // Round to nearest even
    let render_dist_chunks = if render_dist_chunks % 2 == 0 {
        render_dist_chunks
    } else {
        render_dist_chunks + 1
    };
    let sensitivity_pct = player_config
        .as_ref()
        .map(|pc| ((pc.sensitivity * 100.0).round() as i32).clamp(10, 100))
        .unwrap_or(100);

    let theme = current_theme(theme);
    let (node, bg) = overlay_node(&theme);
    commands
        .spawn((SettingsMenuRoot, node, bg))
        .with_children(|overlay| {
            overlay.spawn(panel_node(&theme)).with_children(|p| {
                p.spawn((
                    Text::new("SETTINGS"),
                    TextFont {
                        font: config.font.clone(),
                        font_size: 42.0,
                        ..default()
                    },
                    TextColor(theme.header),
                    Node {
                        margin: UiRect::bottom(Val::Px(20.0)),
                        ..default()
                    },
                ));

                spawn_slider_row(
                    p,
                    "Field of View",
                    format!("{fov_deg:.0}°"),
                    FovLabel,
                    SettingsButton::FovDec,
                    SettingsButton::FovInc,
                    config.font.clone(),
                    config.symbol_font.clone(),
                    &theme,
                );

                spawn_slider_row(
                    p,
                    "SFX Volume",
                    format!("{volume_pct:.0}%"),
                    VolumeLabel,
                    SettingsButton::VolumeDec,
                    SettingsButton::VolumeInc,
                    config.font.clone(),
                    config.symbol_font.clone(),
                    &theme,
                );

                spawn_slider_row(
                    p,
                    "Render Distance",
                    format!("{render_dist_chunks} chunks"),
                    RenderDistLabel,
                    SettingsButton::RenderDistDec,
                    SettingsButton::RenderDistInc,
                    config.font.clone(),
                    config.symbol_font.clone(),
                    &theme,
                );

                spawn_slider_row(
                    p,
                    "Sensitivity",
                    format!("{sensitivity_pct:.0}%"),
                    SensitivityLabel,
                    SettingsButton::SensitivityDec,
                    SettingsButton::SensitivityInc,
                    config.font.clone(),
                    config.symbol_font.clone(),
                    &theme,
                );

                p.spawn(Node {
                    margin: UiRect::top(Val::Px(20.0)),
                    ..default()
                })
                .with_children(|row| {
                    spawn_btn(
                        row,
                        "< Back",
                        SettingsButton::Back,
                        200.0,
                        50.0,
                        config.font.clone(),
                        &theme,
                    );
                });
            });
        });
}

#[allow(clippy::too_many_arguments)]
fn spawn_slider_row<L: Component, D: Component + ThemedButton, I: Component + ThemedButton>(
    parent: &mut ChildSpawnerCommands,
    label: &str,
    value: String,
    value_marker: L,
    dec: D,
    inc: I,
    font: Handle<Font>,
    symbol_font: Handle<Font>,
    theme: &PauseMenuTheme,
) {
    parent
        .spawn(Node {
            flex_direction: FlexDirection::Row,
            align_items: AlignItems::Center,
            column_gap: Val::Px(12.0),
            ..default()
        })
        .with_children(|row| {
            row.spawn((
                Text::new(label),
                TextFont {
                    font: font.clone(),
                    font_size: 20.0,
                    ..default()
                },
                TextColor(theme.label),
                Node {
                    width: Val::Px(200.0),
                    ..default()
                },
            ));
            spawn_btn(row, "\u{25C0}", dec, 44.0, 44.0, symbol_font.clone(), theme);
            row.spawn((
                value_marker,
                Text::new(value),
                TextFont {
                    font: font.clone(),
                    font_size: 22.0,
                    ..default()
                },
                TextColor(theme.text),
                Node {
                    width: Val::Px(80.0),
                    justify_content: JustifyContent::Center,
                    ..default()
                },
            ));
            spawn_btn(row, "\u{25B6}", inc, 44.0, 44.0, symbol_font, theme);
        });
}

/// Despawns the settings overlay when leaving [`PauseMenuState::Settings`].
///
/// Runs via `OnExit(Settings)`. The only exit transition is `Settings → Paused`
/// via the Back button.
fn despawn_settings_menu(mut commands: Commands, q: Query<Entity, With<SettingsMenuRoot>>) {
    for e in &q {
        commands.entity(e).despawn();
    }
}

/// Handles hover/press styling and click actions for settings menu buttons.
///
/// Runs every frame in [`PauseMenuState::Settings`]. Updates button background
/// colors from [`PauseMenuTheme`] and adjusts values on press:
/// - `FovInc` / `FovDec`: changes FOV by ±5° (clamped `50°`–`120°`) and updates
///   [`FovLabel`] text and the [`Camera3d`] perspective projection.
/// - `VolumeInc` / `VolumeDec`: changes [`SfxConfig::volume`] by ±0.1 (clamped
///   `0.0`–`1.0`) and updates [`VolumeLabel`] text.
/// - `RenderDistInc` / `RenderDistDec`: changes [`WorldConfig::load_distance`] by
///   ±2 chunks (clamped `4`–`32`) and updates [`RenderDistLabel`] text and
///   [`ChunkManager`] distances.
/// - `SensitivityInc` / `SensitivityDec`: changes [`PlayerConfig::sensitivity`] by
///   ±1% (clamped `10`–`100`), applies it to every live [`Player`] so mouse
///   look changes immediately, and updates [`SensitivityLabel`] text.
/// - `Back`: emits [`SaveSettingsRequest`] and transitions to [`PauseMenuState::Paused`].
#[allow(clippy::too_many_arguments)]
fn handle_settings_buttons(
    mut q: Query<
        (&Interaction, &mut BackgroundColor, &SettingsButton),
        (Changed<Interaction>, With<Button>),
    >,
    mut sfx_config: ResMut<SfxConfig>,
    mut world_config: Option<ResMut<WorldConfig>>,
    mut chunk_manager: Option<ResMut<ChunkManager>>,
    mut player_config: Option<ResMut<PlayerConfig>>,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut fov_label: Query<
        &mut Text,
        (
            With<FovLabel>,
            Without<VolumeLabel>,
            Without<RenderDistLabel>,
            Without<SensitivityLabel>,
        ),
    >,
    mut vol_label: Query<
        &mut Text,
        (
            With<VolumeLabel>,
            Without<FovLabel>,
            Without<RenderDistLabel>,
            Without<SensitivityLabel>,
        ),
    >,
    mut rdist_label: Query<
        &mut Text,
        (
            With<RenderDistLabel>,
            Without<FovLabel>,
            Without<VolumeLabel>,
            Without<SensitivityLabel>,
        ),
    >,
    mut sens_label: Query<
        &mut Text,
        (
            With<SensitivityLabel>,
            Without<FovLabel>,
            Without<VolumeLabel>,
            Without<RenderDistLabel>,
        ),
    >,
    mut camera_q: Query<&mut Projection, With<Camera3d>>,
    mut players: Query<&mut Player>,
    mut save_writer: MessageWriter<SaveSettingsRequest>,
    theme: Option<Res<PauseMenuTheme>>,
) {
    let theme = current_theme(theme);
    for (interaction, mut bg, action) in &mut q {
        *bg = BackgroundColor(action.colors(&theme).background(*interaction));
        if *interaction != Interaction::Pressed {
            continue;
        }

        match action {
            SettingsButton::FovInc | SettingsButton::FovDec => {
                if let Ok(mut proj) = camera_q.single_mut() {
                    if let Projection::Perspective(ref mut pp) = *proj {
                        let new_fov = step_fov_degrees(
                            pp.fov.to_degrees(),
                            matches!(action, SettingsButton::FovInc),
                        );
                        pp.fov = new_fov.to_radians();
                        if let Ok(mut t) = fov_label.single_mut() {
                            **t = format!("{new_fov:.0}°");
                        }
                    }
                }
            }
            SettingsButton::VolumeInc | SettingsButton::VolumeDec => {
                sfx_config.volume = step_volume(
                    sfx_config.volume,
                    matches!(action, SettingsButton::VolumeInc),
                );
                let pct = sfx_config.volume * 100.0;
                if let Ok(mut t) = vol_label.single_mut() {
                    **t = format!("{pct:.0}%");
                }
            }
            SettingsButton::RenderDistInc | SettingsButton::RenderDistDec => {
                if let Some(ref mut wc) = world_config {
                    let new_chunks = step_render_distance_chunks(
                        wc.load_distance,
                        matches!(action, SettingsButton::RenderDistInc),
                    );
                    wc.load_distance = new_chunks as f32 * 16.0;
                    wc.unload_distance = wc.load_distance + 32.0;
                    if let Some(ref mut cm) = chunk_manager {
                        cm.load_distance = wc.load_distance;
                        cm.unload_distance = wc.unload_distance;
                    }
                    if let Ok(mut t) = rdist_label.single_mut() {
                        **t = format!("{new_chunks} chunks");
                    }
                }
            }
            SettingsButton::SensitivityInc | SettingsButton::SensitivityDec => {
                if let Some(ref mut pc) = player_config {
                    let new_pct = step_sensitivity_pct(
                        pc.sensitivity,
                        matches!(action, SettingsButton::SensitivityInc),
                    );
                    pc.sensitivity = new_pct as f32 / 100.0;
                    // `Player::sensitivity` is copied from the config at spawn
                    // and is what mouse look reads, so update live players too;
                    // otherwise the change only applied after a restart.
                    for mut player in &mut players {
                        player.sensitivity = pc.sensitivity;
                    }
                    if let Ok(mut t) = sens_label.single_mut() {
                        **t = format!("{new_pct:.0}%");
                    }
                }
            }
            SettingsButton::Back => {
                save_writer.write(SaveSettingsRequest);
                next.set(PauseMenuState::Paused);
            }
        }
    }
}

// ─── Slider steps ─────────────────────────────────────────────────────────────
//
// Pure helpers behind the settings buttons, kept separate from the Bevy system
// so the rules (step size, limits, rounding) are unit-testable.

/// Next field of view in degrees: ±5°, clamped to `50`–`120`.
fn step_fov_degrees(current_deg: f32, increase: bool) -> f32 {
    let delta = if increase { 5.0 } else { -5.0 };
    (current_deg + delta).clamp(50.0, 120.0)
}

/// Next SFX volume: ±0.1, clamped to `0.0`–`1.0`.
fn step_volume(current: f32, increase: bool) -> f32 {
    let delta = if increase { 0.1 } else { -0.1 };
    (current + delta).clamp(0.0, 1.0)
}

/// Next render distance in chunks: the current `load_distance` is rounded to
/// whole chunks, clamped to `4`–`32` and bumped to even, then moved ±2 chunks
/// and clamped again.
fn step_render_distance_chunks(load_distance: f32, increase: bool) -> i32 {
    let current = ((load_distance / 16.0).round() as i32).clamp(4, 32);
    let current = if current % 2 == 0 {
        current
    } else {
        current + 1
    };
    let delta = if increase { 2 } else { -2 };
    (current + delta).clamp(4, 32)
}

/// Next mouse sensitivity in percent: ±1%, clamped to `10`–`100`.
fn step_sensitivity_pct(sensitivity: f32, increase: bool) -> i32 {
    let current_pct = (sensitivity * 100.0).round() as i32;
    let delta = if increase { 1 } else { -1 };
    (current_pct + delta).clamp(10, 100)
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use bevy::ecs::message::Messages;
    use bevy::ecs::system::RunSystemOnce;

    use crate::player::player_cursor_system;
    use bevy::state::app::StatesPlugin;
    use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};

    /// Headless app with the pause transitions wired as [`PauseMenuPlugin`]
    /// does (minus UI and assets) plus the player's cursor system, and a
    /// focused primary window with a free cursor.
    fn pause_cursor_app() -> (App, Entity) {
        let mut app = App::new();
        app.add_plugins(StatesPlugin);
        app.init_state::<PauseMenuState>();
        app.add_message::<SfxRequest>();
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<ButtonInput<MouseButton>>();
        app.add_systems(
            Update,
            (
                toggle_pause.run_if(in_state(PauseMenuState::Playing)),
                escape_to_resume.run_if(in_state(PauseMenuState::Paused)),
                player_cursor_system.run_if(in_state(PauseMenuState::Playing)),
            ),
        );
        app.add_systems(OnEnter(PauseMenuState::Paused), release_cursor);
        let window = app
            .world_mut()
            .spawn((
                Window {
                    focused: true,
                    ..default()
                },
                PrimaryWindow,
            ))
            .id();
        (app, window)
    }

    /// Presses `key` for one frame, then runs a second frame so the state
    /// transition it requested is applied.
    fn tap(app: &mut App, key: KeyCode) {
        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .press(key);
        app.update();
        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .reset_all();
        app.update();
    }

    fn click(app: &mut App) {
        app.world_mut()
            .resource_mut::<ButtonInput<MouseButton>>()
            .press(MouseButton::Left);
        app.update();
        app.world_mut()
            .resource_mut::<ButtonInput<MouseButton>>()
            .reset_all();
    }

    fn pause_state(app: &App) -> PauseMenuState {
        app.world()
            .resource::<State<PauseMenuState>>()
            .get()
            .clone()
    }

    fn grab(app: &App, window: Entity) -> CursorGrabMode {
        app.world()
            .get::<CursorOptions>(window)
            .expect("window should still exist")
            .grab_mode
    }

    #[test]
    fn cursor_follows_pause_focus_and_click_with_the_player_cursor_system() {
        let (mut app, window) = pause_cursor_app();

        // Escape before the first click opens the menu; it must not close the window.
        tap(&mut app, KeyCode::Escape);
        assert_eq!(pause_state(&app), PauseMenuState::Paused);
        assert_eq!(grab(&app, window), CursorGrabMode::None);

        // Escape again resumes with the cursor captured.
        tap(&mut app, KeyCode::Escape);
        assert_eq!(pause_state(&app), PauseMenuState::Playing);
        assert_eq!(grab(&app, window), CursorGrabMode::Locked);

        // Losing focus releases the cursor without pausing.
        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
        app.update();
        assert_eq!(grab(&app, window), CursorGrabMode::None);
        assert_eq!(pause_state(&app), PauseMenuState::Playing);

        // Regaining focus alone does not recapture; a click does.
        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
        app.update();
        assert_eq!(grab(&app, window), CursorGrabMode::None);
        click(&mut app);
        assert_eq!(grab(&app, window), CursorGrabMode::Locked);

        // Pausing from a captured cursor releases it for the menu.
        tap(&mut app, KeyCode::Escape);
        assert_eq!(pause_state(&app), PauseMenuState::Paused);
        assert_eq!(grab(&app, window), CursorGrabMode::None);
    }

    #[test]
    fn resuming_does_not_capture_an_unfocused_window() {
        let (mut app, window) = pause_cursor_app();
        tap(&mut app, KeyCode::Escape);
        assert_eq!(pause_state(&app), PauseMenuState::Paused);
        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;

        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .press(KeyCode::Escape);
        app.update();
        // Checked before the next frame, where the player's cursor system
        // would release an unfocused capture anyway.
        assert_eq!(grab(&app, window), CursorGrabMode::None);
        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .reset_all();
        app.update();

        assert_eq!(pause_state(&app), PauseMenuState::Playing);
        assert_eq!(grab(&app, window), CursorGrabMode::None);
    }

    #[test]
    fn pause_cursor_changes_only_touch_the_primary_window() {
        let (mut app, window) = pause_cursor_app();
        let secondary = app
            .world_mut()
            .spawn((
                Window {
                    focused: false,
                    ..default()
                },
                CursorOptions {
                    grab_mode: CursorGrabMode::Confined,
                    ..default()
                },
            ))
            .id();

        tap(&mut app, KeyCode::Escape);
        tap(&mut app, KeyCode::Escape);

        assert_eq!(grab(&app, window), CursorGrabMode::Locked);
        assert_eq!(grab(&app, secondary), CursorGrabMode::Confined);
    }

    #[test]
    fn fov_steps_by_five_degrees_within_limits() {
        assert_eq!(step_fov_degrees(70.0, true), 75.0);
        assert_eq!(step_fov_degrees(70.0, false), 65.0);
        assert_eq!(step_fov_degrees(118.0, true), 120.0);
        assert_eq!(step_fov_degrees(52.0, false), 50.0);
    }

    #[test]
    fn volume_steps_by_a_tenth_within_limits() {
        assert!((step_volume(0.5, true) - 0.6).abs() < 1e-6);
        assert!((step_volume(0.5, false) - 0.4).abs() < 1e-6);
        assert_eq!(step_volume(0.95, true), 1.0);
        assert_eq!(step_volume(0.05, false), 0.0);
    }

    #[test]
    fn render_distance_steps_by_two_chunks_within_limits() {
        // Default load distance is 150 units ≈ 9.4 chunks → 9 → bumped to 10.
        assert_eq!(step_render_distance_chunks(150.0, true), 12);
        assert_eq!(step_render_distance_chunks(150.0, false), 8);
        assert_eq!(step_render_distance_chunks(8.0 * 16.0, true), 10);
        assert_eq!(step_render_distance_chunks(32.0 * 16.0, true), 32);
        assert_eq!(step_render_distance_chunks(4.0 * 16.0, false), 4);
        // Values outside the slider range are clamped first.
        assert_eq!(step_render_distance_chunks(1000.0 * 16.0, false), 30);
    }

    #[test]
    fn sensitivity_steps_by_one_percent_within_limits() {
        assert_eq!(step_sensitivity_pct(1.0, false), 99);
        assert_eq!(step_sensitivity_pct(1.0, true), 100);
        assert_eq!(step_sensitivity_pct(0.5, true), 51);
        assert_eq!(step_sensitivity_pct(0.1, false), 10);
    }

    /// World with the resources `handle_settings_buttons` needs and one
    /// pressed button.
    fn settings_world(pressed: SettingsButton) -> World {
        let mut world = World::new();
        world.insert_resource(SfxConfig::default());
        world.init_resource::<NextState<PauseMenuState>>();
        world.init_resource::<Messages<SaveSettingsRequest>>();
        world.spawn((
            Button,
            Interaction::Pressed,
            BackgroundColor(Color::NONE),
            pressed,
        ));
        world
    }

    fn press(world: &mut World) {
        world
            .run_system_once(handle_settings_buttons)
            .expect("handle_settings_buttons should run");
    }

    #[test]
    fn sensitivity_button_updates_config_and_live_players() {
        let mut world = settings_world(SettingsButton::SensitivityDec);
        world.insert_resource(PlayerConfig::default());
        let player = world.spawn(Player::default()).id();
        assert_eq!(world.get::<Player>(player).unwrap().sensitivity, 1.0);

        press(&mut world);

        assert!((world.resource::<PlayerConfig>().sensitivity - 0.99).abs() < 1e-6);
        assert!(
            (world.get::<Player>(player).unwrap().sensitivity - 0.99).abs() < 1e-6,
            "the live player must pick up the new sensitivity without a restart"
        );
    }

    #[test]
    fn volume_button_updates_sfx_config() {
        let mut world = settings_world(SettingsButton::VolumeDec);
        let before = world.resource::<SfxConfig>().volume;

        press(&mut world);

        let after = world.resource::<SfxConfig>().volume;
        assert!((after - (before - 0.1).clamp(0.0, 1.0)).abs() < 1e-6);
    }

    #[test]
    fn back_button_requests_save_and_returns_to_pause() {
        let mut world = settings_world(SettingsButton::Back);

        press(&mut world);

        let saves = world.resource::<Messages<SaveSettingsRequest>>();
        assert_eq!(saves.iter_current_update_messages().count(), 1);
        assert!(matches!(
            *world.resource::<NextState<PauseMenuState>>(),
            NextState::Pending(PauseMenuState::Paused)
        ));
    }

    // ─── Theme ───────────────────────────────────────────────────────────────

    const PRIMARY: ButtonColors = ButtonColors {
        normal: Color::srgb(0.10, 0.20, 0.30),
        hovered: Color::srgb(0.11, 0.21, 0.31),
        pressed: Color::srgb(0.12, 0.22, 0.32),
        text: Color::srgb(0.13, 0.23, 0.33),
    };
    const SECONDARY: ButtonColors = ButtonColors {
        normal: Color::srgb(0.40, 0.50, 0.60),
        hovered: Color::srgb(0.41, 0.51, 0.61),
        pressed: Color::srgb(0.42, 0.52, 0.62),
        text: Color::srgb(0.43, 0.53, 0.63),
    };

    /// A theme in which every value differs from the default and from every
    /// other value, so a color in the wrong place fails a test.
    fn custom_theme() -> PauseMenuTheme {
        PauseMenuTheme {
            overlay: Color::srgba(0.9, 0.1, 0.1, 0.5),
            panel: Color::srgb(0.9, 0.9, 0.8),
            header: Color::srgb(0.1, 0.9, 0.1),
            text: Color::srgb(0.1, 0.1, 0.9),
            label: Color::srgb(0.9, 0.1, 0.9),
            button: PRIMARY,
            secondary_button: SECONDARY,
            corner_radius: 9.0,
            panel_width: Val::Px(520.0),
            panel_padding: UiRect::all(Val::Px(32.0)),
        }
    }

    /// World with what the two spawn systems need, and optionally a theme.
    fn menu_world(theme: Option<PauseMenuTheme>) -> World {
        let mut world = World::new();
        world.insert_resource(PauseMenuConfig::default());
        world.insert_resource(SfxConfig::default());
        if let Some(theme) = theme {
            world.insert_resource(theme);
        }
        world
    }

    fn open_pause_menu(world: &mut World) {
        world
            .run_system_once(spawn_pause_menu)
            .expect("spawn_pause_menu should run");
    }

    fn open_settings_menu(world: &mut World) {
        world
            .run_system_once(spawn_settings_menu)
            .expect("spawn_settings_menu should run");
    }

    /// Color of the only text entity whose content is `content`.
    fn text_color(world: &mut World, content: &str) -> Color {
        let mut query = world.query::<(&Text, &TextColor)>();
        let found: Vec<Color> = query
            .iter(world)
            .filter(|(text, _)| text.0 == content)
            .map(|(_, color)| color.0)
            .collect();
        assert_eq!(found.len(), 1, "expected exactly one text {content:?}");
        found[0]
    }

    /// Background color of the overlay root marked `R`, and the root entity.
    fn overlay<R: Component>(world: &mut World) -> (Entity, Color) {
        let mut query = world.query_filtered::<(Entity, &BackgroundColor), With<R>>();
        let (root, bg) = query
            .single(world)
            .expect("the menu should have exactly one overlay root");
        (root, bg.0)
    }

    /// Background color, node and parent of the menu's single panel.
    fn panel(world: &mut World) -> (Color, Node, Entity) {
        let mut query =
            world.query_filtered::<(&BackgroundColor, &Node, &ChildOf), With<PauseMenuPanel>>();
        let (bg, node, child_of) = query
            .single(world)
            .expect("the menu should have exactly one panel");
        (bg.0, node.clone(), child_of.parent())
    }

    /// Background color and corner radius of every pause-menu button that
    /// `select` accepts.
    fn pause_buttons(
        world: &mut World,
        select: fn(&PauseButton) -> bool,
    ) -> Vec<(Color, BorderRadius)> {
        let mut query = world.query::<(&PauseButton, &BackgroundColor, &Node)>();
        query
            .iter(world)
            .filter(|(action, _, _)| select(action))
            .map(|(_, bg, node)| (bg.0, node.border_radius))
            .collect()
    }

    /// Same as `pause_buttons` for the settings submenu.
    fn settings_buttons(
        world: &mut World,
        select: fn(&SettingsButton) -> bool,
    ) -> Vec<(Color, BorderRadius)> {
        let mut query = world.query::<(&SettingsButton, &BackgroundColor, &Node)>();
        query
            .iter(world)
            .filter(|(action, _, _)| select(action))
            .map(|(_, bg, node)| (bg.0, node.border_radius))
            .collect()
    }

    #[test]
    fn default_theme_equals_the_previous_constants() {
        let buttons = ButtonColors::default();
        assert_eq!(buttons.normal, Color::srgb(0.15, 0.15, 0.20));
        assert_eq!(buttons.hovered, Color::srgb(0.25, 0.25, 0.35));
        assert_eq!(buttons.pressed, Color::srgb(0.35, 0.35, 0.50));
        assert_eq!(buttons.text, Color::WHITE);

        let theme = PauseMenuTheme::default();
        assert_eq!(theme.overlay, Color::srgba(0.0, 0.0, 0.0, 0.78));
        assert_eq!(theme.panel, Color::NONE);
        assert_eq!(theme.header, Color::WHITE);
        assert_eq!(theme.text, Color::WHITE);
        assert_eq!(theme.label, Color::srgb(0.8, 0.8, 0.8));
        assert_eq!(theme.button, buttons);
        assert_eq!(theme.secondary_button, buttons);
        assert_eq!(theme.corner_radius, 0.0);
        assert_eq!(theme.panel_width, Val::Auto);
        assert_eq!(theme.panel_padding, UiRect::ZERO);
    }

    #[test]
    fn button_colors_pick_the_background_for_each_interaction() {
        assert_eq!(PRIMARY.background(Interaction::None), PRIMARY.normal);
        assert_eq!(PRIMARY.background(Interaction::Hovered), PRIMARY.hovered);
        assert_eq!(PRIMARY.background(Interaction::Pressed), PRIMARY.pressed);
    }

    #[test]
    fn pause_menu_without_a_theme_resource_keeps_the_previous_look() {
        let mut world = menu_world(None);

        open_pause_menu(&mut world);

        let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
        assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));

        // The panel exists but cannot be seen and does not change the layout.
        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
        assert_eq!(panel_parent, root);
        assert_eq!(panel_bg, Color::NONE);
        assert_eq!(panel_node.width, Val::Auto);
        assert_eq!(panel_node.padding, UiRect::ZERO);
        assert_eq!(panel_node.border_radius, BorderRadius::ZERO);
        assert_eq!(panel_node.row_gap, Val::Px(14.0));
        assert_eq!(panel_node.flex_direction, FlexDirection::Column);
        assert_eq!(panel_node.align_items, AlignItems::Center);

        assert_eq!(text_color(&mut world, "PAUSED"), Color::WHITE);
        let buttons = pause_buttons(&mut world, |_| true);
        assert_eq!(buttons.len(), 3);
        for (bg, radius) in buttons {
            assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
            assert_eq!(radius, BorderRadius::ZERO);
        }
        for label in ["Resume", "Settings", "Quit"] {
            assert_eq!(text_color(&mut world, label), Color::WHITE);
        }
    }

    #[test]
    fn custom_theme_styles_the_pause_menu() {
        let theme = custom_theme();
        let mut world = menu_world(Some(theme.clone()));

        open_pause_menu(&mut world);

        let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
        assert_eq!(overlay_bg, theme.overlay);

        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
        assert_eq!(panel_parent, root);
        assert_eq!(panel_bg, theme.panel);
        assert_eq!(panel_node.width, Val::Px(520.0));
        assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
        assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));

        assert_eq!(text_color(&mut world, "PAUSED"), theme.header);

        let radius = BorderRadius::all(Val::Px(9.0));
        assert_eq!(
            pause_buttons(&mut world, |b| matches!(b, PauseButton::Resume)),
            vec![(PRIMARY.normal, radius)]
        );
        assert_eq!(
            pause_buttons(&mut world, |b| !matches!(b, PauseButton::Resume)),
            vec![(SECONDARY.normal, radius); 2]
        );
        assert_eq!(text_color(&mut world, "Resume"), PRIMARY.text);
        assert_eq!(text_color(&mut world, "Settings"), SECONDARY.text);
        assert_eq!(text_color(&mut world, "Quit"), SECONDARY.text);
    }

    #[test]
    fn pause_menu_buttons_are_children_of_the_panel() {
        let mut world = menu_world(None);

        open_pause_menu(&mut world);

        let mut panels = world.query_filtered::<Entity, With<PauseMenuPanel>>();
        let panel_entity = panels.single(&world).expect("one panel");
        let mut buttons = world.query_filtered::<&ChildOf, With<PauseButton>>();
        let parents: Vec<Entity> = buttons.iter(&world).map(|c| c.parent()).collect();
        assert_eq!(parents, vec![panel_entity; 3]);
    }

    #[test]
    fn settings_menu_without_a_theme_resource_keeps_the_previous_look() {
        let mut world = menu_world(None);

        open_settings_menu(&mut world);

        let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
        assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));
        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
        assert_eq!(panel_parent, root);
        assert_eq!(panel_bg, Color::NONE);
        assert_eq!(panel_node.width, Val::Auto);
        assert_eq!(panel_node.padding, UiRect::ZERO);

        assert_eq!(text_color(&mut world, "SETTINGS"), Color::WHITE);
        assert_eq!(
            text_color(&mut world, "Field of View"),
            Color::srgb(0.8, 0.8, 0.8)
        );
        let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
        assert_eq!(
            values.single(&world).expect("one FOV value").0,
            Color::WHITE
        );
        let buttons = settings_buttons(&mut world, |_| true);
        assert_eq!(buttons.len(), 9);
        for (bg, radius) in buttons {
            assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
            assert_eq!(radius, BorderRadius::ZERO);
        }
        assert_eq!(text_color(&mut world, "< Back"), Color::WHITE);
    }

    #[test]
    fn custom_theme_styles_the_settings_menu() {
        let theme = custom_theme();
        let mut world = menu_world(Some(theme.clone()));

        open_settings_menu(&mut world);

        let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
        assert_eq!(overlay_bg, theme.overlay);

        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
        assert_eq!(panel_parent, root);
        assert_eq!(panel_bg, theme.panel);
        assert_eq!(panel_node.width, Val::Px(520.0));
        assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
        assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));

        assert_eq!(text_color(&mut world, "SETTINGS"), theme.header);
        for label in [
            "Field of View",
            "SFX Volume",
            "Render Distance",
            "Sensitivity",
        ] {
            assert_eq!(text_color(&mut world, label), theme.label);
        }
        let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
        assert_eq!(values.single(&world).expect("one FOV value").0, theme.text);

        let radius = BorderRadius::all(Val::Px(9.0));
        assert_eq!(
            settings_buttons(&mut world, |b| matches!(b, SettingsButton::Back)),
            vec![(PRIMARY.normal, radius)]
        );
        assert_eq!(
            settings_buttons(&mut world, |b| !matches!(b, SettingsButton::Back)),
            vec![(SECONDARY.normal, radius); 8]
        );
        assert_eq!(text_color(&mut world, "< Back"), PRIMARY.text);
    }

    /// World with what both button handlers need, and optionally a theme.
    fn handler_world(theme: Option<PauseMenuTheme>) -> World {
        let mut world = World::new();
        world.insert_resource(SfxConfig::default());
        world.init_resource::<NextState<PauseMenuState>>();
        world.init_resource::<Messages<SaveSettingsRequest>>();
        world.init_resource::<Messages<SfxRequest>>();
        world.init_resource::<Messages<AppExit>>();
        if let Some(theme) = theme {
            world.insert_resource(theme);
        }
        world
    }

    /// Spawns a button in the given interaction state with a background no
    /// theme uses, so the handler must be what sets the asserted color.
    fn spawn_button<A: Component>(world: &mut World, action: A, state: Interaction) -> Entity {
        world
            .spawn((Button, state, BackgroundColor(Color::NONE), action))
            .id()
    }

    fn background(world: &World, entity: Entity) -> Color {
        world
            .get::<BackgroundColor>(entity)
            .expect("button should exist")
            .0
    }

    #[test]
    fn pause_buttons_take_theme_colors_per_interaction_state() {
        let mut world = handler_world(Some(custom_theme()));
        let primary_idle = spawn_button(&mut world, PauseButton::Resume, Interaction::None);
        let primary_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
        let primary_pressed = spawn_button(&mut world, PauseButton::Resume, Interaction::Pressed);
        let secondary_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
        let secondary_hovered = spawn_button(&mut world, PauseButton::Quit, Interaction::Hovered);
        let secondary_pressed =
            spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);

        world
            .run_system_once(handle_pause_buttons)
            .expect("handle_pause_buttons should run");

        assert_eq!(background(&world, primary_idle), PRIMARY.normal);
        assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
        assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
        assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
        assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
        assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
    }

    #[test]
    fn settings_buttons_take_theme_colors_per_interaction_state() {
        let mut world = handler_world(Some(custom_theme()));
        let primary_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
        let primary_hovered = spawn_button(&mut world, SettingsButton::Back, Interaction::Hovered);
        let primary_pressed = spawn_button(&mut world, SettingsButton::Back, Interaction::Pressed);
        let secondary_idle = spawn_button(&mut world, SettingsButton::FovInc, Interaction::None);
        let secondary_hovered =
            spawn_button(&mut world, SettingsButton::VolumeDec, Interaction::Hovered);
        let secondary_pressed =
            spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);

        press(&mut world);

        assert_eq!(background(&world, primary_idle), PRIMARY.normal);
        assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
        assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
        assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
        assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
        assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
    }

    #[test]
    fn buttons_without_a_theme_resource_use_the_previous_colors() {
        let mut world = handler_world(None);
        let pause_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
        let pause_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
        let pause_pressed = spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);
        let settings_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
        let settings_hovered =
            spawn_button(&mut world, SettingsButton::FovInc, Interaction::Hovered);
        let settings_pressed =
            spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);

        world
            .run_system_once(handle_pause_buttons)
            .expect("handle_pause_buttons should run");
        press(&mut world);

        for idle in [pause_idle, settings_idle] {
            assert_eq!(background(&world, idle), Color::srgb(0.15, 0.15, 0.20));
        }
        for hovered in [pause_hovered, settings_hovered] {
            assert_eq!(background(&world, hovered), Color::srgb(0.25, 0.25, 0.35));
        }
        for pressed in [pause_pressed, settings_pressed] {
            assert_eq!(background(&world, pressed), Color::srgb(0.35, 0.35, 0.50));
        }
    }
}