chainview 0.1.2

Terminal UI for option chains, Greeks and volatility - real-time market data and backtest replay in your terminal.
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
//! The auto/dark/light theme, the modal help-overlay renderer, the truthful
//! status bar / keybar, and the `NO_COLOR` fallback (`docs/05-views-and-ux.md`
//! §7, §8).
//!
//! # The keymap is the source of truth; this module renders it
//!
//! The single-source keybinding map lives in the **application** layer
//! ([`crate::app::keymap`]) so both the dispatch and this overlay read one table
//! (`docs/05-views-and-ux.md` §3). This module depends on it
//! ([`help_sections`](crate::app::keymap)) to **generate** the help overlay —
//! `ui → application`, the allowed direction — and holds no dispatch logic itself,
//! so a bound key and its documentation cannot drift.
//!
//! # Color is never the only signal; `NO_COLOR` is honored
//!
//! Every color-encoded state also carries a glyph or text marker — the at-spot row
//! carries [`AT_SPOT_MARKER`], the P&L sign carries `+`/`−`, the tick direction
//! carries `▲`/`▼`/`·` — so the UI is legible on a monochrome terminal and to
//! color-blind users (`docs/05-views-and-ux.md` §7, `CLAUDE.md` accessibility
//! policy). When `NO_COLOR` is set ([`Theme::no_color`]), [`Theme`] drops every
//! foreground/background color and falls back to intensity + markers only; the
//! markers are always present regardless of color.
//!
//! # The draw path stays pure
//!
//! Every function here is a pure projection over borrowed [`App`] state: the
//! spinner/clock advances off [`App::tick_count`], never a wall clock read in
//! `draw`, and no I/O or heavy compute happens while rendering
//! (`docs/02-tui-architecture.md` §7). The responsive chain column-drop **order**
//! ([`greek_columns_for_slots`]) and the cross-screen too-small guard
//! ([`is_too_small`]) live here; the chain-matrix body that consumes them lands in
//! #18.

use optionstratlib::prelude::{Decimal, Positive};
use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block, Clear, Paragraph};

use crate::app::keymap::{Binding, help_sections};
use crate::app::{
    App, BundleLoad, LiveScreen, LiveState, Mode, ReplayScreen, ReplayState, ScreenLoad,
    is_replay_screen_reachable, live_screen_name, replay_screen_name,
};
use crate::chain::{StreamHealth, TickDir};
use crate::config::ThemeChoice;
use crate::replay::Playback;

// ===========================================================================
// Theme + palette (auto/dark/light, NO_COLOR fallback).
// ===========================================================================

/// The resolved color variant a [`Theme`] paints with
/// (`docs/05-views-and-ux.md` §7). An optional user override is deferred past v1;
/// v0.1 ships the built-in variants only, resolved from [`ThemeChoice`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ThemeVariant {
    /// A palette tuned for a dark terminal background (the zero-config base).
    #[default]
    Dark,
    /// A palette tuned for a light terminal background.
    Light,
}

/// The resolved theme the draw path reads: the color variant plus the `NO_COLOR`
/// flag (`docs/05-views-and-ux.md` §7).
///
/// Built once per frame from [`App::theme`] and [`App::no_color`] by
/// [`Theme::resolve`]; every semantic style getter honors [`no_color`](Self::no_color)
/// so a color-encoded state degrades to intensity + markers only, never color
/// alone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Theme {
    /// The resolved color variant.
    pub variant: ThemeVariant,
    /// Whether color is disabled (`NO_COLOR` / `--no-color` / config). When set,
    /// every semantic style resolves to intensity/markers only, with no color.
    pub no_color: bool,
}

impl Theme {
    /// Resolve the concrete theme from the user's [`ThemeChoice`] and the
    /// `no_color` flag (`docs/05-views-and-ux.md` §7).
    ///
    /// `Auto` resolves to a palette built from the 16 ANSI-named colors, which the
    /// terminal maps to its own palette — legible on **both** dark and light
    /// backgrounds with zero config ([ADR-0003]). Terminal-background detection is
    /// terminal I/O and cannot happen in the pure draw path, so `Auto` uses the
    /// adaptive ANSI base rather than probing.
    ///
    /// [ADR-0003]: https://github.com/joaquinbejar/ChainView/blob/main/docs/adr/0003-zero-config-first-run.md
    #[must_use]
    pub fn resolve(choice: ThemeChoice, no_color: bool) -> Self {
        let variant = match choice {
            // The adaptive ANSI base reads on both; `Auto` uses the dark tuning,
            // which relies only on named colors the terminal remaps to its theme.
            ThemeChoice::Auto | ThemeChoice::Dark => ThemeVariant::Dark,
            ThemeChoice::Light => ThemeVariant::Light,
        };
        Self { variant, no_color }
    }

    /// A semantic style: `color` foreground plus `modifier`, or — under
    /// [`no_color`](Self::no_color) — only `modifier`, so no color code is emitted
    /// but the intensity (bold/dim) survives.
    #[must_use]
    fn semantic(self, color: Color, modifier: Modifier) -> Style {
        let base = Style::new().add_modifier(modifier);
        if self.no_color { base } else { base.fg(color) }
    }

    /// The accent style for headers, keys, and the focused affordance.
    #[must_use]
    pub fn accent(self) -> Style {
        self.semantic(Color::Cyan, Modifier::BOLD)
    }

    /// The dim style for secondary text (never colored, so it is `NO_COLOR`-safe
    /// already).
    #[must_use]
    pub fn dim(self) -> Style {
        Style::new().add_modifier(Modifier::DIM)
    }

    /// The style for a transient warning/hint in the keybar.
    #[must_use]
    pub fn warning(self) -> Style {
        self.semantic(Color::Yellow, Modifier::BOLD)
    }

    /// The style for a stream-health badge, exhaustive over [`StreamHealth`].
    #[must_use]
    pub fn health_style(self, health: &StreamHealth) -> Style {
        match health {
            StreamHealth::Live => self.semantic(Color::Green, Modifier::BOLD),
            StreamHealth::Stale { .. } | StreamHealth::Reconnecting { .. } => {
                self.semantic(Color::Yellow, Modifier::BOLD)
            }
        }
    }

    /// The shading style for the shared strike column, keyed on the `K/S`
    /// [`StrikeRelation`] bucket (`docs/05-views-and-ux.md` §7). Deliberately not
    /// an ITM/OTM label. Under `NO_COLOR` the shading drops and the `◀ATM` marker
    /// plus the numeric strike ordering convey the relation.
    #[must_use]
    pub fn strike_relation_style(self, rel: StrikeRelation) -> Style {
        match rel {
            StrikeRelation::BelowSpot => self.semantic(Color::Green, Modifier::empty()),
            StrikeRelation::AtSpot => self.semantic(Color::Yellow, Modifier::BOLD),
            StrikeRelation::AboveSpot => self.semantic(Color::Red, Modifier::empty()),
        }
    }

