calcli 0.3.0

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

use std::cell::Cell;
use std::collections::BTreeMap;

use anyhow::Result;
use crossterm::event::KeyEvent;
use ratada::autocomplete::{AcOutcome, Autocomplete};
use ratada::command_palette::CommandItem;
use ratada::quit::QuitConfirm;
use ratada::theme::{
    Color, ColorOverrides, DEFAULT_THEME, GlyphVariant, Glyphs, Palette, Skin,
    ThemeRegistry,
};
use ratada::{
    Flow, Screen, Tui, clipboard, modal, quit, shortcut_hints, style,
};
use ratatui::Frame;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

use crate::config::Config;
use crate::domain::completion;
use crate::domain::format::{AngleMode, Notation};
use crate::domain::highlight;
use crate::domain::quantity::Quantity;
use crate::keymap::{Action, Context, Keymap};
use crate::services::{CalcService, Preview};
use crate::storage::{
    PersistedEntry, PersistedSettings, PersistedState, PersistedValue, UiState,
};
use crate::tui::appframe::{self, FrameContext, HintGroups};
use crate::tui::bindings;
use crate::tui::colors::{CaretColors, Highlight, styles_for, to_ratatui};
use crate::tui::interaction::{Answer, Interaction, Modals, Selection};
use crate::tui::text_edit::{self, TextCursor};
use crate::tui::views::ViewId;
use crate::tui::views::calc::{
    self, CalcView, HistoryStyle, Metrics, Mode, Row,
};
use crate::tui::views::settings::{self, SettingsView};
use crate::tui::views::variables::{self, Variable, VariablesView};

/// The label of the closing hint group, shown in the footer and the help.
const GLOBAL_GROUP: &str = "Global";

/// The whole TUI state: the calculator service plus view-only fields.
pub struct App {
    service: CalcService,
    skin: Skin,
    registry: ThemeRegistry,
    theme: String,
    /// The `[appearance.colors]` overrides, re-applied whenever the theme
    /// changes so a runtime theme switch never loses them.
    overrides: BTreeMap<String, String>,
    keymap: Keymap,
    highlight: Highlight,
    confirm_delete: bool,

    history: HistoryStyle,
    input_max_lines: usize,
    live_feedback: bool,

    active: ViewId,
    input: String,
    cursor: TextCursor,
    /// The suggestion dropdown for the input field, rebuilt from the current
    /// variables plus the built-in names on every edit.
    autocomplete: Autocomplete,
    mode: Mode,
    selected: Option<usize>,
    var_selected: usize,
    setting_selected: usize,

    status: Option<String>,
    quit: bool,
    editing_inserted: bool,

    metrics: Cell<Metrics>,
    var_offset: Cell<usize>,
    setting_offset: Cell<usize>,
}

impl App {
    /// Builds the app from a configured service, the loaded config and the
    /// restored UI state.
    pub fn new(service: CalcService, config: &Config, ui: &UiState) -> Self {
        let registry = config.theme_registry();
        let skin =
            Skin::new(config.palette(), Glyphs::new(config.appearance.glyphs));
        let autocomplete =
            Autocomplete::new(completion::candidates(service.variables()));
        let mut app = App {
            service,
            skin,
            registry,
            theme: config.appearance.theme.clone(),
            overrides: config.appearance.colors.clone(),
            keymap: config.keymap(),
            highlight: Highlight::new(&config.highlight),
            confirm_delete: config.confirm_delete,
            history: HistoryStyle {
                spacing: config.history_spacing,
                separator: config
                    .history_separator
                    .then(|| to_ratatui(config.palette().border)),
            },
            input_max_lines: config.input_max_lines,
            live_feedback: config.live_feedback,
            active: ViewId::Calc,
            input: String::new(),
            cursor: TextCursor::at(0),
            autocomplete,
            mode: Mode::Input,
            selected: None,
            var_selected: 0,
            setting_selected: 0,
            status: None,
            quit: false,
            editing_inserted: false,
            metrics: Cell::new(Metrics::default()),
            var_offset: Cell::new(0),
            setting_offset: Cell::new(0),
        };
        for conflict in app.keymap.conflicts() {
            log::warn!(
                "key '{}' for '{}' is shadowed by '{}'",
                conflict.key,
                conflict.action.config_name(),
                conflict.claimed_by.config_name(),
            );
        }
        app.restore(ui);
        // Only the soft quit is questioned; `Ctrl+Q` stays the unconditional
        // escape hatch either way.
        quit::set_confirm(if config.confirm_quit {
            QuitConfirm::Soft
        } else {
            QuitConfirm::Never
        });
        app.install_quit_guard();
        app
    }

    /// Registers how the quit confirmation is drawn, with the current skin.
    /// Re-run from [`Self::set_skin`] so the dialog follows the active theme.
    fn install_quit_guard(&self) {
        let skin = self.skin;
        quit::set_guard(move |tui, _kind, background| {
            modal::confirm(tui, &skin, " Quit? ", background)
        });
    }

    /// The single seam for changing the skin: the quit guard holds a copy of it
    /// and has to be re-registered whenever the theme or the glyphs change.
    fn set_skin(&mut self, skin: Skin) {
        self.skin = skin;
        self.install_quit_guard();
    }

    /// Switches the active theme by name, falling back to the default when the
    /// name is unknown.
    ///
    /// The configured colour overrides are re-applied on top, exactly as at
    /// startup. Dropping them here would undo calcli's own defaults (the red
    /// block cursor, the input fills) on every restart, because restoring the
    /// persisted theme name comes through this path.
    fn set_theme(&mut self, name: &str) {
        let name = if self.registry.contains(name) {
            name.to_string()
        } else {
            log::warn!("unknown theme '{name}', using '{DEFAULT_THEME}'");
            DEFAULT_THEME.to_string()
        };
        let base = self.registry.resolve(&name);
        let mut skin = self.skin;
        skin.palette = Palette::resolve(base, &self.color_overrides());
        self.set_skin(skin);
        self.theme = name;
    }

    /// The configured colour overrides, layered over whichever theme is active.
    fn color_overrides(&self) -> ColorOverrides<'_> {
        ColorOverrides::from_lookup(|name| {
            self.overrides.get(name).map_or("", String::as_str)
        })
    }

    /// Switches the glyph variant.
    fn set_glyphs(&mut self, variant: GlyphVariant) {
        let mut skin = self.skin;
        skin.glyphs = Glyphs::new(variant);
        self.set_skin(skin);
    }

    /// Applies the persisted UI state.
    fn restore(&mut self, ui: &UiState) {
        self.active = ViewId::from_index(ui.active_view);
        if let Some(theme) = &ui.theme {
            self.set_theme(theme);
        }
        if let Some(glyphs) = ui.glyphs {
            self.set_glyphs(glyphs);
        }
        if let Some(visible) = ui.hints_visible {
            shortcut_hints::set_visible(visible);
        }
    }

    /// Snapshots the session for persistence: settings, UI, variables, history.
    pub fn persisted_state(&self) -> PersistedState {
        let settings = self.service.settings();
        let history =
            self.service
                .history()
                .entries()
                .iter()
                .map(|entry| PersistedEntry {
                    input: entry.input.clone(),
                    value: entry.value.as_ref().map(Quantity::display_value),
                    unit: entry.value.as_ref().and_then(|value| {
                        value.unit_symbol().map(str::to_string)
                    }),
                })
                .collect();
        let variables = self
            .service
            .variables()
            .iter()
            .map(|(name, value)| {
                (
                    name.clone(),
                    PersistedValue {
                        value: value.display_value(),
                        unit: value.unit_symbol().map(str::to_string),
                    },
                )
            })
            .collect();
        PersistedState {
            settings: Some(PersistedSettings {
                notation: settings.notation,
                decimals: settings.decimals,
                angle_mode: settings.angle_mode,
                decimal_separator: settings.decimal_separator.to_string(),
                trim_trailing_zeros: settings.trim_trailing_zeros,
            }),
            ui: UiState {
                active_view: self.active.index(),
                theme: Some(self.theme.clone()),
                glyphs: Some(self.skin.glyphs.variant),
                hints_visible: Some(shortcut_hints::visible()),
            },
            variables,
            history,
        }
    }

    /// The calculator service, for the integration tests.
    pub fn service(&self) -> &CalcService {
        &self.service
    }

    /// The warning marker for the current glyph set.
    fn warn(&self) -> &'static str {
        match self.skin.glyphs.variant {
            GlyphVariant::Unicode => "\u{26a0}",
            GlyphVariant::Ascii => "!",
        }
    }

    /// Which keymap context the current view and mode select.
    fn context(&self) -> Context {
        match (self.active, self.mode) {
            (ViewId::Calc, Mode::Input) => Context::Input,
            (ViewId::Calc, Mode::Edit(_)) => Context::Edit,
            (ViewId::Calc, Mode::History) => Context::History,
            (ViewId::Variables, _) => Context::Variables,
            (ViewId::Settings, _) => Context::Settings,
        }
    }

    /// The active skin, for the dialogs drawn over this view.
    pub(crate) fn skin(&self) -> &Skin {
        &self.skin
    }

    /// Asks before a destructive action, unless `confirm_delete` is off.
    ///
    /// A `Ctrl+Q` inside the dialog quits at once and the action is abandoned:
    /// the toolkit honours the hard quit everywhere, modals included.
    fn confirm(
        &mut self,
        io: &mut dyn Interaction,
        prompt: &str,
    ) -> Result<bool> {
        if !self.confirm_delete {
            return Ok(true);
        }
        let answer = io.confirm(self, prompt)?;
        self.absorb(answer);
        Ok(answer.is_yes())
    }

    /// Records a forced quit raised from inside a dialog.
    fn absorb(&mut self, answer: Answer) {
        if answer.is_forced_quit() {
            self.quit = true;
        }
    }
}

