calcli 0.2.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
//! The Ratatui front-end: the [`App`] state, the event loop and rendering.
//!
//! Layout, top to bottom: a header, the scrollable history (input left, result
//! right), the fixed input field, a settings bar showing every active setting,
//! a transient status line and a footer of shortcut hints. Overlays (variables,
//! help, a confirm modal) draw on top. The calculator core lives in
//! [`crate::service`]; this module only translates keys into service calls and
//! renders the result.

pub mod colors;
pub mod help;
pub mod history_view;
pub mod terminal;
pub mod text_edit;
pub mod variables_view;
pub mod widgets;

use std::cell::Cell;
use std::io;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Paragraph};

use crate::config::{Config, GlyphSet};
use crate::domain::format::{AngleMode, Notation};
use crate::domain::highlight;
use crate::domain::quantity::Quantity;
use crate::service::{CalcService, Preview};
use crate::storage::{
    PersistedEntry, PersistedSettings, PersistedState, PersistedValue,
};
use crate::tui::colors::{Highlight, parse_color};
use crate::tui::terminal::{Tui, is_global_quit};
use crate::tui::text_edit::TextCursor;
use crate::tui::widgets::{ConfirmModal, ConfirmResult, hint_lines};
use crate::util::clipboard;

/// Where keyboard focus sits in the main view.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Typing a new expression in the input field.
    Input,
    /// Browsing the history with a row selected.
    History,
    /// Editing the input of the history row at this index, in place.
    Edit(usize),
}

/// A pending destructive action awaiting confirmation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConfirmAction {
    /// Remove every variable.
    ResetVariables,
    /// Delete the history entry at this index.
    DeleteEntry(usize),
    /// Clear the entire history.
    ClearHistory,
}

/// The overlay drawn on top of the main view, if any.
enum Overlay {
    /// No overlay.
    None,
    /// The variables list.
    Variables,
    /// The help screen.
    Help,
    /// A yes/no confirmation for `action`.
    Confirm(ConfirmModal, ConfirmAction),
}

/// The whole TUI state: the calculator service plus view-only fields.
pub struct App {
    service: CalcService,
    accent: Color,
    highlight: Highlight,
    settings_bar_bg: Color,
    history_alt_bg: Color,
    history_zebra: bool,
    history_spacing: usize,
    history_separator: Option<Color>,
    input_max_lines: usize,
    glyphs: GlyphSet,
    live_feedback: bool,
    input: String,
    cursor: TextCursor,
    mode: Mode,
    selected: Option<usize>,
    overlay: Overlay,
    var_selected: usize,
    help_scroll: usize,
    status: Option<String>,
    quit: bool,
    editing_inserted: bool,
    view_height: Cell<usize>,
    var_offset: Cell<usize>,
    input_width: Cell<usize>,
    history_width: Cell<usize>,
}

impl App {
    /// Builds the app from a configured service and the loaded config.
    pub fn new(service: CalcService, config: &Config) -> Self {
        App {
            service,
            accent: parse_color(&config.theme.accent_color),
            highlight: Highlight::from_theme(&config.theme),
            settings_bar_bg: parse_color(&config.theme.settings_bar_bg),
            history_alt_bg: parse_color(&config.theme.history_alt_bg),
            history_zebra: config.history_zebra,
            history_spacing: config.history_spacing,
            history_separator: config
                .history_separator
                .then(|| parse_color(&config.theme.history_separator_color)),
            input_max_lines: config.input_max_lines,
            glyphs: config.glyphs,
            live_feedback: config.live_feedback,
            input: String::new(),
            cursor: TextCursor::at(0),
            mode: Mode::Input,
            selected: None,
            overlay: Overlay::None,
            var_selected: 0,
            help_scroll: 0,
            status: None,
            quit: false,
            editing_inserted: false,
            view_height: Cell::new(1),
            var_offset: Cell::new(0),
            input_width: Cell::new(1),
            history_width: Cell::new(1),
        }
    }

