frankensearch-tui 0.1.0

Shared TUI framework for frankensearch products (fsfs, ops TUI)
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
//! App shell: status bar, breadcrumbs, screen lifecycle.
//!
//! The [`AppShell`] owns the [`ScreenRegistry`], manages navigation between
//! screens, renders the chrome (status bar, breadcrumbs), and dispatches
//! input events to the active screen.

use std::cell::Cell;
use std::hash::{DefaultHasher, Hash, Hasher};

use ftui_core::geometry::Rect;
use ftui_render::frame::Frame;
use ftui_style::Style;
use ftui_text::{Line, Span};
use ftui_widgets::{
    Widget,
    block::Block,
    borders::{BorderType, Borders},
    paragraph::Paragraph,
};
use serde::{Deserialize, Serialize};

use crate::frame::{CachedLayout, CachedTabState};
use crate::input::{InputEvent, KeyAction, Keymap};
use crate::overlay::OverlayManager;
use crate::palette::{CommandPalette, PaletteState};
use crate::screen::{KeybindingHint, ScreenAction, ScreenContext, ScreenId, ScreenRegistry};
use crate::theme::Theme;

// ─── Shell Config ────────────────────────────────────────────────────────────

/// Configuration for the app shell.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShellConfig {
    /// Application title shown in the status bar.
    pub title: String,
    /// Theme preset to use.
    pub theme: Theme,
    /// Whether to show the status bar.
    pub show_status_bar: bool,
    /// Whether to show breadcrumbs (tab bar).
    pub show_breadcrumbs: bool,
}

impl Default for ShellConfig {
    fn default() -> Self {
        Self {
            title: "frankensearch".to_string(),
            theme: Theme::dark(),
            show_status_bar: true,
            show_breadcrumbs: true,
        }
    }
}

// ─── Status Line ─────────────────────────────────────────────────────────────

/// Status line content rendered at the bottom of the shell.
#[derive(Debug, Clone, Default)]
pub struct StatusLine {
    /// Left-aligned status text.
    pub left: String,
    /// Center status text.
    pub center: String,
    /// Right-aligned status text.
    pub right: String,
}

impl StatusLine {
    /// Create a new status line.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the left-aligned text.
    #[must_use]
    pub fn with_left(mut self, text: impl Into<String>) -> Self {
        self.left = text.into();
        self
    }

    /// Set the center text.
    #[must_use]
    pub fn with_center(mut self, text: impl Into<String>) -> Self {
        self.center = text.into();
        self
    }

    /// Set the right-aligned text.
    #[must_use]
    pub fn with_right(mut self, text: impl Into<String>) -> Self {
        self.right = text.into();
        self
    }
}

// ─── App Shell ───────────────────────────────────────────────────────────────

/// The main app shell that manages screens, chrome, and input dispatch.
pub struct AppShell {
    /// Shell configuration.
    pub config: ShellConfig,
    /// Screen registry.
    pub registry: ScreenRegistry,
    /// Currently active screen ID.
    pub active_screen: Option<ScreenId>,
    /// Keymap for input resolution.
    pub keymap: Keymap,
    /// Overlay manager.
    pub overlays: OverlayManager,
    /// Command palette.
    pub palette: CommandPalette,
    /// Status line content.
    pub status_line: StatusLine,
    /// Whether the app should quit.
    pub should_quit: bool,
    /// Last confirmed palette action ID (reset each `handle_input` call).
    last_palette_action: Option<String>,
    /// Terminal area captured from the most recent render pass.
    last_render_area: Cell<Rect>,
    /// Cached layout to avoid recomputing splits every frame.
    cached_layout: CachedLayout,
    /// Cached tab titles and selected index.
    cached_tabs: CachedTabState,
}

impl AppShell {
    fn build_help_overlay_request(&self) -> crate::overlay::OverlayRequest {
        let mut request = crate::overlay::OverlayRequest::new(
            crate::overlay::OverlayKind::Help,
            "Keyboard Shortcuts",
        )
        .with_body("Global shortcuts + active screen controls");

        if let Some(screen_id) = &self.active_screen
            && let Some(screen) = self.registry.get(screen_id)
        {
            let hints = screen.keybindings();
            if !hints.is_empty() {
                request.title = format!("Keyboard Shortcuts · {}", screen.title());
                request.actions = Self::encode_screen_keybindings(hints);
            }
        }

        request
    }

    fn encode_screen_keybindings(hints: &[KeybindingHint]) -> Vec<String> {
        hints
            .iter()
            .map(|hint| format!("{}|{}", hint.key, hint.description))
            .collect()
    }