    /// The style for a price-direction indicator, exhaustive over [`TickDir`].
    #[must_use]
    pub fn tick_dir_style(self, dir: TickDir) -> Style {
        match dir {
            TickDir::Up => self.semantic(Color::Green, Modifier::empty()),
            TickDir::Down => self.semantic(Color::Red, Modifier::empty()),
            TickDir::Flat => self.dim(),
        }
    }

    /// The style for a signed P&L value: red when negative, green when
    /// non-negative. The `+`/`−` sign ([`pnl_sign_char`]) carries the sign under
    /// `NO_COLOR`.
    #[must_use]
    pub fn pnl_style(self, is_negative: bool) -> Style {
        if is_negative {
            self.semantic(Color::Red, Modifier::empty())
        } else {
            self.semantic(Color::Green, Modifier::empty())
        }
    }

    /// The style for an order-book side on the depth ladder (#48): green for a
    /// **bid** (the buy side), red for an **ask** (the sell side). Color only
    /// reinforces — the depth screen's `bid`/`ask` text label carries the side under
    /// `NO_COLOR`, so the ladder reads on a monochrome terminal.
    #[must_use]
    pub fn book_side_style(self, is_bid: bool) -> Style {
        if is_bid {
            self.semantic(Color::Green, Modifier::empty())
        } else {
            self.semantic(Color::Red, Modifier::empty())
        }
    }
}

// ===========================================================================
// Color-independent markers + view-model buckets.
// ===========================================================================

/// The marker on the at-spot strike row (`docs/05-views-and-ux.md` §7) — the
/// color-independent signal that survives a monochrome terminal.
pub const AT_SPOT_MARKER: &str = "◀ATM";

/// The default at-the-money band, as the `|K/S − 1|` tolerance that buckets a
/// strike as [`StrikeRelation::AtSpot`] (`docs/01-domain-model.md` §8). `0.005`
/// is 0.5%.
pub const ATM_BAND_PERMILLE: i64 = 5;

/// A row-level, option-style-**independent** relation of the strike to spot,
/// defined once as the `K/S` bucket (`docs/01-domain-model.md` §8).
///
/// Deliberately **not** an ITM/OTM label: a call and a put at one strike have
/// opposite ITM/OTM status, so no single label on a shared strike row can be
/// truthful. This value shades only the shared **strike column** by where the
/// strike sits relative to spot. It is a UI view-model bucket (computed at
/// projection time, borrowed, never stored); the chain-matrix body that renders it
/// lands in #18.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum StrikeRelation {
    /// `K < S · (1 − band)` — the call leg is ITM here, the put OTM.
    BelowSpot,
    /// `|K/S − 1| ≤ band` — the nearest listed strike(s) to spot.
    AtSpot,
    /// `K > S · (1 + band)` — the put leg is ITM here, the call OTM.
    AboveSpot,
}

impl StrikeRelation {
    /// Bucket a `strike` against `spot` by the `K/S` ratio, using the documented
    /// [`ATM_BAND_PERMILLE`] tolerance (`docs/01-domain-model.md` §8).
    ///
    /// Computed with [`Decimal`] and checked multiplication only (no division, so
    /// no rounding policy is needed); a zero spot or an arithmetic overflow falls
    /// back to the neutral [`AtSpot`](Self::AtSpot) rather than panicking, so a
    /// degenerate quote can never crash a frame.
    #[must_use]
    pub fn classify(strike: Positive, spot: Positive) -> Self {
        let spot_dec = spot.to_dec();
        if spot_dec == Decimal::ZERO {
            return Self::AtSpot;
        }
        let band = Decimal::new(ATM_BAND_PERMILLE, 3);
        let strike_dec = strike.to_dec();
        let lower = Decimal::ONE
            .checked_sub(band)
            .and_then(|f| spot_dec.checked_mul(f));
        let upper = Decimal::ONE
            .checked_add(band)
            .and_then(|f| spot_dec.checked_mul(f));
        let (Some(lower), Some(upper)) = (lower, upper) else {
            return Self::AtSpot;
        };
        if strike_dec < lower {
            Self::BelowSpot
        } else if strike_dec > upper {
            Self::AboveSpot
        } else {
            Self::AtSpot
        }
    }
}

/// The color-independent marker for a strike relation: the [`AT_SPOT_MARKER`] for
/// the at-spot row, empty otherwise (`docs/05-views-and-ux.md` §7). Below/above
/// spot are conveyed by the marked at-spot row plus the numeric strike ordering,
/// so they need no separate glyph.
#[must_use]
pub fn strike_relation_marker(rel: StrikeRelation) -> &'static str {
    match rel {
        StrikeRelation::AtSpot => AT_SPOT_MARKER,
        StrikeRelation::BelowSpot | StrikeRelation::AboveSpot => "",
    }
}

/// The color-independent glyph for a price-direction indicator
/// (`docs/01-domain-model.md` §8): `▲` up, `▼` down, `·` flat.
#[must_use]
pub fn tick_dir_glyph(dir: TickDir) -> char {
    match dir {
        TickDir::Up => '▲',
        TickDir::Down => '▼',
        TickDir::Flat => '·',
    }
}

/// The color-independent sign for a signed value: `−` when negative, `+`
/// otherwise (`docs/05-views-and-ux.md` §7).
#[must_use]
pub fn pnl_sign_char(is_negative: bool) -> char {
    if is_negative { '−' } else { '+' }
}

/// The at-spot marker as a styled [`Span`] — the marker text plus the strike-column
/// style. Under `NO_COLOR` the style carries no color but the `◀ATM` text remains.
#[must_use]
pub fn strike_relation_marker_span(rel: StrikeRelation, theme: Theme) -> Span<'static> {
    Span::styled(
        strike_relation_marker(rel).to_owned(),
        theme.strike_relation_style(rel),
    )
}

/// A price-direction glyph as a styled [`Span`]. Under `NO_COLOR` the style carries
/// no color but the `▲`/`▼`/`·` glyph remains.
#[must_use]
pub fn tick_dir_span(dir: TickDir, theme: Theme) -> Span<'static> {
    Span::styled(tick_dir_glyph(dir).to_string(), theme.tick_dir_style(dir))
}

/// A P&L sign glyph as a styled [`Span`]. Under `NO_COLOR` the style carries no
/// color but the `+`/`−` sign remains.
#[must_use]
pub fn pnl_sign_span(is_negative: bool, theme: Theme) -> Span<'static> {
    Span::styled(
        pnl_sign_char(is_negative).to_string(),
        theme.pnl_style(is_negative),
    )
}