    /// Snapshots the session for persistence: settings, variables and 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(|q| q.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,
            }),
            variables,
            history,
        }
    }

    // --- Accessors used by the render submodules ---

    /// The resolved accent colour.
    pub fn accent(&self) -> Color {
        self.accent
    }

    /// The resolved syntax-highlight styles.
    pub fn highlight(&self) -> &Highlight {
        &self.highlight
    }

    /// The zebra-striping background for alternating history entries, or `None`
    /// when zebra striping is disabled.
    pub fn history_alt_bg(&self) -> Option<Color> {
        self.history_zebra.then_some(self.history_alt_bg)
    }

    /// Blank lines inserted after each history entry's result.
    pub fn history_spacing(&self) -> usize {
        self.history_spacing
    }

    /// The colour of the separator line between entries, or `None` when off.
    pub fn history_separator(&self) -> Option<Color> {
        self.history_separator
    }

    /// The calculator service.
    pub fn service(&self) -> &CalcService {
        &self.service
    }

    /// The current focus mode.
    pub fn mode(&self) -> Mode {
        self.mode
    }

    /// The selected history index, if any.
    pub fn selected(&self) -> Option<usize> {
        self.selected
    }

    /// The current input buffer.
    pub fn input(&self) -> &str {
        &self.input
    }

    /// The input caret.
    pub fn cursor(&self) -> TextCursor {
        self.cursor
    }

    /// The selected variable index in the overlay.
    pub fn var_selected(&self) -> usize {
        self.var_selected
    }

    /// The help overlay scroll position.
    pub fn help_scroll(&self) -> usize {
        self.help_scroll
    }

    /// Records the history viewport height (for paging).
    pub fn set_view_height(&self, height: usize) {
        self.view_height.set(height);
    }

    /// Records the history content width (for wrapping in-place edits).
    pub fn set_history_width(&self, width: usize) {
        self.history_width.set(width);
    }

    /// The stored variables scroll offset.
    pub fn var_offset(&self) -> usize {
        self.var_offset.get()
    }

    /// Records the variables scroll offset chosen while rendering.
    pub fn set_var_offset(&self, offset: usize) {
        self.var_offset.set(offset);
    }

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

/// Runs the event loop until the user quits, leaving the app holding the final
/// state for the caller to persist.
///
/// # Errors
/// Returns an I/O error if drawing or reading from the terminal fails.
pub fn run(app: &mut App, tui: &mut Tui) -> io::Result<()> {
    loop {
        tui.terminal.draw(|frame| render(app, frame))?;
        let key = tui.read_key()?;
        if is_global_quit(key) {
            return Ok(());
        }
        app.handle_key(key);
        if app.quit {
            return Ok(());
        }
    }
}

impl App {
    /// Dispatches a key to the right handler for the current overlay and mode.
    fn handle_key(&mut self, key: KeyEvent) {
        self.status = None;
        if let Overlay::Confirm(..) = self.overlay {
            self.handle_confirm_key(key);
            return;
        }
        if self.handle_global_key(key) {
            return;
        }
        match self.overlay {
            Overlay::Variables => self.handle_variables_key(key),
            Overlay::Help => self.handle_help_key(key),
            Overlay::None | Overlay::Confirm(..) => match self.mode {
                Mode::Input => self.handle_input_key(key),
                Mode::History => self.handle_history_key(key),
                Mode::Edit(index) => self.handle_edit_key(key, index),
            },
        }
    }

    /// Handles the global function-key shortcuts; returns whether it consumed
    /// the key.
    fn handle_global_key(&mut self, key: KeyEvent) -> bool {
        match key.code {
            KeyCode::F(1) => self.toggle_help(),
            KeyCode::F(2) => {
                self.service.cycle_notation();
                self.status = Some(format!(
                    "notation: {}",
                    self.service.settings().notation.label()
                ));
            }
            KeyCode::F(3) => {
                self.service.toggle_angle_mode();
                self.status = Some(format!(
                    "angle: {}",
                    self.service.settings().angle_mode.label()
                ));
            }
            KeyCode::F(4) => self.toggle_variables(),
            KeyCode::F(5) => {
                self.service.toggle_decimal_separator();
                self.status = Some(format!(
                    "decimal separator: {}",
                    self.service.settings().decimal_separator
                ));
            }
            KeyCode::F(6) => {
                self.service.toggle_trim_trailing_zeros();
                let state = if self.service.settings().trim_trailing_zeros {
                    "trimmed"
                } else {
                    "fixed"
                };
                self.status = Some(format!("trailing zeros: {state}"));
            }
            _ => return false,
        }
        true
    }

    /// Toggles the help overlay.
    fn toggle_help(&mut self) {
        self.overlay = match self.overlay {
            Overlay::Help => Overlay::None,
            _ => {
                self.help_scroll = 0;
                Overlay::Help
            }
        };
    }

    /// Toggles the variables overlay.
    fn toggle_variables(&mut self) {
        self.overlay = match self.overlay {
            Overlay::Variables => Overlay::None,
            _ => {
                self.var_selected = 0;
                self.var_offset.set(0);
                Overlay::Variables
            }
        };
    }