    /// Create a new app shell with the given config.
    #[must_use]
    pub fn new(config: ShellConfig) -> Self {
        Self {
            config,
            registry: ScreenRegistry::new(),
            active_screen: None,
            keymap: Keymap::default_bindings(),
            overlays: OverlayManager::new(),
            palette: CommandPalette::new(),
            status_line: StatusLine::new(),
            should_quit: false,
            last_palette_action: None,
            last_render_area: Cell::new(Rect::new(0, 0, 0, 0)),
            cached_layout: CachedLayout::new(),
            cached_tabs: CachedTabState::new(),
        }
    }

    /// Navigate to a screen by ID.
    pub fn navigate_to(&mut self, id: &ScreenId) {
        if self.registry.get(id).is_some() {
            // Blur the old screen.
            if let Some(old_id) = &self.active_screen {
                let old_id = old_id.clone();
                if let Some(screen) = self.registry.get_mut(&old_id) {
                    screen.on_blur();
                }
            }
            // Focus the new screen.
            self.active_screen = Some(id.clone());
            if let Some(screen) = self.registry.get_mut(id) {
                screen.on_focus();
            }
            // Invalidate tab cache since the active screen changed.
            self.cached_tabs.invalidate();
        }
    }

    /// Navigate to the next screen in tab order.
    pub fn next_screen(&mut self) {
        if let Some(current) = &self.active_screen
            && let Some(next) = self.registry.next_screen(current).cloned()
        {
            self.navigate_to(&next);
        }
    }

    /// Navigate to the previous screen in tab order.
    pub fn prev_screen(&mut self) {
        if let Some(current) = &self.active_screen
            && let Some(prev) = self.registry.prev_screen(current).cloned()
        {
            self.navigate_to(&prev);
        }
    }

    /// Build the screen context for the current state.
    #[must_use]
    pub fn screen_context(&self, area: Rect) -> ScreenContext {
        ScreenContext {
            active_screen: self
                .active_screen
                .clone()
                .unwrap_or_else(|| ScreenId::new("")),
            terminal_width: area.width,
            terminal_height: area.height,
            focused: true,
        }
    }

    /// Handle an input event. Returns `true` if the app should quit.
    ///
    /// Returns the confirmed palette action ID if the user selected a command.
    /// Callers should check `last_palette_action()` after calling this.
    #[allow(clippy::too_many_lines)]
    pub fn handle_input(&mut self, event: &InputEvent) -> bool {
        self.last_palette_action = None;

        if let InputEvent::Resize(width, height) = event {
            self.last_render_area.set(Rect::new(0, 0, *width, *height));
        }

        if self.last_render_area.get().width == 0 || self.last_render_area.get().height == 0 {
            // Fallback keeps context sane in non-interactive test harnesses.
            self.last_render_area.set(Rect::new(0, 0, 80, 24));
        }

        // If the command palette is open, route input there first.
        if self.palette.state() == &PaletteState::Open {
            if let InputEvent::Key(key, mods) = event {
                if let Some(action) = self.keymap.resolve(*key, *mods) {
                    match action {
                        KeyAction::TogglePalette | KeyAction::Dismiss => {
                            self.palette.close();
                            return false;
                        }
                        KeyAction::Up => {
                            self.palette.select_prev();
                            return false;
                        }
                        KeyAction::Down => {
                            self.palette.select_next();
                            return false;
                        }
                        KeyAction::Confirm => {
                            if let Some(action_id) = self.palette.confirm() {
                                self.last_palette_action = Some(action_id);
                            }
                            self.palette.close();
                            return false;
                        }
                        _ => {}
                    }
                }
                // Handle text input for palette search.
                match key {
                    ftui_core::event::KeyCode::Char(ch)
                        if !mods.intersects(
                            ftui_core::event::Modifiers::CTRL
                                | ftui_core::event::Modifiers::ALT
                                | ftui_core::event::Modifiers::SUPER,
                        ) =>
                    {
                        self.palette.push_char(*ch);
                        return false;
                    }
                    ftui_core::event::KeyCode::Backspace => {
                        self.palette.pop_char();
                        return false;
                    }
                    _ => {}
                }
            }
            return false;
        }

        // If an overlay is active, let it handle first.
        if self.overlays.has_active() {
            if let InputEvent::Key(key, mods) = event
                && let Some(action) = self.keymap.resolve(*key, *mods)
                && action == &KeyAction::Dismiss
            {
                self.overlays.dismiss();
                return false;
            }
            return false;
        }

        // Resolve key actions.
        if let InputEvent::Key(key, mods) = event
            && let Some(action) = self.keymap.resolve(*key, *mods).cloned()
        {
            match action {
                KeyAction::Quit => {
                    self.should_quit = true;
                    return true;
                }
                KeyAction::NextScreen => {
                    self.next_screen();
                    return false;
                }
                KeyAction::PrevScreen => {
                    self.prev_screen();
                    return false;
                }
                KeyAction::ToggleHelp => {
                    if self
                        .overlays
                        .top()
                        .is_some_and(|o| o.kind == crate::overlay::OverlayKind::Help)
                    {
                        self.overlays.dismiss();
                    } else {
                        self.overlays.push(self.build_help_overlay_request());
                    }
                    return false;
                }
                KeyAction::TogglePalette => {
                    self.palette.toggle();
                    return false;
                }
                KeyAction::CycleTheme => {
                    self.config.theme = Theme::from_preset(self.config.theme.preset.next());
                    self.cached_tabs.invalidate();
                    return false;
                }
                _ => {}
            }
        }

        // Forward to active screen.
        if let Some(screen_id) = &self.active_screen {
            let screen_id = screen_id.clone();
            let ctx = self.screen_context(self.last_render_area.get());
            if let Some(screen) = self.registry.get_mut(&screen_id) {
                match screen.handle_input(event, &ctx) {
                    ScreenAction::Quit => {
                        self.should_quit = true;
                        return true;
                    }
                    ScreenAction::Navigate(target) => {
                        self.navigate_to(&target);
                    }
                    ScreenAction::OpenOverlay(name) => {
                        self.overlays.push(crate::overlay::OverlayRequest::new(
                            crate::overlay::OverlayKind::Custom(name.clone()),
                            name,
                        ));
                    }
                    ScreenAction::Consumed | ScreenAction::Ignored => {}
                }
            }
        }

        false
    }