// ===========================================================================
// Responsive chain columns + too-small guard.
// ===========================================================================

/// A droppable analytic column of the chain matrix
/// (`docs/05-views-and-ux.md` §8). Δ is always shown; the rest drop as width
/// shrinks in [`GREEK_DROP_ORDER`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum GreekColumn {
    /// Delta — the primary Greek, never dropped.
    Delta,
    /// Gamma — dropped first as width shrinks.
    Gamma,
    /// Theta — dropped last.
    Theta,
    /// Vega — dropped second.
    Vega,
}

/// The order optional Greek columns are **dropped** as terminal width shrinks
/// (`docs/05-views-and-ux.md` §8): `Γ` first, then `ν`, then `Θ`. Δ is never in
/// this list — it is always shown.
pub const GREEK_DROP_ORDER: [GreekColumn; 3] =
    [GreekColumn::Gamma, GreekColumn::Vega, GreekColumn::Theta];

/// Which optional Greek columns are visible for a given number of extra column
/// slots that fit (`docs/05-views-and-ux.md` §8). Δ is always visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GreekColumns {
    /// Delta — always `true`.
    pub delta: bool,
    /// Gamma — shown only when there is width for all three optional columns.
    pub gamma: bool,
    /// Vega — shown when there is width for at least two.
    pub vega: bool,
    /// Theta — shown when there is width for at least one (dropped last).
    pub theta: bool,
}

/// Resolve which Greek columns are visible given `extra_slots`, the number of
/// optional Greek columns that fit after the always-present price/IV/Δ columns
/// (`docs/05-views-and-ux.md` §8).
///
/// Encodes the drop **order** `Γ → ν → Θ`: `Θ` is dropped last (retained first),
/// then `ν`, then `Γ`. So `0` slots shows Δ only; `1` adds `Θ`; `2` adds `ν`; `3`
/// adds `Γ`. The actual per-column widths and the render live in the chain matrix
/// (#18); this fixes only the policy.
#[must_use]
pub fn greek_columns_for_slots(extra_slots: usize) -> GreekColumns {
    GreekColumns {
        delta: true,
        theta: extra_slots >= 1,
        vega: extra_slots >= 2,
        gamma: extra_slots >= 3,
    }
}

/// The minimum terminal width below which any screen shows the "widen the terminal"
/// state instead of a body (`docs/05-views-and-ux.md` §8).
pub const MIN_WIDTH: u16 = 40;
/// The minimum terminal height below which any screen shows the "widen the
/// terminal" state instead of a body (`docs/05-views-and-ux.md` §8).
pub const MIN_HEIGHT: u16 = 8;

/// Whether `area` is below the minimum renderable size
/// (`docs/05-views-and-ux.md` §8). When true, [`render`](crate::render) shows the
/// cross-screen "widen the terminal" hint rather than a corrupt layout.
#[must_use]
pub fn is_too_small(area: Rect) -> bool {
    area.width < MIN_WIDTH || area.height < MIN_HEIGHT
}

/// Draw the cross-screen "widen the terminal" state (`docs/05-views-and-ux.md`
/// §8) — the first-class too-small render, never a corrupt layout. Legible without
/// color (text + explicit size), so it survives `NO_COLOR`.
pub fn draw_too_small(frame: &mut Frame, area: Rect, theme: Theme) {
    let text = Text::from(vec![
        Line::from(Span::styled("widen the terminal", theme.warning())),
        Line::from(Span::styled(
            format!(
                "have {}x{}, need at least {MIN_WIDTH}x{MIN_HEIGHT}",
                area.width, area.height
            ),
            theme.dim(),
        )),
    ]);
    frame.render_widget(Paragraph::new(text).alignment(Alignment::Center), area);
}

// ===========================================================================
// Status bar, keybar/hint, and the modal help overlay.
// ===========================================================================

/// The braille spinner frames, cycled by the tick counter — the only motion the
/// status bar shows (`docs/05-views-and-ux.md` §7: motion reserved for the loading
/// spinner and the replay play-head).
const SPINNER_FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];

/// The spinner frame for a tick count — a pure projection of [`App::tick_count`],
/// never a wall-clock read. Shared with the chain screen's loading state (#18),
/// so the body spinner and the status-bar spinner advance in lock-step.
#[must_use]
pub(crate) fn spinner_frame(tick: u64) -> char {
    let len = SPINNER_FRAMES.len() as u64;
    let idx = (tick % len) as usize;
    SPINNER_FRAMES.get(idx).copied().unwrap_or(' ')
}

/// The visible placeholder a neutralized control/introducer scalar is replaced
/// with, so a stripped byte reads as a deliberate "removed" glyph rather than
/// vanishing silently (`docs/SECURITY.md` §6.4). `U+FFFD` sits above the C1 range
/// and is a single display column, so the placeholder can neither re-introduce an
/// unsafe byte nor widen a cell.
pub(crate) const SANITIZE_PLACEHOLDER: char = '\u{FFFD}';

/// Whether `c` is a terminal-unsafe control scalar: a **C0** control
/// (`0x00..=0x1F`, including `TAB`/`LF`/`CR` and the `ESC` `0x1B` introducer),
/// `DEL` (`0x7F`), or a **C1** control (`0x80..=0x9F`, including the 8-bit `CSI`
/// `0x9B` / `OSC` `0x9D` / `DCS` `0x90` introducers).
///
/// Equivalent to [`char::is_control`], but spelled out over explicit code-point
/// ranges so the escape-hygiene coverage is auditable directly against
/// `docs/SECURITY.md` §6.4.
#[must_use]
fn is_unsafe_control(c: char) -> bool {
    let cp = c as u32;
    cp < 0x20 || cp == 0x7f || (0x80..=0x9f).contains(&cp)
}

/// Neutralize a venue- or user-controlled string for the render edge
/// (`docs/SECURITY.md` §6.4 terminal escape-sequence hygiene): every C0/C1 control
/// and every escape introducer (`ESC`/`CSI`/`OSC`/`DCS`, 7-bit **and** 8-bit) is
/// replaced with a visible [`SANITIZE_PLACEHOLDER`], so a hostile instrument name,
/// symbol, or venue error string renders as **inert visible text** — never a
/// cursor move, a title change, a clipboard write (`OSC 52`), or a torn matrix
/// layout (a `TAB`/`LF` cannot break a row).
///
/// Because a terminal only enters escape-processing on an **introducer** byte —
/// all of which are C0/C1 controls — replacing every introducer leaves the
/// residual bytes as inert printable text; the sanitizer therefore neutralizes a
/// whole `ESC`-prefixed sequence (`\x1b]52;c;…\x07`, `\x1b[2J`, …) without parsing
/// it. It is a **pure** helper, unit- and property-testable independent of a
/// rendered frame, and is the single sanitizer every venue-string render edge
/// routes through (the status bar, keybar/hint, and the chain matrix's
/// title/symbol/expiry/message).
///
/// It does **not** touch ChainView's own styling or the `NO_COLOR` markers
/// (`docs/SECURITY.md` §6.4) — those bytes are not venue-controlled.
#[must_use]
pub(crate) fn sanitize(raw: &str) -> String {
    raw.chars()
        .map(|c| {
            if is_unsafe_control(c) {
                SANITIZE_PLACEHOLDER
            } else {
                c
            }
        })
        .collect()
}