    /// Handles keys while typing a new expression. The input soft-wraps and
    /// grows, so `Up`/`Down` move the caret across wrapped lines; `Up` on the
    /// first line (and `PageUp`) enter the history.
    fn handle_input_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Enter => self.submit_input(),
            KeyCode::PageUp => self.enter_history(),
            KeyCode::Up => {
                let (line, _) = self.cursor_display();
                if line == 0 {
                    self.enter_history();
                } else {
                    self.apply_input_key(key);
                }
            }
            KeyCode::Down => {
                let (line, count) = self.cursor_display();
                if line + 1 < count {
                    self.apply_input_key(key);
                }
            }
            KeyCode::Char('y') if ctrl => {
                match self.service.history().last_value() {
                    Some(value) => self.copy_plain(&value),
                    None => self.status = Some("no result yet".to_string()),
                }
            }
            KeyCode::Esc => {
                self.input.clear();
                self.cursor = TextCursor::at(0);
            }
            _ => self.apply_input_key(key),
        }
    }

    /// Applies a clipboard chord or an edit key to the soft-wrapped input.
    fn apply_input_key(&mut self, key: KeyEvent) {
        if text_edit::handle_clipboard(&mut self.input, &mut self.cursor, key) {
            return;
        }
        let width = self.input_width.get().max(1);
        text_edit::apply_edit_key(
            &mut self.input,
            &mut self.cursor,
            key,
            text_edit::EditMode::Multiline { width },
        );
    }

    /// The caret's `(display line, total lines)` for the current input width.
    fn cursor_display(&self) -> (usize, usize) {
        let width = self.input_width.get().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, offsets.len())
    }

    /// Evaluates the input buffer (or runs a `:` command) and clears it.
    fn submit_input(&mut self) {
        let text = self.input.trim().to_string();
        if text.is_empty() {
            return;
        }
        // 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 message = self.run_command(command);
            self.status = Some(message);
        } else {
            let outcome = self.service.submit(&text);
            self.status = Some(self.outcome_status(&outcome));
            self.selected = None;
        }
        self.input.clear();
        self.cursor = TextCursor::at(0);
    }

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

    /// 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);
    }

    /// Handles keys while browsing the history.
    fn handle_history_key(&mut self, key: KeyEvent) {
        let Some(index) = self.selected else {
            self.mode = Mode::Input;
            return;
        };
        let total = self.service.history().len();
        let last = total.saturating_sub(1);
        let page = self.view_height.get().max(1);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        match key.code {
            KeyCode::Up if alt => self.move_selected(index, -1),
            KeyCode::Down if alt => self.move_selected(index, 1),
            KeyCode::Up => self.selected = Some(index.saturating_sub(1)),
            KeyCode::Down => {
                if index < last {
                    self.selected = Some(index + 1);
                } else {
                    self.leave_history();
                }
            }
            KeyCode::Home => self.selected = Some(0),
            KeyCode::End => self.selected = Some(last),
            KeyCode::PageUp => self.selected = Some(index.saturating_sub(page)),
            KeyCode::PageDown => self.selected = Some((index + page).min(last)),
            KeyCode::Char('y') => self.copy_selected(index, false),
            KeyCode::Char('Y') => self.copy_selected(index, true),
            KeyCode::Char('e') | KeyCode::Enter => self.start_edit(index),
            KeyCode::Char('o') => self.insert_line(index + 1),
            KeyCode::Char('O') => self.insert_line(index),
            KeyCode::Char('d') | KeyCode::Delete => self.confirm_delete(index),
            KeyCode::Char('D') => self.confirm_clear_history(),
            KeyCode::Esc => self.leave_history(),
            _ => {}
        }
    }

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

    /// 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;
    }

    /// Opens the confirmation modal for deleting the selected entry.
    fn confirm_delete(&mut self, index: usize) {
        self.overlay = Overlay::Confirm(
            ConfirmModal::new("Delete this line?"),
            ConfirmAction::DeleteEntry(index),
        );
    }

    /// Opens the confirmation modal for clearing the whole history.
    fn confirm_clear_history(&mut self) {
        if self.service.history().is_empty() {
            return;
        }
        self.overlay = Overlay::Confirm(
            ConfirmModal::new("Clear the entire history?"),
            ConfirmAction::ClearHistory,
        );
    }

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

    /// 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(|e| e.value.clone());
        match value {
            Some(value) if as_displayed => self.copy_display(&value),
            Some(value) => self.copy_plain(&value),
            None => self.status = Some("no value to copy".to_string()),
        }
    }

    /// 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;
    }

    /// Deletes history entry `index` and keeps a valid selection.
    fn delete_selected(&mut self, index: usize) {
        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.status = Some("line deleted".to_string());
    }

    /// Handles keys while editing a history line in place.
    fn handle_edit_key(&mut self, key: KeyEvent, index: usize) {
        match key.code {
            KeyCode::Enter => {
                let text = self.input.clone();
                self.service.edit_entry(index, &text);
                self.editing_inserted = false;
                self.finish_edit(index);
                self.status = Some("line updated".to_string());
            }
            KeyCode::Esc => {
                if self.editing_inserted {
                    self.cancel_insert(index);
                } else {
                    self.finish_edit(index);
                }
            }
            _ => {
                if text_edit::handle_clipboard(
                    &mut self.input,
                    &mut self.cursor,
                    key,
                ) {
                    return;
                }
                // In-place editing soft-wraps at the history width, like the
                // entry is displayed.
                let width = self.history_width.get().max(1);
                text_edit::apply_edit_key(
                    &mut self.input,
                    &mut self.cursor,
                    key,
                    text_edit::EditMode::Multiline { width },
                );
            }
        }
    }

    /// 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));
        }
    }

    /// Handles keys in the variables overlay.
    fn handle_variables_key(&mut self, key: KeyEvent) {
        let total = self.service.variables().len();
        match key.code {
            KeyCode::Esc => self.overlay = Overlay::None,
            KeyCode::Up => {
                self.var_selected = cycle(self.var_selected, -1, total)
            }
            KeyCode::Down => {
                self.var_selected = cycle(self.var_selected, 1, total)
            }
            KeyCode::Enter => self.insert_variable(),
            KeyCode::Char('y') => self.copy_variable(false),
            KeyCode::Char('Y') => self.copy_variable(true),
            KeyCode::Char('d') | KeyCode::Delete => self.delete_variable(),
            KeyCode::Char('r') | KeyCode::Char('R') => {
                if total > 0 {
                    self.overlay = Overlay::Confirm(
                        ConfirmModal::new("Reset all variables?"),
                        ConfirmAction::ResetVariables,
                    );
                }
            }
            _ => {}
        }
    }

    /// 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 closes the
    /// overlay.
    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.overlay = Overlay::None;
        self.mode = Mode::Input;
        self.status = Some(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.status = Some(format!("removed {name}"));
    }

    /// Handles keys for the confirm modal.
    fn handle_confirm_key(&mut self, key: KeyEvent) {
        let (result, action) = match &self.overlay {
            Overlay::Confirm(modal, action) => (modal.handle_key(key), *action),
            _ => return,
        };
        match result {
            ConfirmResult::Yes => self.apply_confirmed(action),
            ConfirmResult::No => self.overlay = return_overlay(action),
            ConfirmResult::Pending => {}
        }
    }

    /// Performs a confirmed destructive action and restores the right view.
    fn apply_confirmed(&mut self, action: ConfirmAction) {
        match action {
            ConfirmAction::ResetVariables => {
                self.service.reset_variables();
                self.var_selected = 0;
                self.status = Some("variables reset".to_string());
            }
            ConfirmAction::DeleteEntry(index) => self.delete_selected(index),
            ConfirmAction::ClearHistory => {
                self.service.clear_history();
                self.leave_history();
                self.status = Some("history cleared".to_string());
            }
        }
        self.overlay = return_overlay(action);
    }

    /// Handles keys in the help overlay.
    fn handle_help_key(&mut self, key: KeyEvent) {
        let max_scroll = help::line_count();
        match key.code {
            KeyCode::Esc | KeyCode::F(1) | KeyCode::Char('?') => {
                self.overlay = Overlay::None;
            }
            KeyCode::Up => {
                self.help_scroll = self.help_scroll.saturating_sub(1)
            }
            KeyCode::Down => {
                self.help_scroll = (self.help_scroll + 1).min(max_scroll);
            }
            KeyCode::PageUp => {
                self.help_scroll = self.help_scroll.saturating_sub(10)
            }
            KeyCode::PageDown => {
                self.help_scroll = (self.help_scroll + 10).min(max_scroll);
            }
            _ => {}
        }
    }

    /// Runs a `:` command (without the leading colon) and returns a status line.
    fn run_command(&mut self, command: &str) -> String {
        match command.trim() {
            "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" => {
                if self.service.history().is_empty() {
                    return "history is already empty".to_string();
                }
                self.overlay = Overlay::Confirm(
                    ConfirmModal::new("Clear the entire history?"),
                    ConfirmAction::ClearHistory,
                );
                String::new()
            }
            other => self.run_notation_command(other),
        }
    }

    /// 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}'"),
        }
    }

    /// 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.status = Some(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.status = Some(copy_status(&text));
    }
}