    /// Get the last palette action confirmed by the user.
    ///
    /// Returns `Some(action_id)` if the user selected an action from the
    /// command palette during the last `handle_input()` call.
    #[must_use]
    pub fn last_palette_action(&self) -> Option<&str> {
        self.last_palette_action.as_deref()
    }

    /// Render the shell chrome and active screen.
    ///
    /// Uses cached layout and tab state to avoid redundant allocations
    /// when the terminal dimensions and screen configuration haven't changed.
    #[allow(clippy::too_many_lines)]
    pub fn render(&mut self, frame: &mut Frame) {
        let area = frame.bounds();
        self.last_render_area.set(area);
        let ctx = self.screen_context(area);

        // Cached layout avoids recomputing splits when area hasn't changed.
        // Copy the Rect values directly (Rect is Copy, 8 bytes) instead of
        // allocating a Vec clone every frame.
        let show_bc = self.config.show_breadcrumbs;
        let show_sb = self.config.show_status_bar;
        let num_screens = self.registry.len();
        let layout_chunks = self
            .cached_layout
            .get_or_compute(area, show_bc, show_sb, num_screens);
        let bc_area = if show_bc && num_screens > 1 {
            Some(layout_chunks[0])
        } else {
            None
        };
        let content_idx = usize::from(bc_area.is_some());
        let content_area = layout_chunks[content_idx];
        let status_area = if show_sb {
            Some(layout_chunks[content_idx + 1])
        } else {
            None
        };

        // Breadcrumbs / tabs (using cached titles and selected index).
        if let Some(bc_rect) = bc_area {
            let screen_ids = self.registry.screen_ids();
            let mut id_hasher = DefaultHasher::new();
            let mut title_hasher = DefaultHasher::new();
            for id in screen_ids {
                id.0.hash(&mut id_hasher);
                id.0.hash(&mut title_hasher);
                if let Some(screen) = self.registry.get(id) {
                    screen.title().hash(&mut title_hasher);
                }
            }
            let screen_ids_hash = id_hasher.finish();
            let title_signature = title_hasher.finish();
            let active_str = self.active_screen.as_ref().map(|id| id.0.as_str());

            if !self
                .cached_tabs
                .is_valid(screen_ids_hash, title_signature, active_str)
            {
                let titles: Vec<String> = screen_ids
                    .iter()
                    .map(|id| {
                        self.registry
                            .get(id)
                            .map_or_else(|| id.0.clone(), |s| s.title().to_string())
                    })
                    .collect();

                let selected = self
                    .active_screen
                    .as_ref()
                    .and_then(|active| screen_ids.iter().position(|id| id == active))
                    .unwrap_or(0);

                self.cached_tabs.update(
                    titles,
                    selected,
                    screen_ids_hash,
                    title_signature,
                    active_str,
                );
            }

            let mut tab_spans: Vec<Span<'_>> = Vec::new();
            for (i, title) in self.cached_tabs.titles.iter().enumerate() {
                if i > 0 {
                    tab_spans.push(Span::styled(
                        " \u{2502} ",
                        Style::new().fg(self.config.theme.border.to_color()),
                    ));
                }
                if i == self.cached_tabs.selected {
                    tab_spans.push(Span::styled(
                        format!(" {title} "),
                        Style::new()
                            .fg(self.config.theme.highlight_fg.to_color())
                            .bg(self.config.theme.accent.to_color())
                            .bold(),
                    ));
                } else {
                    tab_spans.push(Span::styled(
                        format!(" {title} "),
                        Style::new().fg(self.config.theme.muted.to_color()).bg(self
                            .config
                            .theme
                            .bg
                            .to_color()),
                    ));
                }
            }
            let tab_line = Paragraph::new(Line::from_spans(tab_spans))
                .style(Style::new().bg(self.config.theme.bg.to_color()));

            tab_line.render(bc_rect, frame);
        }

        // Main content area.
        if let Some(screen_id) = &self.active_screen {
            if let Some(screen) = self.registry.get(screen_id) {
                screen.render(frame, &ctx);
            }
        } else {
            // No screen active — render placeholder.
            let block = Block::new()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::new().fg(self.config.theme.border.to_color()))
                .style(
                    Style::new().bg(self.config.theme.bg.to_color()).fg(self
                        .config
                        .theme
                        .fg
                        .to_color()),
                );
            let placeholder = Paragraph::new("No screens registered").block(block);
            placeholder.render(content_area, frame);
        }