/// The health badge glyph, exhaustive over [`StreamHealth`]. Paired with the text
/// so the badge survives a monochrome terminal.
#[must_use]
fn health_glyph(health: &StreamHealth) -> char {
    match health {
        StreamHealth::Live => '●',
        StreamHealth::Stale { .. } => '◐',
        StreamHealth::Reconnecting { .. } => '↻',
    }
}

/// The health badge text, exhaustive over [`StreamHealth`].
#[must_use]
fn health_text(health: &StreamHealth) -> String {
    match health {
        StreamHealth::Live => "live".to_owned(),
        StreamHealth::Stale { .. } => "stale".to_owned(),
        StreamHealth::Reconnecting { attempt } => format!("reconnecting ({attempt})"),
    }
}

/// The stream-health badge as a styled [`Span`] — glyph plus text, so the state is
/// legible without color.
#[must_use]
pub fn health_span(health: &StreamHealth, theme: Theme) -> Span<'static> {
    Span::styled(
        format!("{} {}", health_glyph(health), health_text(health)),
        theme.health_style(health),
    )
}

/// Whether the live view is in a motion state (loading or reconnecting), which
/// animates the spinner.
#[must_use]
fn live_in_motion(live: &LiveState) -> bool {
    matches!(live.load, ScreenLoad::Loading)
        || matches!(live.source.health, StreamHealth::Reconnecting { .. })
}

/// The replay playback badge for the status bar, or `None` when there is nothing to
/// show (a loading/failed bundle that is not playing). Distinct from the loading
/// spinner (which is reserved for [`BundleLoad::Loading`]) so "playing" and "loading"
/// never share a glyph: `▶ ×N` while [`Playback::Playing`] at speed `N`, and `⏸`
/// while [`Playback::Paused`] over a **loaded** bundle. The `▶`/`⏸`/`×` are text
/// glyphs, so the badge survives a monochrome terminal (`NO_COLOR`).
#[must_use]
fn playback_badge(replay: &ReplayState) -> Option<String> {
    match replay.play {
        Playback::Playing { speed } => Some(format!("▶ ×{}", speed.multiplier())),
        Playback::Paused => match replay.bundle {
            BundleLoad::Ready(_) => Some("⏸".to_owned()),
            // Nothing to pause yet: the loading spinner / error body carries the state.
            BundleLoad::Loading | BundleLoad::Error { .. } => None,
        },
    }
}

/// A short label for the loaded bundle directory (its final path component). Shared
/// with the replay screen's loading body (`src/ui/replay.rs`).
#[must_use]
pub(crate) fn run_label(replay: &ReplayState) -> String {
    replay
        .dir
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_else(|| replay.dir.to_string_lossy().into_owned())
}

/// Draw the always-truthful one-line status bar (`docs/05-views-and-ux.md` §8):
/// provider / health / clock / mode in Live, run id / mode in Replay. The spinner
/// advances off [`App::tick_count`], never a wall clock, so the draw stays pure.
pub fn draw_status(app: &App, frame: &mut Frame, area: Rect, theme: Theme) {
    let mut spans = vec![Span::styled("chainview", theme.accent()), Span::raw("  ")];
    match &app.mode {
        Mode::Live(live) => {
            spans.push(Span::styled("live", theme.dim()));
            spans.push(Span::raw("  "));
            spans.push(Span::raw(sanitize(&live.store.chain().symbol)));
            spans.push(Span::raw("  "));
            spans.push(Span::raw(sanitize(live.source.provider.as_str())));
            spans.push(Span::raw("  "));
            spans.push(health_span(&live.source.health, theme));
            if live_in_motion(live) {
                spans.push(Span::raw(" "));
                spans.push(Span::styled(
                    spinner_frame(app.tick_count).to_string(),
                    theme.accent(),
                ));
            }
        }
        Mode::Replay(replay) => {
            spans.push(Span::styled("replay", theme.dim()));
            spans.push(Span::raw("  "));
            spans.push(Span::raw(sanitize(&run_label(replay))));
            // The spinner animates ONLY while the bundle is loading (the §7 loading
            // idiom); playback carries a distinct `▶ ×N` / `⏸` badge below, so the
            // two states never share a glyph.
            if matches!(replay.bundle, BundleLoad::Loading) {
                spans.push(Span::raw(" "));
                spans.push(Span::styled(
                    spinner_frame(app.tick_count).to_string(),
                    theme.accent(),
                ));
            }
            if let Some(badge) = playback_badge(replay) {
                spans.push(Span::raw("  "));
                spans.push(Span::styled(badge, theme.accent()));
            }
        }
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// Append a `{slot} {name}` keybar entry, marking an unavailable screen with
/// parentheses + a dim style — a color-independent signal.
fn push_slot(
    spans: &mut Vec<Span<'static>>,
    slot: u8,
    name: &'static str,
    reachable: bool,
    theme: Theme,
) {
    if reachable {
        spans.push(Span::styled(format!("{slot} "), theme.accent()));
        spans.push(Span::raw(format!("{name}  ")));
    } else {
        spans.push(Span::styled(format!("{slot} ({name})  "), theme.dim()));
    }
}

/// Build the generated keybar line from the map's screen slots for the active mode,
/// dimming (and parenthesizing) unavailable screens.
#[must_use]
fn keybar_line(app: &App, theme: Theme) -> Line<'static> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    match &app.mode {
        Mode::Live(live) => {
            for (slot, screen) in [
                (1u8, LiveScreen::Chain),
                (2, LiveScreen::Depth),
                (3, LiveScreen::Surface),
                (4, LiveScreen::Payoff),
            ] {
                push_slot(
                    &mut spans,
                    slot,
                    live_screen_name(screen),
                    live.screen_reachable(screen),
                    theme,
                );
            }
        }
        Mode::Replay(_) => {
            for (slot, screen) in [(1u8, ReplayScreen::Replay), (2, ReplayScreen::Payoff)] {
                push_slot(
                    &mut spans,
                    slot,
                    replay_screen_name(screen),
                    is_replay_screen_reachable(screen),
                    theme,
                );
            }
        }
    }
    spans.push(Span::styled("? help  ", theme.dim()));
    spans.push(Span::styled("q quit", theme.dim()));
    Line::from(spans)
}