/// The overlay to restore after a confirmation: back to the variables list for
/// a variables action, otherwise the main view.
fn return_overlay(action: ConfirmAction) -> Overlay {
    match action {
        ConfirmAction::ResetVariables => Overlay::Variables,
        ConfirmAction::DeleteEntry(_) | ConfirmAction::ClearHistory => {
            Overlay::None
        }
    }
}

/// Cyclically moves an index by `delta` within `len` items (empty stays 0).
fn cycle(index: usize, delta: isize, len: usize) -> usize {
    if len == 0 {
        return 0;
    }
    let next = index as isize + delta;
    next.rem_euclid(len as isize) as usize
}

/// 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()
    }
}

/// Draws the whole UI for one frame.
fn render(app: &App, frame: &mut Frame) {
    let area = frame.area();
    let input_height = input_box_height(app, area.width);
    let footer_height = footer_height(app, area.width).max(1);
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),             // header
            Constraint::Min(1),                // history
            Constraint::Length(input_height),  // input (grows with wrapping)
            Constraint::Length(1),             // settings bar
            Constraint::Length(1),             // status line
            Constraint::Length(footer_height), // footer hints (wraps)
        ])
        .split(area);

    render_header(frame, chunks[0], app);
    history_view::render(frame, chunks[1], app);
    render_input(frame, chunks[2], app);
    render_settings_bar(frame, chunks[3], app);
    render_status(frame, chunks[4], app);
    render_footer(frame, chunks[5], app);

    match &app.overlay {
        Overlay::Variables => variables_view::render(frame, area, app),
        Overlay::Help => help::render(frame, area, app),
        Overlay::Confirm(modal, _) => modal.render(frame, area, app.accent),
        Overlay::None => {}
    }
}