        // Status bar.
        if let Some(sb_rect) = status_area {
            let status_text = if self.status_line.center.is_empty() {
                format!(" {} ", self.config.title)
            } else {
                format!(
                    " {} \u{2502} {} ",
                    self.config.title, self.status_line.center
                )
            };

            let active_screen_hints = self
                .active_screen
                .as_ref()
                .and_then(|id| self.registry.get(id))
                .map_or(&[][..], |screen| screen.keybindings());
            let hints = Self::status_bar_hints(sb_rect.width, active_screen_hints);
            let left_content_len =
                self.status_line.left.len() + status_text.len() + self.status_line.right.len();
            let pad_width = (sb_rect.width as usize).saturating_sub(left_content_len + hints.len());
            let padding = " ".repeat(pad_width);

            let muted_style = Style::new().fg(self.config.theme.muted.to_color());

            let status_spans = vec![
                Span::styled(
                    self.status_line.left.clone(),
                    Style::new().fg(self.config.theme.status_bar_fg.to_color()),
                ),
                Span::styled(
                    status_text,
                    Style::new()
                        .fg(self.config.theme.status_bar_fg.to_color())
                        .bold(),
                ),
                Span::styled(
                    self.status_line.right.clone(),
                    Style::new().fg(self.config.theme.status_bar_fg.to_color()),
                ),
                Span::raw(padding),
                Span::styled(hints, muted_style),
            ];

            let status = Paragraph::new(Line::from_spans(status_spans))
                .style(Style::new().bg(self.config.theme.status_bar_bg.to_color()));

            status.render(sb_rect, frame);
        }
    }

    /// Build right-aligned keybinding hints for the status bar.
    fn status_bar_hints(width: u16, screen_hints: &[KeybindingHint]) -> String {
        if width < 60 {
            return String::new();
        }

        let mut base = if width < 90 {
            "Tab:Nav  ?:Help  ^T:Theme ".to_string()
        } else {
            "Tab:Nav  ?:Help  ^P:Cmd  ^T:Theme  q:Quit ".to_string()
        };

        if width >= 110 && !screen_hints.is_empty() {
            let contextual = screen_hints
                .iter()
                .take(2)
                .map(|hint| format!("{} {}", hint.key, hint.description))
                .collect::<Vec<_>>()
                .join("  ");
            if !contextual.is_empty() {
                base.push_str("| ");
                base.push_str(&contextual);
                base.push(' ');
            }
        }

        base
    }
}

#[cfg(test)]
mod tests {
    use std::any::Any;
    use std::sync::{Arc, Mutex};

    use ftui_render::frame::Frame;

    use crate::screen::{Screen, ScreenAction};