/// Draw the one-line hint/keybar (`docs/05-views-and-ux.md` §8): the transient
/// status hint when present (an unavailable-screen flash), else the "close help"
/// note while the overlay is open, else the generated keybar. The transient hint
/// carries a `!` marker so it reads without color.
pub fn draw_hint(app: &App, frame: &mut Frame, area: Rect, theme: Theme) {
    let line = if let Some(hint) = &app.status_hint {
        Line::from(vec![
            Span::styled("! ", theme.warning()),
            Span::styled(sanitize(hint), theme.warning()),
        ])
    } else if app.help_open {
        Line::from(Span::styled("?/Esc  close help", theme.dim()))
    } else {
        keybar_line(app, theme)
    };
    frame.render_widget(Paragraph::new(line), area);
}

/// The outer width of the two-column help overlay box.
const HELP_WIDTH: u16 = 72;

/// The fixed label-column width inside a help row (keys on the left, help on the
/// right); terse help text (`src/app/keymap.rs`) fits the remaining column width on
/// an 80-column terminal without truncation.
const HELP_LABEL_WIDTH: usize = 10;

/// One rendered section for a help column: the accent title, then one row per
/// binding, or — for a **deferred** screen with no bindings yet — a "not available"
/// note so every screen is still listed (`docs/05-views-and-ux.md` §2, fix SF-04).
fn render_section(
    lines: &mut Vec<Line<'static>>,
    title: &str,
    bindings: &[&'static Binding],
    theme: Theme,
) {
    lines.push(Line::from(Span::styled(title.to_owned(), theme.accent())));
    if bindings.is_empty() {
        lines.push(Line::from(Span::styled(
            "  not available yet".to_owned(),
            theme.dim(),
        )));
        return;
    }
    for binding in bindings {
        let mut spans = vec![
            Span::styled(
                format!(" {:<HELP_LABEL_WIDTH$} ", binding.keys_label),
                theme.accent(),
            ),
            Span::raw(binding.help.to_owned()),
        ];
        // A deferred key resolves and is documented, but its body is not wired yet:
        // append a dim `(<version>)` suffix so `?` honestly shows it is not live.
        // The parenthesized text carries the signal without relying on color.
        if let Some(version) = binding.deferred {
            spans.push(Span::styled(format!(" ({version})"), theme.dim()));
        }
        lines.push(Line::from(spans));
    }
}

/// The estimated rendered height of a section (title + a row per binding, or the
/// single deferred note), used only to balance the two columns.
#[must_use]
fn section_height(bindings: &[&'static Binding]) -> usize {
    bindings.len().max(1) + 1
}

/// Render a column's sections into lines, with a blank separator between sections.
#[must_use]
fn render_column(
    sections: &[(&'static str, Vec<&'static Binding>)],
    theme: Theme,
) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = Vec::new();
    for (index, (title, bindings)) in sections.iter().enumerate() {
        if index > 0 {
            lines.push(Line::from(""));
        }
        render_section(&mut lines, title, bindings, theme);
    }
    lines
}

/// Draw the modal help overlay (`docs/05-views-and-ux.md` §3, §8): every screen
/// and its keys, grouped by context, generated **from the application-layer map**
/// ([`help_sections`](crate::app::keymap)). Laid out in **two columns** (balanced by
/// height) so every documented key is visible on a standard 80x24 terminal without
/// clipping (fix SF-01); deferred screens still appear with a "not available" note
/// (fix SF-04). Floats over the body with a [`Clear`] behind it. While open,
/// dispatch honors only `?`/`Esc` (handled in `App::dispatch_key_global`); no
/// background action fires.
pub fn draw_help_overlay(app: &App, frame: &mut Frame, area: Rect, theme: Theme) {
    // Balance the sections across two columns (assign each to the shorter column),
    // so the overlay is about half as tall as a single column and fits 80x24.
    let mut left: Vec<(&'static str, Vec<&'static Binding>)> = Vec::new();
    let mut right: Vec<(&'static str, Vec<&'static Binding>)> = Vec::new();
    let mut left_h = 0usize;
    let mut right_h = 0usize;
    for (title, bindings) in help_sections(&app.mode) {
        let height = section_height(&bindings);
        if left_h <= right_h {
            left_h += height;
            left.push((title, bindings));
        } else {
            right_h += height;
            right.push((title, bindings));
        }
    }
    let left_lines = render_column(&left, theme);
    let right_lines = render_column(&right, theme);

    // The overlay height is the taller column plus the two border rows; cap so the
    // `+ 2` cannot overflow `u16` (no unchecked add, no banned `saturating_*`).
    // `centered_rect` clamps the result to `area` regardless.
    let content = left_lines.len().max(right_lines.len());
    let capped = content.min(usize::from(u16::MAX) - 2);
    let height = capped as u16 + 2;
    let overlay = super::centered_rect(area, HELP_WIDTH, height);

    frame.render_widget(Clear, overlay);
    let block = Block::bordered().title("Help  —  ?/Esc to close");
    let inner = block.inner(overlay);
    frame.render_widget(block, overlay);
    let [left_area, right_area] =
        Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).areas(inner);
    frame.render_widget(Paragraph::new(Text::from(left_lines)), left_area);
    frame.render_widget(Paragraph::new(Text::from(right_lines)), right_area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::tests_support::{live_app_caps, live_app_on, ready_replay_app, replay_app_on};
    use crate::app::{LiveScreen, ReplayScreen, ScreenLoad};
    use crate::event::{AppEvent, ReplayControl};
    use crate::providers::{ChainCapability, GreeksCapability, ProviderCapabilities};
    use crate::ui::view::ViewState;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use proptest::prelude::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use ratatui::layout::Rect;

    #[track_caller]
    fn terminal(width: u16, height: u16) -> Terminal<TestBackend> {
        match Terminal::new(TestBackend::new(width, height)) {
            Ok(t) => t,
            Err(e) => panic!("TestBackend construction failed: {e}"),
        }
    }

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

    /// The full-frame text as a single string (row-major), for overlay assertions.
    #[track_caller]
    fn rendered_frame(app: &App, width: u16, height: u16) -> String {
        let mut view = ViewState::new();
        view.sync(app);
        let mut term = terminal(width, height);
        match term.draw(|frame| crate::render(app, &view, frame)) {
            Ok(_) => {}
            Err(e) => panic!("render failed: {e}"),
        }
        term.backend()
            .buffer()
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect()
    }

    // --- NO_COLOR strips color but keeps markers -----------------------------

    #[test]
    fn test_theme_no_color_strikes_color_but_keeps_at_spot_marker() {
        let theme = Theme::resolve(ThemeChoice::Auto, true);
        let span = strike_relation_marker_span(StrikeRelation::AtSpot, theme);
        assert!(
            span.style.fg.is_none() && span.style.bg.is_none(),
            "NO_COLOR must not set a foreground/background color",
        );
        assert!(
            span.content.contains(AT_SPOT_MARKER),
            "the ◀ATM marker must survive NO_COLOR",
        );
    }

    #[test]
    fn test_theme_no_color_keeps_tick_and_pnl_markers() {
        let theme = Theme::resolve(ThemeChoice::Dark, true);
        let up = tick_dir_span(TickDir::Up, theme);
        assert!(up.style.fg.is_none() && up.style.bg.is_none());
        assert!(up.content.contains('▲'));
        let down = tick_dir_span(TickDir::Down, theme);
        assert!(down.content.contains('▼'));
        let neg = pnl_sign_span(true, theme);
        assert!(neg.style.fg.is_none() && neg.style.bg.is_none());
        assert!(neg.content.contains('−'));
        let pos = pnl_sign_span(false, theme);
        assert!(pos.content.contains('+'));
    }

    #[test]
    fn test_theme_with_color_sets_foreground_and_keeps_markers() {
        let theme = Theme::resolve(ThemeChoice::Auto, false);
        let span = tick_dir_span(TickDir::Up, theme);
        assert!(span.style.fg.is_some(), "color mode sets a foreground");
        assert!(
            span.content.contains('▲'),
            "the glyph is present with color too"
        );
    }

    #[test]
    fn test_theme_no_color_health_badge_keeps_glyph_and_text() {
        let theme = Theme::resolve(ThemeChoice::Auto, true);
        let span = health_span(&StreamHealth::Live, theme);
        assert!(span.style.fg.is_none() && span.style.bg.is_none());
        assert!(span.content.contains('●') && span.content.contains("live"));
    }

    // --- Theme resolution ----------------------------------------------------

    #[test]
    fn test_theme_resolve_maps_choice_to_variant() {
        assert_eq!(
            Theme::resolve(ThemeChoice::Auto, false).variant,
            ThemeVariant::Dark
        );
        assert_eq!(
            Theme::resolve(ThemeChoice::Dark, false).variant,
            ThemeVariant::Dark
        );
        assert_eq!(
            Theme::resolve(ThemeChoice::Light, false).variant,
            ThemeVariant::Light
        );
    }

    // --- StrikeRelation K/S bucket -------------------------------------------

    #[track_caller]
    fn pos(v: f64) -> Positive {
        match Positive::new(v) {
            Ok(p) => p,
            Err(e) => panic!("invalid test positive {v}: {e}"),
        }
    }

    #[test]
    fn test_strike_relation_classify_buckets_below_at_above() {
        let spot = pos(60_000.0);
        assert_eq!(
            StrikeRelation::classify(pos(50_000.0), spot),
            StrikeRelation::BelowSpot
        );
        assert_eq!(
            StrikeRelation::classify(pos(60_000.0), spot),
            StrikeRelation::AtSpot
        );
        assert_eq!(
            StrikeRelation::classify(pos(70_000.0), spot),
            StrikeRelation::AboveSpot
        );
        // Inside the 0.5% band is still at-spot.
        assert_eq!(
            StrikeRelation::classify(pos(60_100.0), spot),
            StrikeRelation::AtSpot
        );
    }

    #[test]
    fn test_strike_relation_classify_zero_spot_is_at_spot() {
        assert_eq!(
            StrikeRelation::classify(pos(60_000.0), pos(0.0)),
            StrikeRelation::AtSpot
        );
    }

    // --- Responsive column-drop order ----------------------------------------

    #[test]
    fn test_greek_columns_for_slots_drop_order_gamma_vega_theta() {
        assert_eq!(
            greek_columns_for_slots(0),
            GreekColumns {
                delta: true,
                gamma: false,
                vega: false,
                theta: false
            },
        );
        // Theta retained first (dropped last).
        assert!(greek_columns_for_slots(1).theta);
        assert!(!greek_columns_for_slots(1).vega);
        // Vega second.
        assert!(greek_columns_for_slots(2).vega);
        assert!(!greek_columns_for_slots(2).gamma);
        // Gamma last (dropped first).
        assert!(greek_columns_for_slots(3).gamma);
        assert_eq!(GREEK_DROP_ORDER[0], GreekColumn::Gamma);
    }

    // --- Too-small guard ------------------------------------------------------

    #[test]
    fn test_is_too_small_below_minimum() {
        assert!(is_too_small(Rect::new(0, 0, 30, 24)));
        assert!(is_too_small(Rect::new(0, 0, 80, 4)));
        assert!(!is_too_small(Rect::new(0, 0, 80, 24)));
        assert!(!is_too_small(Rect::new(0, 0, MIN_WIDTH, MIN_HEIGHT)));
    }

    #[test]
    fn test_draw_too_small_renders_widen_hint() {
        let theme = Theme::resolve(ThemeChoice::Auto, false);
        let mut term = terminal(30, 6);
        match term.draw(|frame| draw_too_small(frame, frame.area(), theme)) {
            Ok(_) => {}
            Err(e) => panic!("draw failed: {e}"),
        }
        let buffer = term.backend().buffer().clone();
        let rendered: String = buffer
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect();
        assert!(
            rendered.contains("widen the terminal"),
            "must show the widen hint"
        );
    }

    // --- Status bar / keybar / help overlay render without panic -------------

    #[test]
    fn test_draw_status_and_hint_render_without_panic() {
        let theme = Theme::resolve(ThemeChoice::Auto, false);
        let app = live_app_on(LiveScreen::Chain, ScreenLoad::Loading, false);
        let mut term = terminal(80, 24);
        match term.draw(|frame| {
            let area = frame.area();
            draw_status(&app, frame, Rect::new(0, 0, area.width, 1), theme);
            draw_hint(
                &app,
                frame,
                Rect::new(0, area.height - 1, area.width, 1),
                theme,
            );
        }) {
            Ok(_) => {}
            Err(e) => panic!("draw failed: {e}"),
        }
    }

    #[test]
    fn test_status_bar_playback_badge_shows_speed_and_pause() {
        // SF-02: the replay status bar carries a distinct, NO_COLOR-safe playback
        // badge — `▶ ×N` while playing, `⏸` while paused over a loaded bundle —
        // never reusing the loading spinner glyph for playback.
        let (mut app, _rx) = ready_replay_app(6);
        // Space (play) then `+` (faster) → Playing ×2.
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        app.on_event(AppEvent::ReplayControl(ReplayControl::SpeedFaster));
        let playing = rendered_frame(&app, 80, 24);
        assert!(playing.contains("▶ ×2"), "playing shows ▶ ×2: {playing:?}");
        // Space again → paused; a loaded bundle shows the pause badge, no play badge.
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        let paused = rendered_frame(&app, 80, 24);
        assert!(
            paused.contains('⏸'),
            "paused-with-bundle shows ⏸: {paused:?}"
        );
        assert!(!paused.contains("▶ ×"), "paused shows no play badge");
    }

    #[test]
    fn test_status_bar_loading_shows_spinner_not_playback_badge() {
        // While the bundle is still loading, the spinner animates and no playback
        // badge appears (paused + not-yet-loaded → no `⏸`).
        let app = replay_app_on(ReplayScreen::Replay, false);
        let text = rendered_frame(&app, 80, 24);
        assert!(text.contains('⠋'), "loading shows the spinner (tick 0)");
        assert!(
            !text.contains('⏸'),
            "an unloaded bundle shows no pause badge"
        );
        assert!(
            !text.contains("▶ ×"),
            "an unloaded bundle shows no play badge"
        );
    }

    #[test]
    fn test_draw_help_overlay_renders_bindings_without_panic() {
        let theme = Theme::resolve(ThemeChoice::Auto, false);
        let app = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, true);
        let mut term = terminal(100, 40);
        match term.draw(|frame| draw_help_overlay(&app, frame, frame.area(), theme)) {
            Ok(_) => {}
            Err(e) => panic!("draw failed: {e}"),
        }
    }

    #[test]
    fn test_help_overlay_fits_80x24_shows_every_section() {
        // On the standard trader terminal the two-column overlay must show keys from
        // EVERY section — including the last (Payoff), which clipped off the bottom in
        // the old single-column layout (fix SF-01).
        let app = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, true);
        let text = rendered_frame(&app, 80, 24);
        assert!(text.contains("Move strike"), "a Chain key is visible");
        assert!(
            text.contains("Cycle axis"),
            "a Surface key is visible (SF-04: relabeled from \"Greek axis\")",
        );
        assert!(
            text.contains("Commit strategy"),
            "a Payoff key (the last section) is visible on 80x24, not clipped",
        );
    }

    #[test]
    fn test_help_overlay_marks_deferred_keys_with_version_suffix() {
        // A key that resolves and is documented but is not yet wired shows a dim
        // "(vX)" suffix in the overlay, so `?` honestly signals it is not live yet
        // (the reviewed dead-key-trap fix). The chain SwitchExpiry / underlying / Drill
        // keys defer with "(soon)"; the Depth scroll key is wired now (#48), so it no
        // longer carries a marker. (The narrow 72-col overlay clips the closing paren
        // of a marker on a long help line, so match the opening `(soon`.)
        let app = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, true);
        let text = rendered_frame(&app, 100, 40);
        assert!(
            text.contains("(soon"),
            "a deferred key shows its marker in the overlay",
        );
    }

    #[test]
    fn test_help_overlay_lists_live_replay_payoff_section() {
        // Every screen is listed in the overlay (§2): the replay Payoff panel is live
        // from v0.5 (#49), so its section carries the scrub/playback keys it supports
        // (the recovery for "flat at this step" is scrubbing to an open step) rather
        // than a "not available" note.
        let app = replay_app_on(ReplayScreen::Payoff, true);
        let text = rendered_frame(&app, 100, 40);
        assert!(
            text.contains("Payoff"),
            "the reachable Payoff screen is listed"
        );
        assert!(
            text.contains("Step forward"),
            "the Payoff section lists its scrub keys (no dead 'not available' note)",
        );
        assert!(
            !text.contains("not available"),
            "no replay overlay section is a dead 'not available' note",
        );
    }

    // --- Reachability skip/hint via dispatch (capability-driven) --------------

    fn caps_no_depth() -> ProviderCapabilities {
        ProviderCapabilities::builder()
            .chain(ChainCapability::Assemble)
            .depth(false)
            .greeks(GreeksCapability::Provided)
            .build()
    }

    #[test]
    fn test_dispatch_unavailable_number_key_flashes_hint_and_keeps_screen() {
        // A provider without depth: pressing `2` (Depth) must not switch and must
        // flash a keybar hint naming the screen.
        let mut app = live_app_caps(caps_no_depth());
        let before = match &app.mode {
            Mode::Live(live) => live.screen,
            Mode::Replay(_) => panic!("expected a live app"),
        };
        let _ = app.dispatch_key_global(press(KeyCode::Char('2')));
        let after = match &app.mode {
            Mode::Live(live) => live.screen,
            Mode::Replay(_) => panic!("expected a live app"),
        };
        assert_eq!(before, after, "an unavailable number key must not switch");
        match &app.status_hint {
            Some(hint) => assert!(hint.contains("Depth"), "hint names the screen: {hint}"),
            None => panic!("an unavailable number key must flash a hint"),
        }
    }

    #[test]
    fn test_dispatch_available_number_key_switches_and_clears_hint() {
        let mut app = live_app_caps(caps_no_depth());
        // `3` = Surface (Greeks present) is reachable → switch.
        let _ = app.dispatch_key_global(press(KeyCode::Char('3')));
        match &app.mode {
            Mode::Live(live) => assert_eq!(live.screen, LiveScreen::Surface),
            Mode::Replay(_) => panic!("expected a live app"),
        }
        assert!(app.status_hint.is_none(), "a valid switch leaves no hint");
    }

    #[test]
    fn test_dispatch_tab_skips_unavailable_screen() {
        // Depth is unavailable (no depth capability), so Tab from Chain skips it and
        // lands on the next reachable screen (Surface), never on the Depth body.
        let mut app = live_app_caps(caps_no_depth());
        let _ = app.dispatch_key_global(press(KeyCode::Tab));
        match &app.mode {
            Mode::Live(live) => assert_eq!(
                live.screen,
                LiveScreen::Surface,
                "Tab must skip the unavailable Depth screen",
            ),
            Mode::Replay(_) => panic!("expected a live app"),
        }
    }

    // --- Modal help precedence: only ?/Esc act while open --------------------

    #[test]
    fn test_dispatch_modal_help_honors_only_toggle_keys() {
        let mut app = live_app_caps(caps_no_depth());
        // Open help.
        let _ = app.dispatch_key_global(press(KeyCode::Char('?')));
        assert!(app.help_open);
        let screen_before = match &app.mode {
            Mode::Live(live) => live.screen,
            Mode::Replay(_) => panic!("expected a live app"),
        };
        // A screen-switch key while help is open is swallowed — no switch, no hint,
        // help stays open.
        let _ = app.dispatch_key_global(press(KeyCode::Char('3')));
        assert!(app.help_open, "a swallowed key leaves the overlay open");
        assert!(
            app.status_hint.is_none(),
            "no background hint fires behind help"
        );
        match &app.mode {
            Mode::Live(live) => assert_eq!(
                live.screen, screen_before,
                "no background screen switch fires behind the overlay",
            ),
            Mode::Replay(_) => panic!("expected a live app"),
        }
        // A quit key while help is open is also swallowed (only ?/Esc act).
        let _ = app.dispatch_key_global(press(KeyCode::Char('q')));
        assert!(
            !app.should_quit,
            "q does not quit while the overlay is modal"
        );
        // Esc closes it.
        let _ = app.dispatch_key_global(press(KeyCode::Esc));
        assert!(!app.help_open, "Esc closes the overlay");
    }

    // --- The cross-screen too-small guard is wired into render ----------------

    #[test]
    fn test_render_below_min_size_shows_widen_hint() {
        // The full render path shows the cross-screen "widen the terminal" state
        // below the minimum size instead of a screen body.
        let app = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, false);
        let mut view = ViewState::new();
        view.sync(&app);
        let mut term = terminal(30, 6);
        match term.draw(|frame| crate::render(&app, &view, frame)) {
            Ok(_) => {}
            Err(e) => panic!("render failed: {e}"),
        }
        let buffer = term.backend().buffer().clone();
        let rendered: String = buffer
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect();
        assert!(
            rendered.contains("widen the terminal"),
            "render must show the widen hint below the minimum size",
        );
    }

    // --- Escape-sequence sanitizer (docs/SECURITY.md §6.4) -------------------

    #[test]
    fn test_sanitize_replaces_c0_controls_including_esc_tab_newline() {
        // Every C0 control (incl. ESC 0x1B, TAB, LF, CR, BEL) is replaced with the
        // visible placeholder, never left to reach the terminal — so a TAB/LF in an
        // instrument name cannot break the matrix layout.
        let raw = "a\u{0}b\tc\nd\re\u{7}f\u{1b}g";
        let out = sanitize(raw);
        assert!(!out.contains('\u{1b}'), "no ESC survives");
        assert!(!out.contains('\t') && !out.contains('\n') && !out.contains('\r'));
        assert!(!out.contains('\u{7}'), "no BEL survives");
        assert_eq!(
            out.chars()
                .filter(char::is_ascii_alphabetic)
                .collect::<String>(),
            "abcdefg",
            "the printable letters survive, in order",
        );
        assert_eq!(
            out.chars().filter(|&c| c == SANITIZE_PLACEHOLDER).count(),
            6,
            "each of the six C0 controls becomes one placeholder",
        );
    }

    #[test]
    fn test_sanitize_replaces_c1_controls_including_8bit_introducers() {
        // The 8-bit C1 introducers CSI (0x9B) / OSC (0x9D) / DCS (0x90), and the C1
        // range generally, are replaced — a raw 8-bit escape is as dangerous as ESC.
        let raw = "x\u{9b}\u{9d}\u{90}\u{85}y";
        let out = sanitize(raw);
        for c in ['\u{9b}', '\u{9d}', '\u{90}', '\u{85}'] {
            assert!(!out.contains(c), "no C1 control {:#x} survives", c as u32);
        }
        assert_eq!(
            out.chars().filter(|&c| c == SANITIZE_PLACEHOLDER).count(),
            4,
        );
        assert!(out.starts_with('x') && out.ends_with('y'));
    }

    #[test]
    fn test_sanitize_neutralizes_osc_csi_dcs_sequences_to_inert_text() {
        // An OSC clipboard-write, a CSI clear-screen, and a DCS payload each render
        // as inert visible text: the introducer is gone, so the residual params are
        // printable and cause no terminal side effect.
        let raw = "\u{1b}]52;c;cHduZWQ=\u{7}\u{1b}[2J\u{1b}Pq#0;2\u{1b}\\";
        let out = sanitize(raw);
        assert!(!out.contains('\u{1b}'), "no ESC introducer survives");
        assert!(
            out.contains("52;c;cHduZWQ="),
            "the OSC params are inert text"
        );
        assert!(out.contains("[2J"), "the CSI params are inert text");
    }

    #[test]
    fn test_sanitize_preserves_printable_ascii_and_unicode_glyphs() {
        // Sanitize is identity for a normal venue string and for ChainView's own
        // glyphs/markers — the NO_COLOR/marker policy is unaffected (§6.4).
        let raw = "BTC-27JUN25-60000-C  ◀ATM ▲▼· — Γ Δ 49.22%";
        assert_eq!(sanitize(raw), raw);
    }

    #[test]
    fn test_is_unsafe_control_matches_c0_del_c1_ranges() {
        assert!(is_unsafe_control('\u{0}') && is_unsafe_control('\u{1b}'));
        assert!(is_unsafe_control('\u{7f}'), "DEL is unsafe");
        assert!(is_unsafe_control('\u{80}') && is_unsafe_control('\u{9f}'));
        assert!(!is_unsafe_control(' ') && !is_unsafe_control('A'));
        assert!(!is_unsafe_control('◀') && !is_unsafe_control('—'));
    }

    proptest! {
        /// The sanitizer invariant holds for ANY input: the output carries no C0
        /// control (0x00-0x1F), no DEL (0x7F), no C1 control (0x80-0x9F) — hence no
        /// ESC / 8-bit introducer — over an arbitrary Unicode string.
        #[test]
        fn prop_sanitize_output_has_no_control_or_introducer(
            chars in proptest::collection::vec(any::<char>(), 0..64),
        ) {
            let raw: String = chars.into_iter().collect();
            let out = sanitize(&raw);
            for c in out.chars() {
                let cp = c as u32;
                prop_assert!(cp >= 0x20, "C0 control 0x{cp:x} leaked");
                prop_assert!(cp != 0x7f, "DEL leaked");
                prop_assert!(!(0x80..=0x9f).contains(&cp), "C1 control 0x{cp:x} leaked");
            }
            for b in out.bytes() {
                prop_assert_ne!(b, 0x1b, "raw ESC byte leaked");
            }
        }

        /// The same invariant over ARBITRARY BYTES, lossy-decoded to a `str` — the
        /// shape a venue payload takes after UTF-8 decode.
        #[test]
        fn prop_sanitize_arbitrary_bytes_are_display_safe(
            bytes in proptest::collection::vec(any::<u8>(), 0..96),
        ) {
            let raw = String::from_utf8_lossy(&bytes);
            let out = sanitize(&raw);
            for c in out.chars() {
                let cp = c as u32;
                prop_assert!(
                    cp >= 0x20 && cp != 0x7f && !(0x80..=0x9f).contains(&cp),
                    "control 0x{cp:x} leaked",
                );
            }
        }
    }
}