/// Renders the title header.
fn render_header(frame: &mut Frame, area: Rect, app: &App) {
    let line = Line::from(vec![
        Span::styled(
            "calcli",
            Style::default().fg(app.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" v{}", crate::util::app_info::APP_VERSION),
            colors::dim(),
        ),
    ]);
    frame.render_widget(Paragraph::new(line), area);
}

/// Renders the fixed input field, adapting to the focus mode.
fn render_input(frame: &mut Frame, area: Rect, app: &App) {
    let mut block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(app.accent))
        .title(" input ");
    if let Some(feedback) = live_feedback_line(app) {
        block = block.title_bottom(feedback.right_aligned());
    }
    let inner = area.inner(ratatui::layout::Margin::new(1, 1));
    frame.render_widget(block, area);

    let lines = match app.mode {
        Mode::Input => input_editor_lines(app, inner),
        Mode::History => vec![Line::from(Span::styled(
            "browsing history \u{2014} \u{2191}\u{2193} select, Enter edit, Esc back",
            colors::dim(),
        ))],
        Mode::Edit(_) => vec![Line::from(Span::styled(
            "editing line \u{2014} Enter apply, Esc cancel",
            colors::dim(),
        ))],
    };
    frame.render_widget(Paragraph::new(lines), inner);
}

/// Columns available for wrapping the input text (inside borders and prompt).
fn input_wrap_width(total_width: u16) -> usize {
    (total_width as usize).saturating_sub(4).max(1)
}

/// The input box height (including borders): grows with the wrapped line count
/// in Input mode, clamped to `input_max_lines`; one content line otherwise.
fn input_box_height(app: &App, total_width: u16) -> u16 {
    let content = if matches!(app.mode, Mode::Input) {
        text_edit::wrap_offsets(&app.input, input_wrap_width(total_width)).len()
    } else {
        1
    };
    content.clamp(1, app.input_max_lines) as u16 + 2
}