// --- Hints and help ---------------------------------------------------------

impl App {
    /// The closing `Global` group: the app's own chords first, then the
    /// toolkit's (`f1 toggle hints`, `ctrl+q force quit`). One helper feeds
    /// both the footer and the help overlay, so they cannot drift apart.
    fn global_group(&self) -> (String, Vec<(String, String)>) {
        let mut hints = self.keymap.hints(&[
            Action::OpenPalette,
            Action::OpenHelp,
            Action::Quit,
        ]);
        hints.extend(shortcut_hints::global_bindings());
        (GLOBAL_GROUP.to_string(), hints)
    }

    /// Renders one hint table into owned groups, dropping any that ended up
    /// empty because every action in it was unbound.
    fn groups_of(&self, table: &[bindings::Group]) -> HintGroups {
        table
            .iter()
            .filter_map(|(label, actions)| {
                let hints = self.keymap.hints(actions);
                (!hints.is_empty()).then(|| ((*label).to_string(), hints))
            })
            .collect()
    }

    /// The hint groups of the current view: its own groups, then the settings
    /// chords and the tab switches, closed by the `Global` group.
    ///
    /// An in-place edit locks the tab bar, so the `Views` group is left out
    /// there rather than promising a switch that will not happen.
    fn hint_groups(&self) -> HintGroups {
        let table = match (self.active, self.mode) {
            (ViewId::Calc, Mode::Input) => bindings::INPUT_HINT_GROUPS,
            (ViewId::Calc, Mode::Edit(_)) => bindings::EDIT_HINT_GROUPS,
            (ViewId::Calc, Mode::History) => bindings::HISTORY_HINT_GROUPS,
            (ViewId::Variables, _) => bindings::VARIABLES_HINT_GROUPS,
            (ViewId::Settings, _) => bindings::SETTINGS_HINT_GROUPS,
        };
        let mut groups = self.groups_of(table);
        groups.extend(self.groups_of(&[bindings::SETTINGS_CHORDS]));
        if !matches!(self.mode, Mode::Edit(_)) {
            groups.extend(self.groups_of(&[bindings::VIEW_GROUP]));
        }
        groups.push(self.global_group());
        groups
    }

    /// The help overlay's sections: every view's groups, the shared chords,
    /// then the same `Global` group the footer closes with.
    pub(crate) fn help_sections(&self) -> HintGroups {
        let mut sections: HintGroups = Vec::new();
        for (view, table) in bindings::HELP_TABLES {
            for (label, hints) in self.groups_of(table) {
                sections.push((format!("{view} \u{b7} {label}"), hints));
            }
        }
        sections.extend(self.groups_of(&[bindings::SETTINGS_CHORDS]));
        sections.extend(self.groups_of(&[bindings::VIEW_GROUP]));
        sections.push(self.global_group());
        sections
    }
}

// --- Rendering --------------------------------------------------------------

impl App {
    /// Draws the whole UI for one frame.
    fn render_body(&self, frame: &mut Frame) {
        let hints = self.hint_groups();
        let status_right = self.status.clone().unwrap_or_default();
        let content = appframe::render_frame(
            frame,
            &FrameContext {
                skin: &self.skin,
                tabs: ViewId::tabs(),
                active_tab: self.active.index(),
                tabs_locked: matches!(self.mode, Mode::Edit(_)),
                status_left: &self.settings_summary(),
                status_right: &status_right,
                hints: &hints,
            },
        );
        match self.active {
            ViewId::Calc => self.render_calc(frame, content),
            ViewId::Variables => self.render_variables(frame, content),
            ViewId::Settings => self.render_settings(frame, content),
        }
    }

    /// The always-visible settings summary in the status band.
    fn settings_summary(&self) -> String {
        let settings = self.service.settings();
        let values = [
            settings.angle_mode.label().to_string(),
            settings.notation.label().to_string(),
            format!("{} dp", settings.decimals),
            if settings.trim_trailing_zeros {
                "trim".to_string()
            } else {
                "fixed".to_string()
            },
            settings.decimal_separator.to_string(),
            settings::thousands_label(&settings.thousands_separator)
                .to_string(),
            settings::glyphs_label(self.skin.glyphs.variant).to_string(),
        ];
        values.join(" \u{b7} ")
    }

    /// Renders the calculator view and records its measurements.
    fn render_calc(&self, frame: &mut Frame, area: ratatui::layout::Rect) {
        let entries = self.service.history().entries();
        let rows: Vec<Row<'_>> = entries
            .iter()
            .map(|entry| Row {
                entry,
                result: entry
                    .value
                    .as_ref()
                    .map(|value| self.service.format_display(value))
                    .unwrap_or_default(),
            })
            .collect();
        let row_styles: Vec<Vec<Style>> = entries
            .iter()
            .map(|entry| self.styles_of(&entry.input))
            .collect();
        let input_styles = self.styles_of(&self.input);
        // Colour of the autocomplete suggestion text. Set a concrete RGB here.
        let completion_text = Color::Rgb(190, 190, 190);
        let completion = self.autocomplete.lines(
            &self.skin.palette,
            0,
            style::fg(completion_text),
        );

        let view = CalcView {
            rows: &rows,
            selected: self.selected,
            mode: self.mode,
            input: &self.input,
            cursor: self.cursor,
            input_styles: &input_styles,
            row_styles: &row_styles,
            completion,
            caret: CaretColors::from_palette(&self.skin.palette),
            style: HistoryStyle {
                spacing: self.history.spacing,
                separator: self.history.separator,
            },
            accent_color: to_ratatui(self.skin.palette.accent),
            error_color: to_ratatui(self.skin.palette.error),
            warn: self.warn(),
            feedback: self.live_feedback_line(),
            input_max_lines: self.input_max_lines,
        };
        self.metrics
            .set(calc::render(frame, area, &self.skin, &view));
    }

    /// The per-character highlight styles for `text`.
    fn styles_of(&self, text: &str) -> Vec<Style> {
        let kinds = highlight::classify(text, self.service.variables());
        styles_for(&kinds, &self.highlight)
    }

    /// The dim live-feedback line for the input border: a result preview when
    /// the expression is valid, a muted warning when it looks complete but
    /// invalid, and nothing while typing, empty or disabled.
    fn live_feedback_line(&self) -> Option<Line<'static>> {
        if !self.live_feedback
            || self.mode != Mode::Input
            || self.input.is_empty()
        {
            return None;
        }
        match self.service.preview(&self.input) {
            Preview::Value(value) => {
                let text =
                    format!(" = {} ", self.service.format_display(&value));
                let style = Style::default()
                    .fg(to_ratatui(self.skin.palette.accent))
                    .add_modifier(Modifier::DIM);
                Some(Line::from(Span::styled(text, style)))
            }
            Preview::Invalid => {
                let text = format!(" {} ", self.warn());
                let style = Style::default()
                    .fg(to_ratatui(self.skin.palette.error))
                    .add_modifier(Modifier::DIM);
                Some(Line::from(Span::styled(text, style)))
            }
            Preview::Empty | Preview::Incomplete => None,
        }
    }

    /// Renders the variables view.
    fn render_variables(&self, frame: &mut Frame, area: ratatui::layout::Rect) {
        let variables = self.variable_rows();
        variables::render(
            frame,
            area,
            &self.skin,
            &VariablesView {
                variables: &variables,
                selected: self.var_selected,
                offset: &self.var_offset,
            },
        );
    }

    /// The variables, formatted for display.
    fn variable_rows(&self) -> Vec<Variable> {
        self.service
            .variables()
            .iter()
            .map(|(name, value)| Variable {
                name: name.clone(),
                value: self.service.format_display(value),
            })
            .collect()
    }

    /// Renders the settings view.
    fn render_settings(&self, frame: &mut Frame, area: ratatui::layout::Rect) {
        settings::render(
            frame,
            area,
            &self.skin,
            &SettingsView {
                values: self.setting_values(),
                selected: self.setting_selected,
                offset: &self.setting_offset,
            },
        );
    }

    /// The values the settings rows read from.
    fn setting_values(&self) -> settings::Values<'_> {
        settings::Values {
            settings: self.service.settings(),
            glyphs: self.skin.glyphs.variant,
            theme: &self.theme,
        }
    }
}