    use super::*;

    #[test]
    fn shell_config_default() {
        let config = ShellConfig::default();
        assert_eq!(config.title, "frankensearch");
        assert!(config.show_status_bar);
        assert!(config.show_breadcrumbs);
    }

    #[test]
    fn status_line_builder() {
        let status = StatusLine::new()
            .with_left("left")
            .with_center("center")
            .with_right("right");
        assert_eq!(status.left, "left");
        assert_eq!(status.center, "center");
        assert_eq!(status.right, "right");
    }

    #[test]
    fn shell_creation() {
        let shell = AppShell::new(ShellConfig::default());
        assert!(!shell.should_quit);
        assert!(shell.active_screen.is_none());
        assert!(shell.registry.is_empty());
    }

    #[test]
    fn shell_config_serde_roundtrip() {
        let config = ShellConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let decoded: ShellConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.title, config.title);
    }

    #[test]
    fn shell_quit_handling() {
        let mut shell = AppShell::new(ShellConfig::default());
        let event = InputEvent::Key(
            ftui_core::event::KeyCode::Char('q'),
            ftui_core::event::Modifiers::NONE,
        );
        let quit = shell.handle_input(&event);
        assert!(quit);
        assert!(shell.should_quit);
    }

    struct CaptureContextScreen {
        id: ScreenId,
        captured: Arc<Mutex<Option<(u16, u16)>>>,
    }

    impl CaptureContextScreen {
        fn new(id: &str, captured: Arc<Mutex<Option<(u16, u16)>>>) -> Self {
            Self {
                id: ScreenId::new(id),
                captured,
            }
        }
    }

    impl Screen for CaptureContextScreen {
        fn id(&self) -> &ScreenId {
            &self.id
        }

        fn title(&self) -> &'static str {
            "capture"
        }

        fn render(&self, _frame: &mut Frame, _ctx: &ScreenContext) {}

        fn handle_input(&mut self, _event: &InputEvent, ctx: &ScreenContext) -> ScreenAction {
            *self.captured.lock().expect("capture lock") =
                Some((ctx.terminal_width, ctx.terminal_height));
            ScreenAction::Consumed
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn as_any_mut(&mut self) -> &mut dyn Any {
            self
        }
    }

    #[test]
    fn handle_input_uses_last_render_area_for_context() {
        let mut shell = AppShell::new(ShellConfig::default());
        let captured = Arc::new(Mutex::new(None));
        let screen_id = ScreenId::new("capture");
        shell.registry.register(Box::new(CaptureContextScreen::new(
            "capture",
            captured.clone(),
        )));
        shell.navigate_to(&screen_id);

        shell.last_render_area.set(Rect::new(0, 0, 132, 47));
        let event = InputEvent::Key(
            ftui_core::event::KeyCode::Char('x'),
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&event);

        let seen = captured
            .lock()
            .expect("capture lock")
            .expect("context captured");
        assert_eq!(seen, (132, 47));
    }

    #[test]
    fn palette_toggle_shortcut_closes_palette_when_open() {
        let mut shell = AppShell::new(ShellConfig::default());
        let toggle = InputEvent::Key(
            ftui_core::event::KeyCode::Char('p'),
            ftui_core::event::Modifiers::CTRL,
        );

        let _ = shell.handle_input(&toggle);
        assert_eq!(shell.palette.state(), &PaletteState::Open);

        let _ = shell.handle_input(&toggle);
        assert_eq!(shell.palette.state(), &PaletteState::Closed);
    }

    #[test]
    fn palette_accepts_shift_modified_characters() {
        let mut shell = AppShell::new(ShellConfig::default());
        let open = InputEvent::Key(
            ftui_core::event::KeyCode::Char('p'),
            ftui_core::event::Modifiers::CTRL,
        );
        let _ = shell.handle_input(&open);

        let shifted = InputEvent::Key(
            ftui_core::event::KeyCode::Char('A'),
            ftui_core::event::Modifiers::SHIFT,
        );
        let _ = shell.handle_input(&shifted);

        assert_eq!(shell.palette.query(), "A");
    }

    #[test]
    fn resize_event_refreshes_context_dimensions() {
        let mut shell = AppShell::new(ShellConfig::default());
        let captured = Arc::new(Mutex::new(None));
        let screen_id = ScreenId::new("capture");
        shell.registry.register(Box::new(CaptureContextScreen::new(
            "capture",
            captured.clone(),
        )));
        shell.navigate_to(&screen_id);

        let resize = InputEvent::Resize(111, 37);
        let _ = shell.handle_input(&resize);

        let key = InputEvent::Key(
            ftui_core::event::KeyCode::Char('x'),
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&key);

        let seen = captured
            .lock()
            .expect("capture lock")
            .expect("context captured");
        assert_eq!(seen, (111, 37));
    }

    // ─── bd-n6x8 tests begin ───

    /// Minimal stub screen for navigation/lifecycle tests.
    struct StubScreen {
        id: ScreenId,
        title: &'static str,
        focused: Arc<Mutex<bool>>,
    }

    impl StubScreen {
        fn new(id: &str, title: &'static str) -> Self {
            Self {
                id: ScreenId::new(id),
                title,
                focused: Arc::new(Mutex::new(false)),
            }
        }

        #[expect(dead_code)]
        fn is_focused(&self) -> bool {
            *self.focused.lock().unwrap()
        }
    }

    impl Screen for StubScreen {
        fn id(&self) -> &ScreenId {
            &self.id
        }

        fn title(&self) -> &'static str {
            self.title
        }

        fn render(&self, _frame: &mut Frame, _ctx: &ScreenContext) {}

        fn handle_input(&mut self, _event: &InputEvent, _ctx: &ScreenContext) -> ScreenAction {
            ScreenAction::Ignored
        }

        fn on_focus(&mut self) {
            *self.focused.lock().unwrap() = true;
        }

        fn on_blur(&mut self) {
            *self.focused.lock().unwrap() = false;
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn as_any_mut(&mut self) -> &mut dyn Any {
            self
        }
    }

    #[test]
    fn status_line_default_is_empty() {
        let sl = StatusLine::default();
        assert!(sl.left.is_empty());
        assert!(sl.center.is_empty());
        assert!(sl.right.is_empty());
    }

    #[test]
    fn status_line_new_matches_default() {
        let n = StatusLine::new();
        let d = StatusLine::default();
        assert_eq!(n.left, d.left);
        assert_eq!(n.center, d.center);
        assert_eq!(n.right, d.right);
    }

    #[test]
    fn status_line_partial_builder_only_left() {
        let sl = StatusLine::new().with_left("L");
        assert_eq!(sl.left, "L");
        assert!(sl.center.is_empty());
        assert!(sl.right.is_empty());
    }

    #[test]
    fn status_line_partial_builder_only_right() {
        let sl = StatusLine::new().with_right("R");
        assert!(sl.left.is_empty());
        assert!(sl.center.is_empty());
        assert_eq!(sl.right, "R");
    }

    #[test]
    fn status_line_debug() {
        let sl = StatusLine::new().with_center("mid");
        let debug = format!("{sl:?}");
        assert!(debug.contains("StatusLine"));
    }

    #[test]
    fn status_line_clone() {
        let sl = StatusLine::new().with_left("L").with_center("C");
        #[allow(clippy::redundant_clone)]
        let cloned = sl.clone();
        assert_eq!(cloned.left, "L");
        assert_eq!(cloned.center, "C");
    }

    #[test]
    fn shell_config_debug() {
        let config = ShellConfig::default();
        let debug = format!("{config:?}");
        assert!(debug.contains("ShellConfig"));
        assert!(debug.contains("frankensearch"));
    }

    #[test]
    fn shell_config_clone() {
        let config = ShellConfig::default();
        #[allow(clippy::redundant_clone)]
        let cloned = config.clone();
        assert_eq!(cloned.title, "frankensearch");
        assert!(cloned.show_status_bar);
    }

    #[test]
    fn navigate_to_nonexistent_screen_is_noop() {
        let mut shell = AppShell::new(ShellConfig::default());
        let bad_id = ScreenId::new("nonexistent");
        shell.navigate_to(&bad_id);
        assert!(shell.active_screen.is_none());
    }

    #[test]
    fn navigate_to_valid_screen() {
        let mut shell = AppShell::new(ShellConfig::default());
        let id_a = ScreenId::new("a");
        shell
            .registry
            .register(Box::new(StubScreen::new("a", "Screen A")));
        shell.navigate_to(&id_a);
        assert_eq!(shell.active_screen.as_ref(), Some(&id_a));
    }

    #[test]
    fn navigate_blurs_old_focuses_new() {
        let mut shell = AppShell::new(ShellConfig::default());
        let focused_a = Arc::new(Mutex::new(false));
        let focused_b = Arc::new(Mutex::new(false));
        let screen_a = StubScreen {
            id: ScreenId::new("a"),
            title: "A",
            focused: Arc::clone(&focused_a),
        };
        let screen_b = StubScreen {
            id: ScreenId::new("b"),
            title: "B",
            focused: Arc::clone(&focused_b),
        };
        shell.registry.register(Box::new(screen_a));
        shell.registry.register(Box::new(screen_b));

        let id_a = ScreenId::new("a");
        let id_b = ScreenId::new("b");

        shell.navigate_to(&id_a);
        assert!(*focused_a.lock().unwrap());

        shell.navigate_to(&id_b);
        assert!(!*focused_a.lock().unwrap(), "old screen should be blurred");
        assert!(*focused_b.lock().unwrap(), "new screen should be focused");
    }

    #[test]
    fn next_screen_with_no_active_is_noop() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.registry.register(Box::new(StubScreen::new("a", "A")));
        shell.next_screen();
        assert!(shell.active_screen.is_none());
    }

    #[test]
    fn prev_screen_with_no_active_is_noop() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.registry.register(Box::new(StubScreen::new("a", "A")));
        shell.prev_screen();
        assert!(shell.active_screen.is_none());
    }

    #[test]
    fn screen_context_with_no_active_uses_empty_id() {
        let shell = AppShell::new(ShellConfig::default());
        let ctx = shell.screen_context(Rect::new(0, 0, 100, 50));
        assert_eq!(ctx.active_screen, ScreenId::new(""));
        assert_eq!(ctx.terminal_width, 100);
        assert_eq!(ctx.terminal_height, 50);
        assert!(ctx.focused);
    }

    #[test]
    fn screen_context_with_active_screen() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell
            .registry
            .register(Box::new(StubScreen::new("s1", "S1")));
        shell.navigate_to(&ScreenId::new("s1"));
        let ctx = shell.screen_context(Rect::new(0, 0, 80, 24));
        assert_eq!(ctx.active_screen, ScreenId::new("s1"));
    }

    #[test]
    fn last_palette_action_initially_none() {
        let shell = AppShell::new(ShellConfig::default());
        assert!(shell.last_palette_action().is_none());
    }

    #[test]
    fn palette_backspace_removes_char() {
        let mut shell = AppShell::new(ShellConfig::default());
        // Open palette
        let open = InputEvent::Key(
            ftui_core::event::KeyCode::Char('p'),
            ftui_core::event::Modifiers::CTRL,
        );
        let _ = shell.handle_input(&open);

        // Type "ab"
        let a = InputEvent::Key(
            ftui_core::event::KeyCode::Char('a'),
            ftui_core::event::Modifiers::NONE,
        );
        let b = InputEvent::Key(
            ftui_core::event::KeyCode::Char('b'),
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&a);
        let _ = shell.handle_input(&b);
        assert_eq!(shell.palette.query(), "ab");

        // Backspace
        let bs = InputEvent::Key(
            ftui_core::event::KeyCode::Backspace,
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&bs);
        assert_eq!(shell.palette.query(), "a");
    }

    #[test]
    fn palette_esc_closes() {
        let mut shell = AppShell::new(ShellConfig::default());
        let open = InputEvent::Key(
            ftui_core::event::KeyCode::Char('p'),
            ftui_core::event::Modifiers::CTRL,
        );
        let _ = shell.handle_input(&open);
        assert_eq!(shell.palette.state(), &PaletteState::Open);

        let esc = InputEvent::Key(
            ftui_core::event::KeyCode::Escape,
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&esc);
        assert_eq!(shell.palette.state(), &PaletteState::Closed);
    }

    #[test]
    fn palette_enter_closes_and_clears() {
        let mut shell = AppShell::new(ShellConfig::default());
        let open = InputEvent::Key(
            ftui_core::event::KeyCode::Char('p'),
            ftui_core::event::Modifiers::CTRL,
        );
        let _ = shell.handle_input(&open);
        assert_eq!(shell.palette.state(), &PaletteState::Open);

        let enter = InputEvent::Key(
            ftui_core::event::KeyCode::Enter,
            ftui_core::event::Modifiers::NONE,
        );
        let quit = shell.handle_input(&enter);
        assert!(!quit);
        assert_eq!(shell.palette.state(), &PaletteState::Closed);
    }

    #[test]
    fn overlay_esc_dismisses() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.last_render_area.set(Rect::new(0, 0, 80, 24));

        // Open help overlay with '?'
        let help = InputEvent::Key(
            ftui_core::event::KeyCode::Char('?'),
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&help);
        assert!(shell.overlays.has_active());

        // Dismiss with Esc
        let esc = InputEvent::Key(
            ftui_core::event::KeyCode::Escape,
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&esc);
        assert!(!shell.overlays.has_active());
    }

    #[test]
    fn help_opens_with_question_mark() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.last_render_area.set(Rect::new(0, 0, 80, 24));

        let help = InputEvent::Key(
            ftui_core::event::KeyCode::Char('?'),
            ftui_core::event::Modifiers::NONE,
        );

        let _ = shell.handle_input(&help);
        assert!(shell.overlays.has_active());

        // When overlay is active, non-Dismiss keys are swallowed
        let _ = shell.handle_input(&help);
        assert!(
            shell.overlays.has_active(),
            "overlay stays open on repeat ?"
        );
    }

    #[test]
    fn tab_key_triggers_next_screen() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.last_render_area.set(Rect::new(0, 0, 80, 24));
        shell.registry.register(Box::new(StubScreen::new("a", "A")));
        shell.registry.register(Box::new(StubScreen::new("b", "B")));
        shell.navigate_to(&ScreenId::new("a"));

        let tab = InputEvent::Key(
            ftui_core::event::KeyCode::Tab,
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&tab);
        assert_eq!(shell.active_screen.as_ref(), Some(&ScreenId::new("b")));
    }

    #[test]
    fn shift_tab_triggers_prev_screen() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.last_render_area.set(Rect::new(0, 0, 80, 24));
        shell.registry.register(Box::new(StubScreen::new("a", "A")));
        shell.registry.register(Box::new(StubScreen::new("b", "B")));
        shell.navigate_to(&ScreenId::new("b"));

        let shift_tab = InputEvent::Key(
            ftui_core::event::KeyCode::BackTab,
            ftui_core::event::Modifiers::SHIFT,
        );
        let _ = shell.handle_input(&shift_tab);
        assert_eq!(shell.active_screen.as_ref(), Some(&ScreenId::new("a")));
    }

    #[test]
    fn overlay_active_blocks_screen_input() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.last_render_area.set(Rect::new(0, 0, 80, 24));
        let captured = Arc::new(Mutex::new(None));
        shell
            .registry
            .register(Box::new(CaptureContextScreen::new("cap", captured.clone())));
        shell.navigate_to(&ScreenId::new("cap"));

        // Open overlay
        let help = InputEvent::Key(
            ftui_core::event::KeyCode::Char('?'),
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&help);
        assert!(shell.overlays.has_active());

        // Send a key that would normally reach the screen
        let x = InputEvent::Key(
            ftui_core::event::KeyCode::Char('x'),
            ftui_core::event::Modifiers::NONE,
        );
        let _ = shell.handle_input(&x);
        // Screen should NOT have received the event
        assert!(captured.lock().unwrap().is_none());
    }

    #[test]
    fn palette_ctrl_char_not_inserted() {
        let mut shell = AppShell::new(ShellConfig::default());
        let open = InputEvent::Key(
            ftui_core::event::KeyCode::Char('p'),
            ftui_core::event::Modifiers::CTRL,
        );
        let _ = shell.handle_input(&open);

        // Ctrl+A should NOT be inserted as text
        let ctrl_a = InputEvent::Key(
            ftui_core::event::KeyCode::Char('a'),
            ftui_core::event::Modifiers::CTRL,
        );
        let _ = shell.handle_input(&ctrl_a);
        assert_eq!(shell.palette.query(), "");
    }

    #[test]
    fn palette_alt_char_not_inserted() {
        let mut shell = AppShell::new(ShellConfig::default());
        let open = InputEvent::Key(
            ftui_core::event::KeyCode::Char('p'),
            ftui_core::event::Modifiers::CTRL,
        );
        let _ = shell.handle_input(&open);

        let alt_x = InputEvent::Key(
            ftui_core::event::KeyCode::Char('x'),
            ftui_core::event::Modifiers::ALT,
        );
        let _ = shell.handle_input(&alt_x);
        assert_eq!(shell.palette.query(), "");
    }

    #[test]
    fn handle_input_does_not_quit_on_non_quit_key() {
        let mut shell = AppShell::new(ShellConfig::default());
        shell.last_render_area.set(Rect::new(0, 0, 80, 24));
        let event = InputEvent::Key(
            ftui_core::event::KeyCode::Char('a'),
            ftui_core::event::Modifiers::NONE,
        );
        let quit = shell.handle_input(&event);
        assert!(!quit);
        assert!(!shell.should_quit);
    }

    // ─── bd-n6x8 tests end ───
}