/// Builds the soft-wrapped, syntax-highlighted editor lines for the input field,
/// each prefixed with the prompt (`> `) or a continuation indent.
fn input_editor_lines(app: &App, inner: Rect) -> Vec<Line<'static>> {
    let width = inner.width.saturating_sub(2) as usize;
    app.input_width.set(width);

    let kinds = highlight::classify(&app.input, app.service.variables());
    let styles = colors::styles_for(&kinds, &app.highlight);
    let display = text_edit::multiline_spans_styled(
        &app.input, app.cursor, width, &styles,
    );

    let height = (inner.height as usize).max(1);
    let total = app.input.chars().count();
    let offsets = text_edit::wrap_offsets(&app.input, width);
    let (cursor_line, _) =
        text_edit::cursor_to_display(&offsets, total, app.cursor.pos);
    let start = window_start(display.len(), height, cursor_line);

    let prompt_style =
        Style::default().fg(app.accent).add_modifier(Modifier::BOLD);
    display
        .into_iter()
        .enumerate()
        .skip(start)
        .take(height)
        .map(|(index, line)| {
            let prefix = if index == 0 {
                Span::styled("> ", prompt_style)
            } else {
                Span::raw("  ")
            };
            let mut spans = line.spans;
            spans.insert(0, prefix);
            Line::from(spans)
        })
        .collect()
}

/// The first visible display line so the cursor line stays within `height`.
fn window_start(total: usize, height: usize, cursor_line: usize) -> usize {
    if total <= height {
        return 0;
    }
    if cursor_line < height {
        0
    } else {
        (cursor_line + 1 - height).min(total - height)
    }
}

/// 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(app: &App) -> Option<Line<'static>> {
    if !app.live_feedback || app.mode != Mode::Input || app.input.is_empty() {
        return None;
    }
    match app.service.preview(&app.input) {
        Preview::Value(value) => {
            let text = format!(" = {} ", app.service.format_display(&value));
            let style =
                Style::default().fg(app.accent).add_modifier(Modifier::DIM);
            Some(Line::from(Span::styled(text, style)))
        }
        Preview::Invalid => {
            let text = format!(" {} ", app.warn());
            let style = Style::default()
                .fg(colors::ERROR)
                .add_modifier(Modifier::DIM);
            Some(Line::from(Span::styled(text, style)))
        }
        Preview::Empty | Preview::Incomplete => None,
    }
}

/// Renders the settings bar showing every active setting.
fn render_settings_bar(frame: &mut Frame, area: Rect, app: &App) {
    let settings = app.service.settings();
    let grouping = match settings.thousands_separator.as_str() {
        " " => "space".to_string(),
        "" => "none".to_string(),
        other => other.to_string(),
    };
    let glyphs = match app.glyphs {
        GlyphSet::Unicode => "unicode",
        GlyphSet::Ascii => "ascii",
    };
    let trim = if settings.trim_trailing_zeros {
        "trim"
    } else {
        "fixed"
    };
    let values = [
        settings.angle_mode.label().to_string(),
        settings.notation.label().to_string(),
        format!("{} dp", settings.decimals),
        trim.to_string(),
        settings.decimal_separator.to_string(),
        grouping,
        glyphs.to_string(),
    ];

    let bg = app.settings_bar_bg;
    let value_style = Style::default().fg(app.accent).bg(bg);
    let separator_style = Style::default().add_modifier(Modifier::DIM).bg(bg);
    let mut spans: Vec<Span> = vec![Span::styled(" ", Style::default().bg(bg))];
    for (index, value) in values.iter().enumerate() {
        if index != 0 {
            spans.push(Span::styled(" | ", separator_style));
        }
        spans.push(Span::styled(value.clone(), value_style));
    }
    let bar = Paragraph::new(Line::from(spans)).style(Style::default().bg(bg));
    frame.render_widget(bar, area);
}

/// Renders the transient status line.
fn render_status(frame: &mut Frame, area: Rect, app: &App) {
    let Some(status) = &app.status else {
        return;
    };
    let line = Line::from(Span::styled(
        widgets::truncate(status, area.width as usize),
        Style::default().fg(app.accent),
    ));
    frame.render_widget(Paragraph::new(line), area);
}

/// The footer shortcut hints for the current overlay and focus mode.
fn footer_hints(app: &App) -> &'static [(&'static str, &'static str)] {
    match (&app.overlay, app.mode) {
        (Overlay::Help, _) => &[("F1/Esc", "close help")],
        (Overlay::Variables, _) => &[
            ("\u{2191}\u{2193}", "select"),
            ("Enter", "insert"),
            ("y/Y", "copy"),
            ("d", "delete"),
            ("R", "reset"),
            ("Esc", "close"),
        ],
        (_, Mode::Edit(_)) => &[("Enter", "apply"), ("Esc", "cancel")],
        (_, Mode::History) => &[
            ("\u{2191}\u{2193}", "select"),
            ("Alt+\u{2191}\u{2193}", "move"),
            ("o/O", "insert"),
            ("Enter", "edit"),
            ("d", "delete"),
            ("D", "clear"),
            ("y/Y", "copy"),
            ("Esc", "back"),
        ],
        (_, Mode::Input) => &[
            ("F1", "help"),
            ("F2", "notation"),
            ("F3", "deg/rad"),
            ("F4", "vars"),
            ("F5", ". ,"),
            ("F6", "trim"),
            ("Enter", "calc"),
            ("\u{2191}", "history"),
            ("^Q", "quit"),
        ],
    }
}