// --- Key handling -----------------------------------------------------------

impl Screen for App {
    type Error = anyhow::Error;

    fn render(&self, frame: &mut Frame) {
        self.render_body(frame);
    }

    fn handle_key(&mut self, key: KeyEvent, tui: &mut Tui) -> Result<Flow> {
        let mut modals = Modals::new(tui);
        self.dispatch(key, &mut modals)
    }
}

impl App {
    /// Whether the loop should keep running.
    fn flow(&self) -> Flow {
        if self.quit {
            Flow::Quit
        } else {
            Flow::Continue
        }
    }

    /// Handles one key press against `io`, the port the dialogs open through.
    ///
    /// Separated from [`Screen::handle_key`] so a test can drive the whole key
    /// path with a terminal-free [`Interaction`].
    pub(crate) fn dispatch(
        &mut self,
        key: KeyEvent,
        io: &mut dyn Interaction,
    ) -> Result<Flow> {
        // A transient status clears on the next key press.
        self.status = None;
        let context = self.context();

        // An open suggestion dropdown claims its own navigation keys first, so
        // `Up`/`Down`/`Enter`/`Esc` steer it rather than the input field. Keys
        // it ignores fall through to the normal path.
        if self.autocomplete.is_open() {
            match self.autocomplete.on_key(key) {
                AcOutcome::Accepted(value) => {
                    self.accept_completion(&value);
                    return Ok(self.flow());
                }
                AcOutcome::Navigated | AcOutcome::Closed => {
                    return Ok(self.flow());
                }
                AcOutcome::Ignored => {}
            }
        }

        let handled = match self.keymap.action_for(&key, context) {
            Some(action) => self.apply_action(action, io)?,
            None => false,
        };
        // Anything the keymap did not claim belongs to the text editor.
        if !handled && context.is_text_editing() {
            self.apply_edit_key(key);
        }
        self.refresh_completion();
        Ok(self.flow())
    }

    /// Rebuilds the suggestion dropdown from the current variables and the
    /// built-in names, matched against the identifier under the caret. Only the
    /// input field completes; every other context leaves the dropdown closed.
    fn refresh_completion(&mut self) {
        // Only the input field completes. `mode` alone is not enough: it stays
        // `Input` after switching to another view, so gate on the full context
        // or the dropdown would linger there and steal `Up`/`Down`.
        let query = if self.context() == Context::Input {
            let range =
                completion::identifier_before(&self.input, self.cursor.pos);
            self.input
                .chars()
                .take(range.end)
                .skip(range.start)
                .collect()
        } else {
            String::new()
        };
        self.autocomplete =
            Autocomplete::new(completion::candidates(self.service.variables()));
        self.autocomplete.refresh(&query);
    }

    /// Replaces the whole identifier under the caret with an accepted
    /// suggestion, so completing mid-word rewrites all of it rather than
    /// leaving its tail behind.
    fn accept_completion(&mut self, value: &str) {
        let range = completion::identifier_at(&self.input, self.cursor.pos);
        self.cursor.move_to(range.start);
        self.cursor.extend_to(range.end);
        text_edit::replace_selection(&mut self.input, &mut self.cursor, value);
    }

    /// Applies `action`, returning whether it was consumed.
    fn apply_action(
        &mut self,
        action: Action,
        io: &mut dyn Interaction,
    ) -> Result<bool> {
        if self.apply_global_action(action, io)? {
            return Ok(true);
        }
        match self.context() {
            Context::Input => self.apply_input_action(action, io),
            Context::Edit => self.apply_edit_action(action),
            Context::History => self.apply_history_action(action, io),
            Context::Variables => self.apply_variables_action(action, io),
            Context::Settings => Ok(self.apply_settings_action(action)),
        }
    }