/// The number of footer lines the hints wrap into at `width`.
fn footer_height(app: &App, width: u16) -> u16 {
    hint_lines(footer_hints(app), app.accent, width as usize).len() as u16
}

/// Renders the footer shortcut hints, wrapping across the lines `area` allows.
fn render_footer(frame: &mut Frame, area: Rect, app: &App) {
    let lines = hint_lines(footer_hints(app), app.accent, area.width as usize);
    frame.render_widget(Paragraph::new(lines), area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::domain::evaluator::MevalEvaluator;
    use crate::domain::history::History;
    use crate::domain::variables::VariableStore;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

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

    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)
    }

    /// Types `text` then submits it (Enter).
    fn submit(app: &mut App, text: &str) {
        for c in text.chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(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)
    }

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

        app.handle_key(key(KeyCode::Up)); // enter history, select last (2)
        assert_eq!(app.selected(), Some(2));
        // Alt+Up moves it to index 1 and recomputes.
        app.handle_key(KeyEvent::new(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));

        // Delete asks first, then removes.
        app.handle_key(key(KeyCode::Char('d')));
        assert!(matches!(app.overlay, Overlay::Confirm(..)));
        app.handle_key(key(KeyCode::Char('y')));
        assert_eq!(app.service().history().len(), 2);

        // Shift+D clears everything after confirming.
        app.handle_key(key(KeyCode::Char('D')));
        assert!(matches!(app.overlay, Overlay::Confirm(..)));
        app.handle_key(key(KeyCode::Char('y')));
        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"); // 15

        app.handle_key(key(KeyCode::Up)); // select last (1)
        app.handle_key(key(KeyCode::Home)); // select 0
        app.handle_key(key(KeyCode::Char('o'))); // insert below -> edit index 1
        assert!(matches!(app.mode(), Mode::Edit(1)));
        for c in "ans*3".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(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");
        app.handle_key(key(KeyCode::Up)); // select 0
        app.handle_key(key(KeyCode::Char('o'))); // insert -> edit index 1
        assert_eq!(app.service().history().len(), 2);
        app.handle_key(key(KeyCode::Esc)); // cancel
        assert_eq!(app.service().history().len(), 1);
        assert!(matches!(app.mode(), Mode::History));
    }

    /// Renders `app` into an 80x24 test terminal and returns the screen text.
    fn render_to_string(app: &App) -> String {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|frame| render(app, frame)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        buffer.content().iter().map(|cell| cell.symbol()).collect()
    }

    #[test]
    fn renders_the_main_chrome_without_panicking() {
        let app = test_app();
        let screen = render_to_string(&app);
        assert!(screen.contains("calcli"));
        assert!(screen.contains("input"));
        assert!(screen.contains("history"));
    }

    #[test]
    fn settings_bar_shows_values_separated_by_pipes() {
        let app = test_app();
        let screen = render_to_string(&app);
        assert!(
            screen.contains("RAD | DEC | 3 dp | trim | . | space | unicode")
        );
    }

    #[test]
    fn typing_and_enter_records_a_result() {
        let mut app = test_app();
        for c in "2+3".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(key(KeyCode::Enter));
        assert_eq!(
            app.service()
                .history()
                .last_value()
                .map(|q| q.display_value()),
            Some(5.0)
        );
        let screen = render_to_string(&app);
        assert!(screen.contains("= 5"));
    }

    #[test]
    fn up_enters_history_and_edit_recomputes() {
        let mut app = test_app();
        for c in "10".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(key(KeyCode::Enter));
        for c in "ans+5".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(key(KeyCode::Enter));

        // Enter history, select the first line, edit it.
        app.handle_key(key(KeyCode::Up));
        app.handle_key(key(KeyCode::Home));
        app.handle_key(key(KeyCode::Enter)); // start editing line 0
        assert!(matches!(app.mode(), Mode::Edit(0)));
        for _ in 0..2 {
            app.handle_key(key(KeyCode::Backspace));
        }
        for c in "20".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(key(KeyCode::Enter)); // apply
        assert_eq!(value_at(&app, 1), Some(25.0));
    }

    #[test]
    fn function_keys_toggle_settings() {
        let mut app = test_app();
        assert_eq!(app.service().settings().angle_mode, AngleMode::Rad);
        app.handle_key(key(KeyCode::F(3)));
        assert_eq!(app.service().settings().angle_mode, AngleMode::Deg);
        assert_eq!(app.service().settings().decimal_separator, '.');
        app.handle_key(key(KeyCode::F(5)));
        assert_eq!(app.service().settings().decimal_separator, ',');
        // F6 flips trailing-zero trimming and reports it on the status line.
        assert!(app.service().settings().trim_trailing_zeros);
        app.handle_key(key(KeyCode::F(6)));
        assert!(!app.service().settings().trim_trailing_zeros);
        assert_eq!(app.status.as_deref(), Some("trailing zeros: fixed"));
    }

    #[test]
    fn variables_overlay_opens_and_resets() {
        let mut app = test_app();
        for c in "7".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(key(KeyCode::Enter));
        for c in "=x".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(key(KeyCode::Enter));
        assert_eq!(
            app.service()
                .variables()
                .get("x")
                .map(Quantity::display_value),
            Some(7.0)
        );

        app.handle_key(key(KeyCode::F(4))); // open variables
        assert!(matches!(app.overlay, Overlay::Variables));
        app.handle_key(key(KeyCode::Char('R'))); // ask to reset
        assert!(matches!(app.overlay, Overlay::Confirm(..)));
        app.handle_key(key(KeyCode::Char('y'))); // confirm
        assert_eq!(app.service().variables().len(), 0);
    }

    #[test]
    fn live_feedback_previews_valid_and_warns_on_invalid() {
        let mut app = test_app();
        for c in "2+3".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        // Valid: a dim result preview on the input border.
        assert!(render_to_string(&app).contains("= 5"));

        // Complete but invalid: a warning marker, no preview.
        app.handle_key(key(KeyCode::Char(')')));
        let screen = render_to_string(&app);
        assert!(screen.contains('\u{26a0}'));
        assert!(!screen.contains("= 5"));
    }

    #[test]
    fn long_input_grows_the_box_and_up_navigates_wrapped_lines() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut app = test_app();
        // A history entry so entering the history from the input is observable.
        app.handle_key(key(KeyCode::Char('1')));
        app.handle_key(key(KeyCode::Enter));
        // A long expression that must wrap in a narrow terminal.
        for _ in 0..18 {
            app.handle_key(key(KeyCode::Char('1')));
            app.handle_key(key(KeyCode::Char('+')));
        }
        app.handle_key(key(KeyCode::Char('1')));

        // Render narrow so the input wraps and the wrap width is recorded.
        let backend = TestBackend::new(24, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|frame| render(&app, frame)).unwrap();

        // The box grew beyond a single content line (3 = borders + 1).
        assert!(input_box_height(&app, 24) > 3);

        // Caret at the end sits on a lower wrapped line: Up stays in the input.
        app.handle_key(key(KeyCode::Up));
        assert_eq!(app.mode(), Mode::Input);

        // Caret on the first line: Up enters the history.
        app.cursor = TextCursor::at(0);
        app.handle_key(key(KeyCode::Up));
        assert!(matches!(app.mode(), Mode::History));
    }

    #[test]
    fn long_history_entry_wraps_instead_of_truncating() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut app = test_app();
        for c in "111111111111111111+7".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        app.handle_key(key(KeyCode::Enter));
        // Clear the transient status (it would truncate with an ellipsis).
        app.handle_key(key(KeyCode::Esc));

        // Narrow so the entry wraps; tall enough that the (now multi-line)
        // footer does not crowd the history off-screen.
        let backend = TestBackend::new(16, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|frame| render(&app, frame)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let screen: String =
            buffer.content().iter().map(|cell| cell.symbol()).collect();

        // No ellipsis anywhere, and the input's tail survived (it wrapped).
        assert!(!screen.contains('\u{2026}'));
        assert!(screen.contains("+7"));
    }

    #[test]
    fn highlighted_input_renders_without_panicking() {
        let mut app = test_app();
        for c in "sin(pi)+x".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        // The styled render path must preserve the typed characters.
        let screen = render_to_string(&app);
        assert!(screen.contains("sin(pi)+x"));
    }

    #[test]
    fn live_feedback_stays_silent_while_typing() {
        let mut app = test_app();
        for c in "2+".chars() {
            app.handle_key(key(KeyCode::Char(c)));
        }
        // Trailing operator looks unfinished: neither a preview nor a warning.
        let screen = render_to_string(&app);
        assert!(!screen.contains('\u{26a0}'));
        assert!(!screen.contains('='));
    }
}