    /// Applies an action that works in every view; returns whether it did.
    fn apply_global_action(
        &mut self,
        action: Action,
        io: &mut dyn Interaction,
    ) -> Result<bool> {
        match action {
            Action::ViewCalc => self.switch_to(ViewId::Calc),
            Action::ViewVariables => self.switch_to(ViewId::Variables),
            Action::ViewSettings => self.switch_to(ViewId::Settings),
            Action::CycleNotation => {
                self.service.cycle_notation();
                self.report(format!(
                    "notation: {}",
                    self.service.settings().notation.label()
                ));
            }
            Action::ToggleAngle => {
                self.service.toggle_angle_mode();
                self.report(format!(
                    "angle: {}",
                    self.service.settings().angle_mode.label()
                ));
            }
            Action::ToggleDecimalSeparator => {
                self.service.toggle_decimal_separator();
                self.report(format!(
                    "decimal separator: {}",
                    self.service.settings().decimal_separator
                ));
            }
            Action::ToggleTrim => {
                self.service.toggle_trim_trailing_zeros();
                let state = if self.service.settings().trim_trailing_zeros {
                    "trimmed"
                } else {
                    "fixed"
                };
                self.report(format!("trailing zeros: {state}"));
            }
            Action::CopyLast => match self.service.history().last_value() {
                Some(value) => self.copy_plain(&value),
                None => self.report("no result yet".to_string()),
            },
            Action::SearchHistory => self.search_history(io)?,
            Action::OpenPalette => self.open_palette(io)?,
            Action::OpenHelp => {
                let answer = io.help(self)?;
                self.absorb(answer);
            }
            Action::Quit => self.request_quit(io),
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Switches views, unless an in-place edit locks the tab bar.
    fn switch_to(&mut self, view: ViewId) {
        if matches!(self.mode, Mode::Edit(_)) {
            self.report("finish the edit first".to_string());
            return;
        }
        self.active = view;
    }

    /// Raises the soft quit, which the toolkit questions when configured to.
    fn request_quit(&mut self, io: &mut dyn Interaction) {
        if io.may_quit(self) {
            self.quit = true;
        }
    }

    /// Opens the fuzzy history finder and recalls the chosen expression into
    /// the input. A `Ctrl+Q` inside it quits the app.
    fn search_history(&mut self, io: &mut dyn Interaction) -> Result<()> {
        let items: Vec<String> = self
            .service
            .history()
            .entries()
            .iter()
            .rev()
            .map(|entry| entry.input.clone())
            .collect();
        if items.is_empty() {
            self.report("no history yet".to_string());
            return Ok(());
        }
        match io.pick(self, " Search history ", &items)? {
            Selection::Index(index) => self.recall(&items[index]),
            Selection::None => {}
            Selection::ForcedQuit => self.quit = true,
        }
        Ok(())
    }

    /// Recalls `expression` into the input field on the Calc view, caret at the
    /// end, ready to edit or submit.
    fn recall(&mut self, expression: &str) {
        self.active = ViewId::Calc;
        self.mode = Mode::Input;
        self.selected = None;
        self.input = expression.to_string();
        self.cursor = TextCursor::at(self.input.chars().count());
    }

    /// Opens the command palette and runs the chosen action. Every action but
    /// the palette itself is listed; one unavailable in the current context is
    /// shown dimmed and cannot be picked. A `Ctrl+Q` inside it quits the app.
    fn open_palette(&mut self, io: &mut dyn Interaction) -> Result<()> {
        let context = self.context();
        let actions: Vec<Action> = Action::all()
            .filter(|a| *a != Action::OpenPalette)
            .collect();
        // The key hints are owned here so the borrowed `CommandItem`s can point
        // into them for the length of the call.
        let keys: Vec<String> = actions
            .iter()
            .map(|action| self.keymap.keys_for(*action).join(", "))
            .collect();
        let items: Vec<CommandItem<'_>> = actions
            .iter()
            .zip(&keys)
            .map(|(action, key_hint)| CommandItem {
                label: action.description(),
                category: bindings::category_of(*action),
                key_hint,
                enabled: action.scope().is_active_in(context),
            })
            .collect();
        match io.palette(self, &items)? {
            Selection::Index(index) => {
                self.apply_action(actions[index], io)?;
            }
            Selection::None => {}
            Selection::ForcedQuit => self.quit = true,
        }
        Ok(())
    }

    /// Records a transient status message.
    fn report(&mut self, message: String) {
        self.status = Some(message);
    }
}

// --- The calc view ----------------------------------------------------------

impl App {
    /// Applies an action while typing an expression.
    fn apply_input_action(
        &mut self,
        action: Action,
        io: &mut dyn Interaction,
    ) -> Result<bool> {
        match action {
            Action::Submit => self.submit_input(io)?,
            Action::ClearInput => {
                self.input.clear();
                self.cursor = TextCursor::at(0);
            }
            Action::EnterHistory => {
                // `Up` only leaves the field from its first display line, so a
                // wrapped expression stays navigable.
                if !self.cursor_is_on_first_line() {
                    return Ok(false);
                }
                self.enter_history();
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Whether the caret sits on the input's first display line.
    fn cursor_is_on_first_line(&self) -> bool {
        let width = self.metrics.get().input_width.max(1);
        let offsets = text_edit::wrap_offsets(&self.input, width);
        let total = self.input.chars().count();
        let (line, _) =
            text_edit::cursor_to_display(&offsets, total, self.cursor.pos);
        line == 0
    }

    /// Evaluates the input buffer (or runs a `:` command) and clears it.
    fn submit_input(&mut self, io: &mut dyn Interaction) -> Result<()> {
        let text = self.input.trim().to_string();
        if text.is_empty() {
            return Ok(());
        }
        // Drop the inline comment to detect a `:` command; otherwise the full
        // text is submitted (a comment-only line becomes a note entry).
        let code = crate::domain::expression::strip_comment(&text).trim();
        if let Some(command) = code.strip_prefix(':') {
            let command = command.to_string();
            self.input.clear();
            self.cursor = TextCursor::at(0);
            let message = self.run_command(&command, io)?;
            self.status = Some(message);
            return Ok(());
        }
        let outcome = self.service.submit(&text);
        self.status = Some(self.outcome_status(&outcome));
        self.selected = None;
        self.input.clear();
        self.cursor = TextCursor::at(0);
        Ok(())
    }

    /// The status message for a submitted line.
    fn outcome_status(
        &self,
        outcome: &crate::services::SubmitOutcome,
    ) -> String {
        match (&outcome.value, &outcome.error) {
            (_, Some(error)) => error.clone(),
            (Some(value), None) => {
                format!("= {}", self.service.format_display(value))
            }
            (None, None) => String::new(),
        }
    }

    /// Runs a `:` command (without the leading colon), returning a status line.
    fn run_command(
        &mut self,
        command: &str,
        io: &mut dyn Interaction,
    ) -> Result<String> {
        let message = match command.trim() {
            // The soft quit, questioned when `confirm_quit` is on. `Ctrl+Q`
            // stays the unconditional escape hatch.
            "q" | "quit" => {
                self.request_quit(io);
                String::new()
            }
            "deg" => {
                self.service.set_angle_mode(AngleMode::Deg);
                "angle: DEG".to_string()
            }
            "rad" => {
                self.service.set_angle_mode(AngleMode::Rad);
                "angle: RAD".to_string()
            }
            "clear" => {
                self.clear_history(io)?;
                self.status.clone().unwrap_or_default()
            }
            other => self.run_notation_command(other),
        };
        Ok(message)
    }

    /// Parses the `:d`/`:s`/`:si` notation commands with optional decimals.
    fn run_notation_command(&mut self, command: &str) -> String {
        let (notation, rest) = if let Some(rest) = command.strip_prefix("si") {
            (Notation::SiPrefixed, rest)
        } else if let Some(rest) = command.strip_prefix('d') {
            (Notation::Decimal, rest)
        } else if let Some(rest) = command.strip_prefix('s') {
            (Notation::Scientific, rest)
        } else {
            return format!("unknown command ':{command}'");
        };
        self.service.set_notation(notation);
        if rest.is_empty() {
            return format!("notation: {}", notation.label());
        }
        match rest.parse::<usize>() {
            Ok(decimals) => {
                self.service.set_decimals(decimals);
                format!("notation: {} ({decimals} dp)", notation.label())
            }
            Err(_) => format!("invalid decimals: '{rest}'"),
        }
    }

    /// Enters history navigation, selecting the most recent line.
    fn enter_history(&mut self) {
        let total = self.service.history().len();
        if total == 0 {
            return;
        }
        self.mode = Mode::History;
        self.selected = Some(total - 1);
    }

    /// Returns from history navigation to the input field.
    fn leave_history(&mut self) {
        self.mode = Mode::Input;
        self.selected = None;
    }

    /// Applies an action while browsing the history.
    fn apply_history_action(
        &mut self,
        action: Action,
        io: &mut dyn Interaction,
    ) -> Result<bool> {
        let Some(index) = self.selected else {
            self.mode = Mode::Input;
            return Ok(false);
        };
        let total = self.service.history().len();
        let last = total.saturating_sub(1);
        let page = self.metrics.get().view_height.max(1);
        match action {
            Action::Up => self.selected = Some(index.saturating_sub(1)),
            Action::Down => {
                if index < last {
                    self.selected = Some(index + 1);
                } else {
                    self.leave_history();
                }
            }
            Action::Top => self.selected = Some(0),
            Action::Bottom => self.selected = Some(last),
            Action::PageUp => self.selected = Some(index.saturating_sub(page)),
            Action::PageDown => self.selected = Some((index + page).min(last)),
            Action::MoveUp => self.move_selected(index, -1),
            Action::MoveDown => self.move_selected(index, 1),
            Action::CopyPlain => self.copy_selected(index, false),
            Action::CopyDisplay => self.copy_selected(index, true),
            Action::EditEntry => self.start_edit(index),
            Action::InsertBelow => self.insert_line(index + 1),
            Action::InsertAbove => self.insert_line(index),
            Action::DeleteEntry => self.delete_entry(index, io)?,
            Action::ClearHistory => self.clear_history(io)?,
            Action::Back => self.leave_history(),
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Moves the selected entry by `delta` and follows it with the selection.
    fn move_selected(&mut self, index: usize, delta: isize) {
        self.selected = Some(self.service.move_entry(index, delta));
    }

    /// Inserts a blank entry at `at` and starts editing it immediately.
    fn insert_line(&mut self, at: usize) {
        self.service.insert_entry(at);
        self.selected = Some(at);
        self.start_edit(at);
        self.editing_inserted = true;
    }

    /// Begins editing history entry `index` in place.
    fn start_edit(&mut self, index: usize) {
        let Some(entry) = self.service.history().entries().get(index) else {
            return;
        };
        self.input = entry.input.clone();
        self.cursor = TextCursor::at(self.input.chars().count());
        self.mode = Mode::Edit(index);
        self.editing_inserted = false;
    }

    /// Asks, then deletes history entry `index`.
    fn delete_entry(
        &mut self,
        index: usize,
        io: &mut dyn Interaction,
    ) -> Result<()> {
        if !self.confirm(io, " Delete this line? ")? {
            return Ok(());
        }
        self.service.delete_entry(index);
        let total = self.service.history().len();
        if total == 0 {
            self.leave_history();
        } else {
            self.selected = Some(index.min(total - 1));
        }
        self.report("line deleted".to_string());
        Ok(())
    }

    /// Asks, then clears the whole history.
    fn clear_history(&mut self, io: &mut dyn Interaction) -> Result<()> {
        if self.service.history().is_empty() {
            self.report("history is already empty".to_string());
            return Ok(());
        }
        if !self.confirm(io, " Clear the entire history? ")? {
            return Ok(());
        }
        self.service.clear_history();
        self.leave_history();
        self.report("history cleared".to_string());
        Ok(())
    }

    /// Copies the value of history entry `index`, plain or as displayed.
    fn copy_selected(&mut self, index: usize, as_displayed: bool) {
        let value = self
            .service
            .history()
            .entries()
            .get(index)
            .and_then(|entry| entry.value.clone());
        match value {
            Some(value) if as_displayed => self.copy_display(&value),
            Some(value) => self.copy_plain(&value),
            None => self.report("no value to copy".to_string()),
        }
    }

    /// Applies an action while editing a history line in place.
    fn apply_edit_action(&mut self, action: Action) -> Result<bool> {
        let Mode::Edit(index) = self.mode else {
            return Ok(false);
        };
        match action {
            Action::ApplyEdit => {
                let text = self.input.clone();
                self.service.edit_entry(index, &text);
                self.editing_inserted = false;
                self.finish_edit(index);
                self.report("line updated".to_string());
            }
            Action::CancelEdit => {
                if self.editing_inserted {
                    self.cancel_insert(index);
                } else {
                    self.finish_edit(index);
                }
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Leaves edit mode back to history navigation.
    fn finish_edit(&mut self, index: usize) {
        self.mode = Mode::History;
        self.selected = Some(index);
        self.input.clear();
        self.cursor = TextCursor::at(0);
    }

    /// Cancels a freshly inserted line: removes the blank entry and returns to
    /// history navigation.
    fn cancel_insert(&mut self, index: usize) {
        self.editing_inserted = false;
        self.service.delete_entry(index);
        self.input.clear();
        self.cursor = TextCursor::at(0);
        let total = self.service.history().len();
        if total == 0 {
            self.leave_history();
        } else {
            self.mode = Mode::History;
            self.selected = Some(index.min(total - 1));
        }
    }

    /// Feeds a key the keymap did not claim to the text editor.
    fn apply_edit_key(&mut self, key: KeyEvent) {
        if text_edit::handle_clipboard(&mut self.input, &mut self.cursor, key) {
            return;
        }
        // The in-place editor wraps at the history width, as the entry is
        // shown.
        let metrics = self.metrics.get();
        let width = match self.mode {
            Mode::Edit(_) => metrics.history_width,
            _ => metrics.input_width,
        }
        .max(1);
        text_edit::apply_edit_key(
            &mut self.input,
            &mut self.cursor,
            key,
            text_edit::EditMode::Multiline { width },
        );
    }
}

// --- The variables view -----------------------------------------------------

impl App {
    /// Applies an action in the variables list.
    fn apply_variables_action(
        &mut self,
        action: Action,
        io: &mut dyn Interaction,
    ) -> Result<bool> {
        let total = self.service.variables().len();
        match action {
            Action::Up => {
                self.var_selected =
                    ratada::nav::cycle(self.var_selected, total, -1);
            }
            Action::Down => {
                self.var_selected =
                    ratada::nav::cycle(self.var_selected, total, 1);
            }
            Action::Top => self.var_selected = 0,
            Action::Bottom => self.var_selected = total.saturating_sub(1),
            Action::InsertVariable => self.insert_variable(),
            Action::CopyPlain => self.copy_variable(false),
            Action::CopyDisplay => self.copy_variable(true),
            Action::DeleteVariable => self.delete_variable(),
            Action::ResetVariables => self.reset_variables(io)?,
            Action::Back => self.active = ViewId::Calc,
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// The name and value of the currently selected variable, if any.
    fn selected_variable(&self) -> Option<(String, Quantity)> {
        self.service
            .variables()
            .iter()
            .nth(self.var_selected)
            .map(|(name, value)| (name.clone(), value.clone()))
    }

    /// Inserts the selected variable's name into the input and returns to Calc.
    fn insert_variable(&mut self) {
        let Some((name, _)) = self.selected_variable() else {
            return;
        };
        text_edit::replace_selection(&mut self.input, &mut self.cursor, &name);
        self.active = ViewId::Calc;
        self.mode = Mode::Input;
        self.report(format!("inserted {name}"));
    }

    /// Copies the selected variable's value, plain or as displayed.
    fn copy_variable(&mut self, as_displayed: bool) {
        let Some((_, value)) = self.selected_variable() else {
            return;
        };
        if as_displayed {
            self.copy_display(&value);
        } else {
            self.copy_plain(&value);
        }
    }

    /// Deletes the selected variable and keeps a valid selection.
    fn delete_variable(&mut self) {
        let Some((name, _)) = self.selected_variable() else {
            return;
        };
        self.service.remove_variable(&name);
        let total = self.service.variables().len();
        self.var_selected = self.var_selected.min(total.saturating_sub(1));
        self.report(format!("removed {name}"));
    }

    /// Asks, then removes every variable.
    fn reset_variables(&mut self, io: &mut dyn Interaction) -> Result<()> {
        if self.service.variables().is_empty() {
            return Ok(());
        }
        if !self.confirm(io, " Reset all variables? ")? {
            return Ok(());
        }
        self.service.reset_variables();
        self.var_selected = 0;
        self.report("variables reset".to_string());
        Ok(())
    }
}

// --- The settings view ------------------------------------------------------

impl App {
    /// Applies an action in the settings list.
    fn apply_settings_action(&mut self, action: Action) -> bool {
        let rows = settings::Row::all().len();
        match action {
            Action::Up => {
                self.setting_selected =
                    ratada::nav::cycle(self.setting_selected, rows, -1);
            }
            Action::Down => {
                self.setting_selected =
                    ratada::nav::cycle(self.setting_selected, rows, 1);
            }
            Action::Top => self.setting_selected = 0,
            Action::Bottom => self.setting_selected = rows - 1,
            Action::PreviousValue => self.step_setting(-1),
            Action::NextValue => self.step_setting(1),
            Action::Back => self.active = ViewId::Calc,
            _ => return false,
        }
        true
    }

    /// Steps the focused setting's value by `delta`, applied live.
    fn step_setting(&mut self, delta: isize) {
        let row = settings::Row::at(self.setting_selected);
        match row {
            settings::Row::Notation => {
                let next = settings::step_notation(
                    self.service.settings().notation,
                    delta,
                );
                self.service.set_notation(next);
            }
            settings::Row::Decimals => {
                let next = settings::step_decimals(
                    self.service.settings().decimals,
                    delta,
                );
                self.service.set_decimals(next);
            }
            settings::Row::AngleMode => {
                let next = settings::step_angle(
                    self.service.settings().angle_mode,
                    delta,
                );
                self.service.set_angle_mode(next);
            }
            settings::Row::TrailingZeros => {
                self.service.toggle_trim_trailing_zeros();
            }
            settings::Row::DecimalSeparator => {
                self.service.toggle_decimal_separator();
            }
            settings::Row::ThousandsSeparator => {
                let next = settings::step_thousands(
                    &self.service.settings().thousands_separator,
                    delta,
                );
                self.service.set_thousands_separator(next);
            }
            settings::Row::Glyphs => {
                let next = match self.skin.glyphs.variant {
                    GlyphVariant::Unicode => GlyphVariant::Ascii,
                    GlyphVariant::Ascii => GlyphVariant::Unicode,
                };
                self.set_glyphs(next);
            }
            settings::Row::Theme => {
                let next = self.registry.next(&self.theme);
                self.set_theme(&next);
            }
        }
        let value = self.setting_values().of(row);
        self.report(format!("{}: {value}", row.label()));
    }
}

// --- Clipboard --------------------------------------------------------------

impl App {
    /// Copies `value` as a plain, full-precision value (the `y` behaviour).
    fn copy_plain(&mut self, value: &Quantity) {
        let text = self.service.format_plain(value);
        self.report(copy_status(&text));
    }

    /// Copies `value` as displayed: rounded and grouped (the `Y` behaviour).
    fn copy_display(&mut self, value: &Quantity) {
        let text = self.service.format_display(value);
        self.report(copy_status(&text));
    }
}

/// Copies `text` to the clipboard and returns a status message either way.
fn copy_status(text: &str) -> String {
    if clipboard::copy(text) {
        format!("copied {text}")
    } else {
        "clipboard unavailable".to_string()
    }
}

#[cfg(test)]
mod tests {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    use super::*;
    use crate::config::CALCLI_THEME;
    use crate::domain::evaluator::MevalEvaluator;
    use crate::domain::history::History;
    use crate::domain::variables::VariableStore;
    use crate::tui::interaction::Headless;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn chord(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, modifiers)
    }

    fn test_app() -> App {
        let config = Config::default();
        let service = CalcService::new(
            Box::new(MevalEvaluator::new()),
            config.format_settings(),
            History::new(100),
            VariableStore::new(),
        );
        App::new(service, &config, &UiState::default())
    }

    /// Presses `key`, answering every confirmation with yes.
    fn press(app: &mut App, key: KeyEvent) {
        app.dispatch(key, &mut Headless::accepting())
            .expect("dispatch must not fail headlessly");
    }

    /// Types `text` then submits it.
    fn submit(app: &mut App, text: &str) {
        for character in text.chars() {
            press(app, key(KeyCode::Char(character)));
        }
        press(app, key(KeyCode::Enter));
    }

    /// The display value of history entry `index`.
    fn value_at(app: &App, index: usize) -> Option<f64> {
        app.service().history().entries()[index]
            .value
            .as_ref()
            .map(Quantity::display_value)
    }

    /// Renders `app` into a test terminal and returns the screen text.
    fn render_to_string(app: &App, width: u16, height: u16) -> String {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("test terminal");
        // The measurements the key handling reads are recorded while drawing.
        terminal.draw(|frame| app.render(frame)).expect("draw");
        terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|cell| cell.symbol())
            .collect()
    }

    // --- Typing and evaluating ---

    #[test]
    fn typing_and_enter_records_a_result() {
        let mut app = test_app();
        submit(&mut app, "2+3");
        assert_eq!(
            app.service()
                .history()
                .last_value()
                .map(|q| q.display_value()),
            Some(5.0),
        );
        assert!(render_to_string(&app, 80, 24).contains("= 5"));
    }

    #[test]
    fn a_bare_digit_is_typed_rather_than_switching_tabs() {
        let mut app = test_app();
        for character in "123".chars() {
            press(&mut app, key(KeyCode::Char(character)));
        }
        assert_eq!(app.input, "123");
        assert_eq!(app.active, ViewId::Calc);
    }

    #[test]
    fn q_and_question_mark_are_typed_into_an_expression() {
        let mut app = test_app();
        press(&mut app, key(KeyCode::Char('q')));
        press(&mut app, key(KeyCode::Char('?')));
        assert_eq!(app.input, "q?");
        assert!(!app.quit);
    }

    #[test]
    fn alt_digits_switch_views_while_typing() {
        let mut app = test_app();
        press(&mut app, chord(KeyCode::Char('2'), KeyModifiers::ALT));
        assert_eq!(app.active, ViewId::Variables);
        press(&mut app, chord(KeyCode::Char('3'), KeyModifiers::ALT));
        assert_eq!(app.active, ViewId::Settings);
        press(&mut app, chord(KeyCode::Char('1'), KeyModifiers::ALT));
        assert_eq!(app.active, ViewId::Calc);
        press(&mut app, key(KeyCode::F(4)));
        assert_eq!(app.active, ViewId::Variables);
    }

    #[test]
    fn alt_gr_types_a_digit_instead_of_switching_views() {
        let mut app = test_app();
        let alt_gr = KeyModifiers::ALT | KeyModifiers::CONTROL;
        press(&mut app, chord(KeyCode::Char('2'), alt_gr));
        assert_eq!(app.active, ViewId::Calc, "AltGr must not switch tabs");
    }

    #[test]
    fn function_keys_toggle_settings_from_the_input() {
        let mut app = test_app();
        assert_eq!(app.service().settings().angle_mode, AngleMode::Rad);
        press(&mut app, key(KeyCode::F(3)));
        assert_eq!(app.service().settings().angle_mode, AngleMode::Deg);

        assert_eq!(app.service().settings().decimal_separator, '.');
        press(&mut app, key(KeyCode::F(5)));
        assert_eq!(app.service().settings().decimal_separator, ',');

        assert!(app.service().settings().trim_trailing_zeros);
        press(&mut app, key(KeyCode::F(6)));
        assert!(!app.service().settings().trim_trailing_zeros);
        assert_eq!(app.status.as_deref(), Some("trailing zeros: fixed"));
    }

    // --- Autocomplete ---

    /// Types `text` character by character through the normal key path.
    fn type_text(app: &mut App, text: &str) {
        for character in text.chars() {
            press(app, key(KeyCode::Char(character)));
        }
    }

    #[test]
    fn typing_an_identifier_prefix_opens_the_suggestion_dropdown() {
        let mut app = test_app();
        type_text(&mut app, "si");
        assert!(app.autocomplete.is_open());
        // Hide the hints so the history area has room for the dropdown box;
        // otherwise the grouped hints squeeze it out (content wins).
        shortcut_hints::set_visible(false);
        let screen = render_to_string(&app, 40, 24);
        shortcut_hints::set_visible(true);
        assert!(screen.contains("sin"));
    }

    #[test]
    fn a_caret_after_an_operator_offers_no_suggestions() {
        let mut app = test_app();
        type_text(&mut app, "2+");
        assert!(!app.autocomplete.is_open());
    }

    #[test]
    fn navigating_and_confirming_replaces_the_typed_prefix() {
        let mut app = test_app();
        type_text(&mut app, "si");
        press(&mut app, key(KeyCode::Down));
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(app.input, "sin");
        assert!(!app.autocomplete.is_open());
    }

    #[test]
    fn a_suggestion_replaces_only_the_word_under_the_caret() {
        let mut app = test_app();
        type_text(&mut app, "2*co");
        press(&mut app, key(KeyCode::Down));
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(app.input, "2*cos");
    }

    #[test]
    fn accepting_mid_word_rewrites_the_whole_identifier() {
        let mut app = test_app();
        render_to_string(&app, 80, 24);
        type_text(&mut app, "sinh");
        // Move the caret into the middle of the word: `si|nh`.
        press(&mut app, key(KeyCode::Left));
        press(&mut app, key(KeyCode::Left));
        // The first match for the `si` prefix is `sin`; accepting it must
        // replace the whole `sinh`, not just its head (which left `sinnh`).
        press(&mut app, key(KeyCode::Down));
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(app.input, "sin");
    }

    #[test]
    fn a_bare_number_offers_no_suggestions() {
        let mut app = test_app();
        type_text(&mut app, "42");
        assert!(!app.autocomplete.is_open());
    }

    #[test]
    fn the_dropdown_never_overwrites_the_header_on_a_short_terminal() {
        let mut app = test_app();
        type_text(&mut app, "si");
        assert!(app.autocomplete.is_open());
        // Too short for the box above the input: it is dropped rather than
        // spilling up over the tab bar.
        let screen = render_to_string(&app, 40, 14);
        assert!(screen.contains("Calc"), "the tab bar must survive intact");
    }

    #[test]
    fn escape_closes_the_dropdown_before_clearing_the_input() {
        let mut app = test_app();
        type_text(&mut app, "si");
        press(&mut app, key(KeyCode::Esc));
        assert!(!app.autocomplete.is_open());
        assert_eq!(app.input, "si", "the first Esc only closes the dropdown");
        press(&mut app, key(KeyCode::Esc));
        assert_eq!(app.input, "", "a second Esc clears the input");
    }

    #[test]
    fn enter_submits_when_no_suggestion_is_highlighted() {
        let mut app = test_app();
        type_text(&mut app, "1+2");
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(value_at(&app, 0), Some(3.0));
        assert!(!app.autocomplete.is_open());
    }

    #[test]
    fn a_defined_variable_is_offered_as_a_suggestion() {
        let mut app = test_app();
        submit(&mut app, "radius = 5");
        type_text(&mut app, "rad");
        assert!(app.autocomplete.is_open());
        press(&mut app, key(KeyCode::Down));
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(app.input, "radius");
    }

    #[test]
    fn switching_views_closes_the_dropdown() {
        let mut app = test_app();
        type_text(&mut app, "si");
        assert!(app.autocomplete.is_open());
        // The Variables view must own `Up`/`Down`, not a lingering dropdown.
        press(&mut app, chord(KeyCode::Char('2'), KeyModifiers::ALT));
        assert_eq!(app.active, ViewId::Variables);
        assert!(!app.autocomplete.is_open());
    }

    #[test]
    fn page_up_still_enters_history_while_the_dropdown_is_open() {
        let mut app = test_app();
        submit(&mut app, "7");
        type_text(&mut app, "si");
        // A wide render puts the caret on the first line, so `Up` would qualify
        // too; `PageUp` is the guaranteed escape while the dropdown owns `Up`.
        render_to_string(&app, 80, 24);
        assert!(app.autocomplete.is_open());
        press(&mut app, key(KeyCode::PageUp));
        assert_eq!(app.mode, Mode::History);
    }

    // --- History search ---

    #[test]
    fn searching_recalls_the_chosen_expression_into_the_input() {
        let mut app = test_app();
        submit(&mut app, "1+1");
        submit(&mut app, "2*3");
        // Items are newest first, so index 1 is the older "1+1".
        let mut io = Headless::accepting().picking(1);
        app.dispatch(chord(KeyCode::Char('r'), KeyModifiers::CONTROL), &mut io)
            .expect("dispatch");
        assert_eq!(app.input, "1+1");
        assert_eq!(app.mode, Mode::Input);
        assert_eq!(app.cursor.pos, 3);
    }

    #[test]
    fn dismissing_the_search_leaves_the_input_untouched() {
        let mut app = test_app();
        submit(&mut app, "9-4");
        type_text(&mut app, "5+");
        let mut io = Headless::declining();
        app.dispatch(chord(KeyCode::Char('r'), KeyModifiers::CONTROL), &mut io)
            .expect("dispatch");
        assert_eq!(app.input, "5+");
    }

    #[test]
    fn searching_an_empty_history_reports_and_opens_nothing() {
        let mut app = test_app();
        let mut io = Headless::accepting().picking(0);
        app.dispatch(chord(KeyCode::Char('r'), KeyModifiers::CONTROL), &mut io)
            .expect("dispatch");
        assert_eq!(io.asked, 0, "no picker opens without history");
        assert_eq!(app.status.as_deref(), Some("no history yet"));
    }

    #[test]
    fn a_forced_quit_inside_the_search_quits_the_app() {
        let mut app = test_app();
        submit(&mut app, "1");
        let mut io = Headless::force_quitting();
        app.dispatch(chord(KeyCode::Char('r'), KeyModifiers::CONTROL), &mut io)
            .expect("dispatch");
        assert!(app.quit);
    }

    // --- Command palette ---

    #[test]
    fn the_palette_runs_the_chosen_action() {
        let mut app = test_app();
        // The catalog lists ToggleAngle before the palette entry, so it keeps
        // its index once the palette itself is filtered out.
        let index = Action::all()
            .filter(|a| *a != Action::OpenPalette)
            .position(|a| a == Action::ToggleAngle)
            .expect("angle action is in the catalog");
        assert_eq!(app.service().settings().angle_mode, AngleMode::Rad);
        let mut io = Headless::accepting().picking(index);
        app.dispatch(chord(KeyCode::Char('p'), KeyModifiers::CONTROL), &mut io)
            .expect("dispatch");
        assert_eq!(app.service().settings().angle_mode, AngleMode::Deg);
    }

    #[test]
    fn a_forced_quit_inside_the_palette_quits_the_app() {
        let mut app = test_app();
        let mut io = Headless::force_quitting();
        app.dispatch(chord(KeyCode::Char('p'), KeyModifiers::CONTROL), &mut io)
            .expect("dispatch");
        assert!(app.quit);
    }

    // --- History navigation and editing ---

    #[test]
    fn up_enters_history_and_an_edit_recomputes_the_chain() {
        let mut app = test_app();
        submit(&mut app, "10");
        submit(&mut app, "ans+5");
        render_to_string(&app, 80, 24);

        press(&mut app, key(KeyCode::Up));
        assert_eq!(app.mode, Mode::History);
        press(&mut app, key(KeyCode::Home));
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(app.mode, Mode::Edit(0));

        for _ in 0..2 {
            press(&mut app, key(KeyCode::Backspace));
        }
        for character in "20".chars() {
            press(&mut app, key(KeyCode::Char(character)));
        }
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(value_at(&app, 1), Some(25.0));
    }

    #[test]
    fn history_reorder_delete_and_clear_via_keys() {
        let mut app = test_app();
        submit(&mut app, "10");
        submit(&mut app, "ans+5");
        submit(&mut app, "ans*2");
        render_to_string(&app, 80, 24);

        press(&mut app, key(KeyCode::Up));
        assert_eq!(app.selected, Some(2));
        press(&mut app, chord(KeyCode::Up, KeyModifiers::ALT));
        assert_eq!(app.selected, Some(1));
        assert_eq!(value_at(&app, 1), Some(20.0));
        assert_eq!(value_at(&app, 2), Some(25.0));

        press(&mut app, key(KeyCode::Char('d')));
        assert_eq!(app.service().history().len(), 2);

        press(&mut app, key(KeyCode::Char('D')));
        assert_eq!(app.service().history().len(), 0);
    }

    #[test]
    fn a_declined_confirmation_keeps_the_entry() {
        let mut app = test_app();
        submit(&mut app, "10");
        render_to_string(&app, 80, 24);
        press(&mut app, key(KeyCode::Up));

        let mut declining = Headless::declining();
        app.dispatch(key(KeyCode::Char('d')), &mut declining)
            .unwrap();
        assert_eq!(declining.asked, 1);
        assert_eq!(app.service().history().len(), 1);
    }

    #[test]
    fn confirm_delete_off_deletes_without_asking() {
        let config = Config {
            confirm_delete: false,
            ..Config::default()
        };
        let service = CalcService::new(
            Box::new(MevalEvaluator::new()),
            config.format_settings(),
            History::new(100),
            VariableStore::new(),
        );
        let mut app = App::new(service, &config, &UiState::default());
        submit(&mut app, "10");
        render_to_string(&app, 80, 24);
        press(&mut app, key(KeyCode::Up));

        let mut declining = Headless::declining();
        app.dispatch(key(KeyCode::Char('d')), &mut declining)
            .unwrap();
        assert_eq!(declining.asked, 0, "no dialog when confirm_delete is off");
        assert_eq!(app.service().history().len(), 0);
    }

    #[test]
    fn inserting_a_line_enters_edit_and_recomputes() {
        let mut app = test_app();
        submit(&mut app, "10");
        submit(&mut app, "ans+5");
        render_to_string(&app, 80, 24);

        press(&mut app, key(KeyCode::Up));
        press(&mut app, key(KeyCode::Home));
        press(&mut app, key(KeyCode::Char('o')));
        assert_eq!(app.mode, Mode::Edit(1));
        for character in "ans*3".chars() {
            press(&mut app, key(KeyCode::Char(character)));
        }
        press(&mut app, key(KeyCode::Enter));

        // ["10", "ans*3", "ans+5"] -> 10, 30, 35.
        assert_eq!(value_at(&app, 1), Some(30.0));
        assert_eq!(value_at(&app, 2), Some(35.0));
    }

    #[test]
    fn cancelling_an_inserted_line_removes_it() {
        let mut app = test_app();
        submit(&mut app, "10");
        render_to_string(&app, 80, 24);
        press(&mut app, key(KeyCode::Up));
        press(&mut app, key(KeyCode::Char('o')));
        assert_eq!(app.service().history().len(), 2);
        press(&mut app, key(KeyCode::Esc));
        assert_eq!(app.service().history().len(), 1);
        assert_eq!(app.mode, Mode::History);
    }

    #[test]
    fn an_in_place_edit_locks_the_tab_bar() {
        let mut app = test_app();
        submit(&mut app, "10");
        render_to_string(&app, 80, 24);
        press(&mut app, key(KeyCode::Up));
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(app.mode, Mode::Edit(0));

        press(&mut app, chord(KeyCode::Char('2'), KeyModifiers::ALT));
        assert_eq!(app.active, ViewId::Calc, "the tab switch is locked");
        assert_eq!(app.status.as_deref(), Some("finish the edit first"));
    }

    // --- The variables view ---

    #[test]
    fn variables_view_lists_and_resets_after_confirmation() {
        let mut app = test_app();
        submit(&mut app, "7");
        submit(&mut app, "=x");
        assert_eq!(
            app.service()
                .variables()
                .get("x")
                .map(Quantity::display_value),
            Some(7.0),
        );

        press(&mut app, key(KeyCode::F(4)));
        assert_eq!(app.active, ViewId::Variables);
        assert!(render_to_string(&app, 80, 24).contains("x = 7"));

        press(&mut app, key(KeyCode::Char('R')));
        assert_eq!(app.service().variables().len(), 0);
    }

    #[test]
    fn inserting_a_variable_returns_to_the_calc_view() {
        let mut app = test_app();
        submit(&mut app, "7");
        submit(&mut app, "=x");
        press(&mut app, key(KeyCode::F(4)));
        press(&mut app, key(KeyCode::Enter));
        assert_eq!(app.active, ViewId::Calc);
        assert_eq!(app.mode, Mode::Input);
        assert_eq!(app.input, "x");
    }

    #[test]
    fn esc_leaves_a_list_view_for_the_calc_view() {
        let mut app = test_app();
        press(&mut app, key(KeyCode::F(4)));
        press(&mut app, key(KeyCode::Esc));
        assert_eq!(app.active, ViewId::Calc);
    }

    // --- The settings view ---

    #[test]
    fn the_settings_view_steps_a_value_live() {
        let mut app = test_app();
        press(&mut app, chord(KeyCode::Char('3'), KeyModifiers::ALT));
        assert_eq!(app.active, ViewId::Settings);
        assert_eq!(app.service().settings().notation, Notation::Decimal);

        // The first row is the notation.
        press(&mut app, key(KeyCode::Right));
        assert_eq!(app.service().settings().notation, Notation::Scientific);
        press(&mut app, key(KeyCode::Left));
        assert_eq!(app.service().settings().notation, Notation::Decimal);
    }

    #[test]
    fn the_settings_view_changes_the_focused_row() {
        let mut app = test_app();
        press(&mut app, chord(KeyCode::Char('3'), KeyModifiers::ALT));
        press(&mut app, key(KeyCode::Down));
        assert_eq!(app.setting_selected, 1);
        // The second row is the decimal count.
        press(&mut app, key(KeyCode::Right));
        assert_eq!(app.service().settings().decimals, 4);
    }

    // --- Quitting ---

    #[test]
    fn ctrl_q_inside_a_confirm_dialog_quits_and_abandons_the_action() {
        let mut app = test_app();
        submit(&mut app, "10");
        render_to_string(&app, 80, 24);
        press(&mut app, key(KeyCode::Up));

        let mut forced = Headless::force_quitting();
        let flow = app.dispatch(key(KeyCode::Char('d')), &mut forced).unwrap();
        assert!(matches!(flow, Flow::Quit));
        assert!(app.quit);
        assert_eq!(
            app.service().history().len(),
            1,
            "a forced quit is not a yes",
        );
    }

    #[test]
    fn ctrl_q_inside_the_help_overlay_quits() {
        let mut app = test_app();
        let mut forced = Headless::force_quitting();
        let flow = app.dispatch(key(KeyCode::F(12)), &mut forced).unwrap();
        assert!(matches!(flow, Flow::Quit));
        assert!(app.quit);
    }

    #[test]
    fn closing_the_help_overlay_normally_keeps_the_app_running() {
        let mut app = test_app();
        let mut declining = Headless::declining();
        let flow = app.dispatch(key(KeyCode::F(12)), &mut declining).unwrap();
        assert!(matches!(flow, Flow::Continue));
        assert!(!app.quit);
        assert_eq!(declining.asked, 1);
    }

    #[test]
    fn the_colon_q_command_quits() {
        let mut app = test_app();
        submit(&mut app, ":q");
        assert!(app.quit);
    }

    #[test]
    fn q_quits_from_a_list_view_but_not_from_the_input() {
        let mut app = test_app();
        press(&mut app, key(KeyCode::Char('q')));
        assert!(!app.quit, "q is a character in the input");

        press(&mut app, key(KeyCode::Esc));
        press(&mut app, key(KeyCode::F(4)));
        press(&mut app, key(KeyCode::Char('q')));
        assert!(app.quit);
    }

    // --- Rendering ---

    #[test]
    fn the_frame_shows_the_brand_the_tabs_and_the_status_band() {
        let app = test_app();
        let screen = render_to_string(&app, 80, 24);
        assert!(screen.contains("calcli"), "the brand");
        assert!(screen.contains("Calc"), "the tab bar");
        assert!(screen.contains("input"), "the input box");
        // The settings summary lives in the status band, dot-separated.
        assert!(screen.contains("RAD \u{b7} DEC \u{b7} 3 dp \u{b7} trim"));
    }

    #[test]
    fn the_footer_closes_with_the_global_group() {
        let app = test_app();
        let groups = app.hint_groups();
        let (label, hints) = groups.last().expect("a Global group");
        assert_eq!(label, "Global");
        let keys: Vec<&str> = hints.iter().map(|(k, _)| k.as_str()).collect();
        assert!(keys.contains(&"f12/?"), "help: {keys:?}");
        assert!(keys.contains(&"q"), "quit: {keys:?}");
        assert!(keys.iter().any(|k| k.contains("ctrl+q")), "{keys:?}");
        assert!(keys.iter().any(|k| k.contains("f1")), "{keys:?}");
    }

    #[test]
    fn the_help_overlay_ends_with_the_same_global_group_as_the_footer() {
        let app = test_app();
        let footer = app.hint_groups();
        let help = app.help_sections();
        assert_eq!(footer.last(), help.last(), "one source, two callers");
    }

    #[test]
    fn no_hint_anywhere_hardcodes_ctrl_q_outside_the_global_group() {
        let app = test_app();
        let sections = app.help_sections();
        let (_, global) = sections.last().expect("a Global group");
        for (label, hints) in &sections[..sections.len() - 1] {
            for (keys, _) in hints {
                assert!(
                    !keys.contains("ctrl+q"),
                    "ctrl+q hardcoded in {label:?}",
                );
            }
        }
        assert!(global.iter().any(|(keys, _)| keys.contains("ctrl+q")));
    }

    #[test]
    fn the_edit_mode_footer_offers_no_tab_switch() {
        let mut app = test_app();
        submit(&mut app, "10");
        render_to_string(&app, 80, 24);
        press(&mut app, key(KeyCode::Up));
        press(&mut app, key(KeyCode::Enter));

        let groups = app.hint_groups();
        let labels: Vec<&str> =
            groups.iter().map(|(label, _)| label.as_str()).collect();
        assert!(!labels.contains(&"Views"), "{labels:?}");
        assert!(labels.contains(&"Editing"), "{labels:?}");
    }

    #[test]
    fn live_feedback_previews_valid_and_warns_on_invalid() {
        let mut app = test_app();
        for character in "2+3".chars() {
            press(&mut app, key(KeyCode::Char(character)));
        }
        assert!(render_to_string(&app, 80, 24).contains("= 5"));

        press(&mut app, key(KeyCode::Char(')')));
        let screen = render_to_string(&app, 80, 24);
        assert!(screen.contains('\u{26a0}'));
        assert!(!screen.contains("= 5"));
    }

    #[test]
    fn live_feedback_stays_silent_while_typing() {
        let mut app = test_app();
        for character in "2+".chars() {
            press(&mut app, key(KeyCode::Char(character)));
        }
        let screen = render_to_string(&app, 80, 24);
        assert!(!screen.contains('\u{26a0}'));
        assert!(!screen.contains('='));
    }

    #[test]
    fn a_highlighted_input_keeps_every_typed_character() {
        let mut app = test_app();
        for character in "sin(pi)+x".chars() {
            press(&mut app, key(KeyCode::Char(character)));
        }
        assert!(render_to_string(&app, 80, 24).contains("sin(pi)+x"));
    }

    #[test]
    fn a_long_history_entry_wraps_instead_of_truncating() {
        let mut app = test_app();
        submit(&mut app, "111111111111111111+7");
        press(&mut app, key(KeyCode::Esc));

        // Narrow enough that the entry must wrap, tall enough that the grouped
        // hint band still leaves the history a viewport.
        let screen = render_to_string(&app, 24, 40);
        assert!(!screen.contains('\u{2026}'), "no ellipsis");
        assert!(screen.contains("+7"), "the tail wrapped");
    }

    #[test]
    fn a_short_terminal_drops_the_hints_rather_than_the_input_box() {
        let app = test_app();
        let screen = render_to_string(&app, 40, 12);
        assert!(screen.contains("input"), "the input box survives");
        assert!(!screen.contains("f12/?"), "the hint band gives way");
    }

    #[test]
    fn restoring_a_persisted_theme_keeps_the_configured_colour_overrides() {
        // `restore` runs `set_theme` for the saved theme name, so a real
        // restart went through the theme path. Resolving without the overrides
        // there silently undid calcli's own defaults: the red block cursor
        // turned accent-green and the input field turned bright.
        let config = Config::default();
        let expected = config.palette();

        let service = CalcService::new(
            Box::new(MevalEvaluator::new()),
            config.format_settings(),
            History::new(100),
            VariableStore::new(),
        );
        let restored = UiState {
            theme: Some(CALCLI_THEME.to_string()),
            ..UiState::default()
        };
        let app = App::new(service, &config, &restored);

        let palette = app.skin().palette;
        assert_eq!(palette.cursor, expected.cursor, "the red block cursor");
        assert_eq!(palette.input_bg, expected.input_bg);
        assert_eq!(palette.input_bg_active, expected.input_bg_active);
        assert_ne!(palette.cursor, palette.accent);
    }

    #[test]
    fn cycling_the_theme_at_runtime_keeps_the_colour_overrides() {
        let mut app = test_app();
        let cursor = app.skin().palette.cursor;
        app.set_theme("monochrome");
        assert_eq!(app.skin().palette.cursor, cursor, "the override survives");
        // The theme's own colours did change.
        assert_ne!(
            app.skin().palette.accent,
            Config::default().palette().accent
        );
    }

    #[test]
    fn the_ui_state_round_trips_through_persistence() {
        let mut app = test_app();
        press(&mut app, chord(KeyCode::Char('3'), KeyModifiers::ALT));
        let state = app.persisted_state();
        assert_eq!(state.ui.active_view, ViewId::Settings.index());
        assert_eq!(state.ui.theme.as_deref(), Some("calcli"));
        assert_eq!(state.ui.hints_visible, Some(shortcut_hints::visible()));
    }

    #[test]
    fn every_view_renders_at_a_tiny_size_without_panicking() {
        let mut app = test_app();
        for view in ViewId::all() {
            app.active = view;
            render_to_string(&app, 12, 5);
        }
    }
}