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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
//! The application state machine and the synchronous event fan-in
//! (`docs/02-tui-architecture.md` §3, §4).
//!
//! [`App`] owns every piece of state the render loop reads and is a
//! `Live | Replay` [`Mode`] state machine — the two modes never run concurrently
//! in one process (§3). Screen identity is **mode-scoped** ([`LiveScreen`] /
//! [`ReplayScreen`]) so an out-of-mode pair (`Replay` + `Chain`) is
//! **unrepresentable** by the type system, not prevented by a runtime fallback,
//! and the render dispatch (#13) stays a total, wildcard-free match (§7).
//!
//! # The fan-in is synchronous and does no I/O
//!
//! [`App::on_event`] folds each [`AppEvent`] into state in **one exhaustive
//! match with no wildcard arm** and sets [`dirty`](App::dirty) on any mutation.
//! Handlers are pure and fast: one that needs I/O (reconnect, re-discover, seek
//! the bundle, subscribe a new expiry) emits a [`Command`] on the app's bounded
//! command channel via [`try_send`](tokio::sync::mpsc::Sender::try_send) — it
//! never performs the I/O inline and never `.await`s. `on_event` is **not**
//! `async` ([ADR-0005](https://github.com/joaquinbejar/ChainView/blob/main/docs/adr/0005-async-data-sync-render-split.md)).
//!
//! # Capability-driven reachability, never a `ProviderId` match
//!
//! A live screen is only ever set to a **reachable** value, and reachability is
//! read from the active provider's declared [`ProviderCapabilities`] — there is
//! **no `match` on [`ProviderId`]** anywhere here, so a built-in and an
//! externally registered provider are gated by identical code
//! (`docs/03-data-providers.md` §11.4,
//! [ADR-0006](https://github.com/joaquinbejar/ChainView/blob/main/docs/adr/0006-open-provider-extension.md)).
//! The `Tab`/`S-Tab` skip and the number-key status hint that build on the
//! [`is_screen_reachable`] helper land with the keybinding map and render loop
//! (#13/#14).
//!
//! # Scope of this issue (#9)
//!
//! This lands the state + fan-in skeleton. The render loop and draw dispatch
//! (#13), the keybinding map and help overlay (#14), the bounded coalescing
//! channel that carries `Market` (#10), the task supervisor (#11), and the
//! registry / app builder (#12) are separate issues. The [`ReplayState`]
//! internals (v0.3) and the [`PayoffBuilder`] internals (v0.2) are documented
//! stubs whose enum/struct **shapes** are fixed here so later work fills them in
//! without a breaking change.

use std::path::PathBuf;

use chrono::{DateTime, Utc};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use optionstratlib::chains::chain::OptionChain;
use optionstratlib::model::Position;
use optionstratlib::prelude::{BasicAxisTypes, Decimal, Positive};
use optionstratlib::visualization::GraphData;
use optionstratlib::{ExpirationDate, OptionStyle};
use tokio::sync::mpsc;

use crate::app::keymap::{GlobalCommand, KeyChord, resolve_global};
use crate::chain::quote_is_stale;
use crate::chain::{
    ChainFetch, ChainSnapshot, ChainStore, DepthLadder, DepthStore, ExpirySource, InstrumentKey,
    MarketUpdate, MergeOutcome, ProviderId, QuoteClocks, StreamHealth,
};
use crate::config::ThemeChoice;
use crate::event::{AppEvent, BundleLoadResult, Command, ReplayControl, SeekTo};
use crate::providers::{ChainCapability, GreeksCapability, ProviderCapabilities};
use crate::replay::{Fill, LoadedBundle, Playback, PlaybackSpeed, TimelineCursor};

mod bridge;
pub(crate) mod keymap;
mod payoff_build;
mod registry;
mod replay_load;
mod replay_payoff_build;
mod replay_view;
mod supervisor;
mod surface_build;

use replay_view::EquityGeometry;

pub use bridge::{BridgeSenders, COMMAND_CHANNEL_CAPACITY, CONTROL_CHANNEL_CAPACITY, EventBridge};
// `ProviderRegistry` stays crate-internal to `registry` (the UI never receives
// it, and external code composes through the builder), so only the builder entry
// points, the drivable resolution, and the supervised-subscription composition
// seam are re-exported here.
pub use registry::{
    ChainViewApp, ChainViewAppBuilder, ProviderSubscription, Resolved,
    spawn_supervised_subscription,
};
pub use replay_load::spawn_bundle_load;
pub use supervisor::{
    DEFAULT_JOIN_BUDGET, ExitCause, ExitReporter, FinalTeardown, GuardTeardown, SupervisedTask,
    Supervisor, TaskExit, TokioTask,
};

// ---------------------------------------------------------------------------
// App: the top-level state the render loop reads (§3).
// ---------------------------------------------------------------------------

/// How many [`AppEvent::Tick`]s a transient keybar hint stays visible before it
/// auto-decays (`docs/05-views-and-ux.md` §2). At the default 250 ms tick this is
/// ~2 s — a readable minimum so a hint never flashes for near-zero time; a key
/// press still clears it sooner.
pub const HINT_TICKS: u8 = 8;

/// The one-line keybar hint flashed when a replay reload (`R`) cannot be enqueued
/// because the command channel is full or closed — the data layer is gone
/// (`docs/05-views-and-ux.md` §6). On such a dropped send the bundle load screen is
/// **not** flipped to [`BundleLoad::Loading`] (which, with no load in flight, would
/// spin forever): the prior bundle state is kept and this hint is flashed instead.
const RELOAD_UNAVAILABLE_HINT: &str = "reload unavailable: data layer not responding";

/// All state the render loop reads, as a `Live | Replay` [`Mode`] state machine
/// (`docs/02-tui-architecture.md` §3).
///
/// Owned single-threaded by the synchronous render loop; every mutation happens
/// on an [`AppEvent`] through [`on_event`](App::on_event), never in `draw`.
#[derive(Debug)]
pub struct App {
    /// The active mode, which owns the mode-scoped active screen.
    pub mode: Mode,
    /// The color-theme selection. The **resolved** palette (variant + `NO_COLOR`
    /// fallback) is computed by the theme layer
    /// ([`Theme::resolve`](crate::ui::theme::Theme::resolve)) each frame from this
    /// selection and [`no_color`](App::no_color).
    pub theme: ThemeChoice,
    /// Whether color output is disabled (`NO_COLOR` / `--no-color` / config). Read
    /// by the theme layer so every color-encoded state falls back to markers +
    /// intensity only (`docs/05-views-and-ux.md` §7). Set by startup from
    /// [`Config::no_color`](crate::Config); defaults `false`.
    pub no_color: bool,
    /// The status-bar model (provider health, clock, mode). Its fields are
    /// populated by the render loop / status line (#13/#14); a documented stub
    /// here so [`App`] is constructible now.
    pub status: StatusLine,
    /// A monotonic tick counter, advanced on every [`AppEvent::Tick`], that drives
    /// the status-bar spinner/clock animation (`docs/05-views-and-ux.md` §7). Read
    /// purely in `draw` so the animation never reads a wall clock there; an idle
    /// tick advances it but does **not** set [`dirty`](App::dirty) (§8).
    pub tick_count: u64,
    /// The wall-clock instant of the most recent tick, stamped off-draw by the
    /// tick handler from the `std` clock (chrono's `clock` feature is off). It is
    /// the **decay reference** the chain matrix reads at draw time, so
    /// the bid-up/ask-down markers decay on wall-time rather than being pinned to
    /// the last poll (`docs/01-domain-model.md` §6, `docs/02-tui-architecture.md`
    /// §7). Advanced every tick regardless of [`dirty`](App::dirty); the next
    /// redraw reads the fresh instant, so `draw` itself never touches a wall clock.
    pub now: DateTime<Utc>,
    /// A transient one-line keybar hint (e.g. "Depth not available on deribit"),
    /// flashed when an unavailable number key is pressed (`docs/05-views-and-ux.md`
    /// §2). It decays either on the next key or after `HINT_TICKS` ticks
    /// ([`hint_ttl`](App::hint_ttl)), so it is visible for a readable minimum
    /// duration. `None` when nothing is flashed.
    pub status_hint: Option<String>,
    /// Ticks remaining before [`status_hint`](App::status_hint) auto-decays. `0`
    /// when no hint is showing; set to `HINT_TICKS` when a hint is flashed and
    /// counted down each [`AppEvent::Tick`].
    pub hint_ttl: u8,
    /// Whether the modal help overlay is open (§9).
    pub help_open: bool,
    /// Whether the loop should exit after this event.
    pub should_quit: bool,
    /// Set by any handler that mutates state; gates the redraw and is cleared
    /// after a draw by [`mark_drawn`](App::mark_drawn). An idle app with no data
    /// and no input leaves it clear and does not redraw (§3, §8).
    pub dirty: bool,
    /// The render-loop -> data-layer command channel. A handler that needs I/O
    /// sends a [`Command`] here; it never performs the I/O inline. Private so the
    /// only way to enqueue work is a typed [`Command`].
    tx_command: mpsc::Sender<Command>,
    /// How many control commands (reconnect / rediscover / reload / seek) were
    /// dropped because the command channel was full or closed. A recovery
    /// keypress must never be a **silent** no-op: instead of swallowing the send
    /// failure, `send_command` records it here so the status line can surface it.
    /// Monotonic, stopping at the ceiling (a checked increment, never wrapping);
    /// `0` is the healthy steady state (commands are user-driven, so the bounded
    /// channel is never expected to fill — a non-zero value means the data layer
    /// is gone or wedged).
    pub commands_dropped: u64,
}

impl App {
    /// Assemble an app in the given mode. The command `Sender` is the render ->
    /// data half the supervisor (#11) / builder (#12) wire to the data layer.
    ///
    /// [`dirty`](App::dirty) starts `true` so the first frame draws.
    #[must_use]
    pub fn new(mode: Mode, theme: ThemeChoice, tx_command: mpsc::Sender<Command>) -> Self {
        Self {
            mode,
            theme,
            no_color: false,
            status: StatusLine::default(),
            tick_count: 0,
            now: now_utc(),
            status_hint: None,
            hint_ttl: 0,
            help_open: false,
            should_quit: false,
            dirty: true,
            tx_command,
            commands_dropped: 0,
        }
    }

    /// Set whether color output is disabled, builder-style, at startup
    /// (`docs/05-views-and-ux.md` §7). Wired from
    /// [`Config::no_color`](crate::Config) by the app builder / `main`.
    #[must_use]
    pub fn with_no_color(mut self, no_color: bool) -> Self {
        self.no_color = no_color;
        self
    }

    /// Fold one event into the app in a **single exhaustive match with no
    /// wildcard arm** (`docs/02-tui-architecture.md` §4). Every mutating handler
    /// sets [`dirty`](App::dirty); a handler that needs I/O emits a [`Command`]
    /// rather than blocking or awaiting. Not `async` and performs no I/O.
    pub fn on_event(&mut self, event: AppEvent) {
        match event {
            AppEvent::Key(key) => self.on_key(key),
            AppEvent::Resize(width, height) => self.on_resize(width, height),
            AppEvent::Tick => self.on_tick(),
            AppEvent::Market(update) => self.on_market(update),
            AppEvent::ReplaySeek(seek) => self.on_replay_seek(seek),
            AppEvent::ReplayControl(control) => self.on_replay_control(control),
            AppEvent::BundleLoaded(result) => self.on_bundle_loaded(result),
        }
    }

    /// Clear [`dirty`](App::dirty) after the render loop has drawn a frame (§3).
    pub fn mark_drawn(&mut self) {
        self.dirty = false;
    }

    // --- Event handlers (each sets `dirty` only when it mutates state) --------

    fn on_key(&mut self, key: KeyEvent) {
        // Fold a key through the GLOBAL level only. The render-loop dispatch (#13,
        // `src/ui`) forwards a [`KeyRoute::ToScreen`] key on to the active screen's
        // `handle_key`; a non-loop caller (this fan-in entry, and #9's tests) folds
        // only the globals and discards the route, so an unbound key is a no-op —
        // exactly the prior behavior.
        let _ = self.dispatch_key_global(key);
    }

    /// The **global** half of the two-level key dispatch
    /// (`docs/02-tui-architecture.md` §9): handle the quit / help / reconnect /
    /// rediscover globals and the modal-help intercept, and report whether the key
    /// was [`Consumed`](KeyRoute::Consumed) or should be forwarded
    /// [`ToScreen`](KeyRoute::ToScreen). The render loop (#13) forwards a
    /// `ToScreen` key to the active screen's `handle_key`; a `Consumed` key stops
    /// here.
    ///
    /// **Modal help precedence (`docs/05-views-and-ux.md` §3).** While the help
    /// overlay is open it is modal: it intercepts **every** key, honoring only `?`
    /// and `Esc` (both close it) and swallowing the rest — no background screen
    /// action fires behind the overlay, so a keystroke can never mutate hidden
    /// state.
    ///
    /// The globals resolve **through the single keybinding map**
    /// ([`resolve_global`], `src/ui/theme.rs`), so the running dispatch and the
    /// help overlay read one table and cannot drift (§3). `Ctrl-C` is the terminal
    /// interrupt and hard-quits even behind the overlay; every other global (quit,
    /// help, screen switch `1`–`4`, `Tab`/`S-Tab` cycle, reconnect, reload) is a
    /// map [`GlobalCommand`]. An unmapped key is forwarded to the active screen (the
    /// two-level dispatch).
    #[must_use = "the route decides whether the active screen also handles the key"]
    pub(crate) fn dispatch_key_global(&mut self, key: KeyEvent) -> KeyRoute {
        // On some platforms crossterm reports `Release`/`Repeat` in addition to
        // `Press`; act on the press only so a key never fires twice, and never
        // forward a non-press to a screen.
        if key.kind != KeyEventKind::Press {
            return KeyRoute::Consumed;
        }
        // `Ctrl-C` is a hard quit regardless of the character key mapping or the
        // overlay state (the terminal-interrupt convention): it is the ONE key that
        // acts behind the modal help overlay. The map lists `q`/`Ctrl-C` as one
        // Quit action, but `q` is swallowed while the overlay is modal and `Ctrl-C`
        // is not — an intentional carve-out for the terminal interrupt.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.request_quit();
            return KeyRoute::Consumed;
        }
        // Modal help: intercept EVERY key — before the keymap-vocabulary check — so
        // an out-of-vocabulary key (F-keys, PageUp/Down, Insert/Delete, media) can
        // never reach the hidden screen behind the overlay. Only `?`/`Esc` act (both
        // close it); everything else is swallowed.
        if self.help_open {
            if matches!(
                KeyChord::from_event(key),
                Some(KeyChord::Char('?') | KeyChord::Esc)
            ) {
                self.toggle_help();
            }
            return KeyRoute::Consumed;
        }
        let Some(chord) = KeyChord::from_event(key) else {
            // Outside the keymap vocabulary — forward to the active screen.
            return KeyRoute::ToScreen;
        };
        // Any live key decays a stale transient hint (`docs/05-views-and-ux.md`
        // §2); a command below may set a fresh one.
        self.clear_status_hint();
        // Resolve the global command from the single map. An unmapped key routes to
        // the active screen.
        match resolve_global(chord) {
            Some(command) => {
                self.apply_global_command(command);
                KeyRoute::Consumed
            }
            None => KeyRoute::ToScreen,
        }
    }

    /// Execute a resolved global command from the keymap
    /// (`docs/05-views-and-ux.md` §3). Matched exhaustively over the
    /// [`GlobalCommand`] closed set with no wildcard arm.
    fn apply_global_command(&mut self, command: GlobalCommand) {
        match command {
            GlobalCommand::Quit => self.request_quit(),
            GlobalCommand::ToggleHelp => self.toggle_help(),
            GlobalCommand::Reconnect => self.request_reconnect(),
            GlobalCommand::Rediscover => self.request_rediscover(),
            GlobalCommand::SwitchScreen(slot) => self.request_switch_screen(slot),
            GlobalCommand::NextScreen => self.cycle_screen(true),
            GlobalCommand::PrevScreen => self.cycle_screen(false),
        }
    }

    fn on_resize(&mut self, _width: u16, _height: u16) {
        // A resize forces a redraw; the new geometry is read from `frame.area()`
        // in the render loop (#13), so nothing is stored here.
        self.dirty = true;
    }

    fn on_tick(&mut self) {
        // Advance the wall-clock reference the chain matrix reads for tick-direction
        // decay, so a bid-up/ask-down marker decays on wall-time instead of persisting
        // until the next poll (`docs/01-domain-model.md` §6). Stamped off-draw here;
        // `draw` reads the cached instant and never touches a wall clock (§7). This
        // sets no `dirty` on its own — under streaming quotes each `Market` update
        // already redraws and reads this fresh instant.
        self.now = now_utc();
        // Advance the spinner/clock counter the status bar reads purely in `draw`
        // (`docs/05-views-and-ux.md` §7). `checked_add` avoids the banned
        // `wrapping_add`; the counter resets on the (practically unreachable) u64
        // overflow, harmless for a spinner index.
        self.tick_count = self.tick_count.checked_add(1).unwrap_or(0);
        let mut needs_redraw = false;
        // Decay a transient keybar hint after its readable minimum lifetime (§2).
        // Counting down does not redraw; only the final clear does, so an idle app
        // does not spin on the intermediate ticks.
        if self.tick_hint() {
            needs_redraw = true;
        }
        // Advance replay playback: while playing, a tick moves the scrub head by
        // the speed quantum (the cursor clamps at `end_step`, so it stops at the
        // tape end and auto-pauses, `docs/04-replay-mode.md` §4). A no-op in live
        // mode and while paused/loading.
        if self.advance_replay_playback() {
            needs_redraw = true;
        }
        // Advance the loading/reconnecting/playback spinner: redraw ONLY in a motion
        // state, so the spinner animates during the initial connect / reconnect /
        // playback (§7) while a truly idle, non-motion app still parks and never
        // redraws on a tick (§8).
        if self.is_in_motion() {
            needs_redraw = true;
        }
        if needs_redraw {
            self.dirty = true;
        }
    }

    /// Count down a live transient hint, clearing it when its lifetime expires.
    /// Returns whether a redraw is needed (only when the hint is actually cleared,
    /// so the intermediate countdown ticks set no `dirty`).
    fn tick_hint(&mut self) -> bool {
        if self.status_hint.is_none() {
            return false;
        }
        // `saturating_*`/`wrapping_*` are banned, so decrement with a checked step
        // and treat "reached zero" as "clear the hint".
        match self.hint_ttl.checked_sub(1) {
            Some(remaining) if remaining > 0 => {
                self.hint_ttl = remaining;
                false
            }
            _ => {
                self.status_hint = None;
                self.hint_ttl = 0;
                true
            }
        }
    }

    /// Whether the app is in a **motion** state whose spinner/play-head advances on
    /// each tick (`docs/05-views-and-ux.md` §7): a live view still loading or
    /// reconnecting, or a replay bundle still loading or playing. A non-motion app
    /// (a ready chain on a live feed, a paused replay) parks and does not redraw on
    /// an idle tick (§8). Mirrors the theme's status-bar motion predicate.
    #[must_use]
    fn is_in_motion(&self) -> bool {
        match &self.mode {
            Mode::Live(live) => {
                matches!(live.load, ScreenLoad::Loading)
                    || matches!(live.source.health, StreamHealth::Reconnecting { .. })
            }
            Mode::Replay(replay) => {
                matches!(replay.bundle, BundleLoad::Loading)
                    || matches!(replay.play, Playback::Playing { .. })
            }
        }
    }

    fn on_market(&mut self, update: MarketUpdate) {
        let changed = match &mut self.mode {
            Mode::Live(live) => live.apply_market(update),
            // Live market updates are meaningless in replay mode (there is no
            // live store); the replay play-head moves via `ReplaySeek` and the
            // bundle lands via `BundleLoaded`.
            Mode::Replay(_) => false,
        };
        if changed {
            self.dirty = true;
        }
    }

    fn on_replay_seek(&mut self, seek: SeekTo) {
        match &mut self.mode {
            // A scrub is meaningless in live mode; ignored.
            Mode::Live(_) => {}
            // Seeking moves the in-memory timeline cursor (no I/O — the whole
            // bundle is loaded, #33), so it folds directly here rather than
            // emitting a command; a no-op until the bundle is `Ready`.
            Mode::Replay(replay) => {
                if replay.seek(seek) {
                    self.dirty = true;
                }
            }
        }
    }

    fn on_replay_control(&mut self, control: ReplayControl) {
        match &mut self.mode {
            // Playback control is meaningless in live mode; ignored.
            Mode::Live(_) => {}
            // Fold the play/pause/speed key into the playback state; the tick timer
            // advances the cursor while playing.
            Mode::Replay(replay) => {
                if replay.apply_control(control) {
                    self.dirty = true;
                }
            }
        }
    }

    fn on_bundle_loaded(&mut self, result: BundleLoadResult) {
        match &mut self.mode {
            // A bundle-load result is meaningless in live mode; ignored.
            Mode::Live(_) => {}
            // The off-thread load finished: fold the `BundleLoad` state machine
            // from `Loading` to `Ready`/`Error` and always redraw the transition.
            Mode::Replay(replay) => {
                replay.apply_load_result(result);
                self.dirty = true;
            }
        }
    }

    /// Advance the replay play-head one tick, or a no-op in live mode / while
    /// paused / while the bundle is not yet `Ready`. Returns whether a redraw is
    /// needed (the cursor moved or playback auto-paused at the tape end).
    fn advance_replay_playback(&mut self) -> bool {
        match &mut self.mode {
            Mode::Live(_) => false,
            Mode::Replay(replay) => replay.advance_playback(),
        }
    }

    // --- Global key actions ---------------------------------------------------

    fn request_quit(&mut self) {
        self.should_quit = true;
        self.dirty = true;
    }

    fn toggle_help(&mut self) {
        self.help_open = !self.help_open;
        self.dirty = true;
    }

    fn request_reconnect(&mut self) {
        match &self.mode {
            Mode::Live(_) => {
                let _ = self.send_command(Command::Reconnect);
            }
            // `r` has no replay binding — `R` reloads the bundle instead (§6).
            Mode::Replay(_) => {}
        }
    }

    fn request_rediscover(&mut self) {
        match &mut self.mode {
            Mode::Live(_) => {
                let _ = self.send_command(Command::Rediscover);
            }
            Mode::Replay(replay) => {
                // Enqueue the reload FIRST and flip to `Loading` only once it is
                // actually on the command channel. A dropped send (a full/closed
                // command channel — the data layer is gone; the drop is counted by
                // `commands_dropped`, #9) would otherwise strand the load screen at
                // `Loading` forever with no load in flight, so on a failed send the
                // prior bundle state is kept and a one-line hint is flashed instead
                // (`docs/05-views-and-ux.md` §6). The fresh bundle lands back via
                // `AppEvent::BundleLoaded`. Cloning the dir first ends the `replay`
                // borrow so the `&mut self` send is free of an overlapping borrow.
                let dir = replay.dir.clone();
                if self.send_command(Command::ReloadBundle(dir)) {
                    if let Mode::Replay(replay) = &mut self.mode {
                        replay.begin_reload();
                    }
                    self.dirty = true;
                } else {
                    self.set_status_hint(RELOAD_UNAVAILABLE_HINT.to_owned());
                }
            }
        }
    }

    /// Enqueue a command for the data layer, non-blocking, returning whether it was
    /// actually enqueued. Never blocks or awaits the render loop. A full or closed
    /// command channel does **not** silently swallow a recovery keypress: the
    /// failure is counted in [`commands_dropped`](App::commands_dropped) (so the
    /// status line can surface it) **and** reported as `false`, so a caller that
    /// must not change state on a dropped send — the replay reload, which would
    /// otherwise strand the load screen at `Loading` with no load in flight — can
    /// react. A command storm is impossible (commands are user-driven, `docs/02`
    /// §5), so a full channel is not expected; a closed channel means the data
    /// layer is gone, which the surfaced count now makes visible rather than
    /// hidden.
    fn send_command(&mut self, command: Command) -> bool {
        if self.tx_command.try_send(command).is_err() {
            // Checked, not `saturating_add` (a banned method): increment only
            // when it does not overflow, so the counter stops at the ceiling
            // rather than wrapping. Reaching `u64::MAX` dropped commands is not a
            // reachable state; the check is defensive.
            if let Some(next) = self.commands_dropped.checked_add(1) {
                self.commands_dropped = next;
            }
            false
        } else {
            true
        }
    }

    // --- Screen navigation (reachable-only, capability-driven) ----------------

    /// Switch to the screen a number key selects (`docs/05-views-and-ux.md` §2).
    /// A **reachable** target switches; an **unavailable** one flashes a one-line
    /// keybar hint and leaves the current screen in place — so `screen` is only
    /// ever set to a reachable value and the render dispatch (#13) stays total.
    /// Reachability reads declared [`ProviderCapabilities`], **never** a
    /// [`ProviderId`] match.
    fn request_switch_screen(&mut self, slot: u8) {
        let outcome = match &mut self.mode {
            Mode::Live(live) => match live_screen_for_slot(slot) {
                Some(screen) if live.screen == screen => SwitchOutcome::NoChange,
                Some(screen) if live.screen_reachable(screen) => {
                    // Route through `enter_screen` so entering the Surface screen pays
                    // any deferred (off-screen) geometry rebuild once, off the draw
                    // path (#106).
                    live.enter_screen(screen);
                    SwitchOutcome::Switched
                }
                Some(screen) => SwitchOutcome::Unavailable(format!(
                    "{} not available on {}",
                    live_screen_name(screen),
                    live.source.provider.as_str()
                )),
                None => SwitchOutcome::Unavailable(format!("no screen bound to {slot}")),
            },
            Mode::Replay(replay) => match replay_screen_for_slot(slot) {
                Some(screen) if replay.screen == screen => SwitchOutcome::NoChange,
                Some(screen) if is_replay_screen_reachable(screen) => {
                    replay.screen = screen;
                    SwitchOutcome::Switched
                }
                Some(screen) => SwitchOutcome::Unavailable(replay_unavailable_hint(screen)),
                None => SwitchOutcome::Unavailable(format!("no screen bound to {slot}")),
            },
        };
        match outcome {
            SwitchOutcome::Switched => self.dirty = true,
            SwitchOutcome::NoChange => {}
            SwitchOutcome::Unavailable(hint) => self.set_status_hint(hint),
        }
    }

    /// Cycle to the next (`forward`) or previous **reachable** screen for the
    /// active mode+provider (`docs/05-views-and-ux.md` §2), skipping unavailable
    /// screens so `Tab`/`S-Tab` never land on a not-supported body.
    fn cycle_screen(&mut self, forward: bool) {
        let changed = match &mut self.mode {
            Mode::Live(live) => {
                let reachable: Vec<LiveScreen> = LIVE_SCREEN_ORDER
                    .into_iter()
                    .filter(|screen| live.screen_reachable(*screen))
                    .collect();
                match next_in_cycle(&reachable, live.screen, forward) {
                    Some(next) if next != live.screen => {
                        // Route through `enter_screen` so a `Tab` into the Surface
                        // screen pays any deferred off-screen geometry rebuild once,
                        // off the draw path (#106).
                        live.enter_screen(next);
                        true
                    }
                    _ => false,
                }
            }
            Mode::Replay(replay) => {
                let reachable: Vec<ReplayScreen> = REPLAY_SCREEN_ORDER
                    .into_iter()
                    .filter(|screen| is_replay_screen_reachable(*screen))
                    .collect();
                match next_in_cycle(&reachable, replay.screen, forward) {
                    Some(next) if next != replay.screen => {
                        replay.screen = next;
                        true
                    }
                    _ => false,
                }
            }
        };
        if changed {
            self.dirty = true;
        }
    }

    /// Flash a transient one-line keybar hint (`docs/05-views-and-ux.md` §2). It
    /// decays on the next key or after [`HINT_TICKS`] ticks, so it stays visible for
    /// a readable minimum duration.
    fn set_status_hint(&mut self, hint: String) {
        self.status_hint = Some(hint);
        self.hint_ttl = HINT_TICKS;
        self.dirty = true;
    }

    /// Clear a transient keybar hint if one is showing, marking the frame dirty
    /// only when a hint was actually cleared (so an idle key with no hint sets no
    /// dirty).
    fn clear_status_hint(&mut self) {
        if self.status_hint.take().is_some() {
            self.hint_ttl = 0;
            self.dirty = true;
        }
    }
}

/// The outcome of a number-key screen switch (`docs/05-views-and-ux.md` §2),
/// computed under the mode borrow and applied to [`App`] afterwards to avoid an
/// overlapping mutable borrow.
enum SwitchOutcome {
    /// The switch was applied — the screen changed.
    Switched,
    /// The requested screen is already active — nothing to do.
    NoChange,
    /// The requested screen is unavailable — flash this keybar hint, no switch.
    Unavailable(String),
}

/// The outcome of the **global** key-dispatch level
/// (`docs/02-tui-architecture.md` §9): whether [`App::dispatch_key_global`]
/// consumed the key, or the render loop (#13) should forward it to the active
/// screen's `handle_key`.
///
/// A ChainView closed set matched exhaustively with no wildcard arm, so the
/// render-loop forwarding site is revisited by the compiler if a routing outcome
/// is ever added.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum KeyRoute {
    /// The global level handled the key (quit / help / reconnect / rediscover, or
    /// a modal-help intercept); the active screen must **not** also see it.
    Consumed,
    /// The global level did not bind the key; forward it to the active screen.
    ToScreen,
}

// ---------------------------------------------------------------------------
// Mode + mode-scoped screens (§3).
// ---------------------------------------------------------------------------

/// The `Live | Replay` mode, each owning its own state and active screen (§3).
///
/// A ChainView closed set matched exhaustively with no wildcard arm, so a new
/// mode forces every match site to be revisited by the compiler.
///
/// The `Live` variant is far larger than `Replay` (it owns the live
/// [`ChainStore`]), but exactly **one** `Mode` exists per process — it is
/// `App.mode`, never collected — so the size asymmetry wastes no memory, while
/// boxing the hot `LiveState` would add indirection to every event fold. The
/// documented shape (§3) is intentionally unboxed.
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Mode {
    /// Live mode: a streamed option chain from the selected provider.
    Live(LiveState),
    /// Replay mode: an IronCondor result bundle rendered read-only.
    Replay(ReplayState),
}

/// The active **Live**-mode screen (`docs/02-tui-architecture.md` §3, §7).
///
/// Owned by [`LiveState`], so a live screen can never pair with a replay mode —
/// the out-of-mode pair is unrepresentable. Fieldless, so `#[repr(u8)]` per the
/// ruleset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum LiveScreen {
    /// The chain matrix (strikes × call/put), the default screen.
    #[default]
    Chain,
    /// The order-book depth ladder (depth-capable providers only).
    Depth,
    /// The volatility smile / surface.
    Surface,
    /// The multi-leg payoff diagram.
    Payoff,
}

/// The active **Replay**-mode screen (`docs/02-tui-architecture.md` §3, §7).
///
/// Owned by [`ReplayState`]. Fieldless, so `#[repr(u8)]` per the ruleset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ReplayScreen {
    /// The equity curve, P&L attribution, and per-trade drill-down.
    #[default]
    Replay,
    /// The payoff diagram for the selected trade (v0.5, `docs/ROADMAP.md`).
    Payoff,
}

// ---------------------------------------------------------------------------
// LiveState: the composite source + overlay binding, the store, and screen.
// ---------------------------------------------------------------------------

/// Live-mode state: the chain source binding, an optional overlay binding, the
/// active screen, the live [`ChainStore`], and the per-screen support state
/// (`docs/02-tui-architecture.md` §3).
#[derive(Debug)]
pub struct LiveState {
    /// The provider that supplies the chain structure (and possibly its own
    /// quotes/Greeks), with its declared capabilities and this side's health.
    pub source: SourceBinding,
    /// An optional quote/Greek overlay provider (standalone DXLink over another
    /// provider's chain), with its own capabilities and **independent** health.
    pub overlay: Option<OverlayBinding>,
    /// The active Live screen — only ever set to a reachable value
    /// ([`set_screen`](LiveState::set_screen)).
    pub screen: LiveScreen,
    /// The normalized, streaming-current chain (`src/chain`), the source of truth
    /// draw reads.
    pub store: ChainStore,
    /// The focused underlying/expiry/strike selection.
    pub selection: Selection,
    /// The multi-leg payoff-builder state (v0.2, `docs/05-views-and-ux.md` §3).
    pub payoff_builder: PayoffBuilder,
    /// The vol smile / Greek-curve / single-expiry-surface panel state and its
    /// cached geometry (v0.5, #47, `docs/05-views-and-ux.md` §4).
    pub surface: SurfacePanel,
    /// The live order-book depth store (v0.5, #48, `docs/03-data-providers.md` §8):
    /// a bounded per-instrument latest-ladder slot the [`LiveScreen::Depth`] screen
    /// reads for the selected contract, folded from `MarketUpdate::Depth`.
    pub depth_store: DepthStore,
    /// The depth-ladder scroll offset (`↑↓ / kj` on the [`LiveScreen::Depth`] screen,
    /// #48). `None` before the user has scrolled — the draw then centers the inside
    /// market (#48 P3-02); `Some(start)` is the explicit first visible row. Clamped to
    /// the viewport (`total − depth_visible_rows`) by the scroll handler and re-clamped
    /// to the window at draw time, so a stored value never over-scrolls a shorter book.
    pub depth_scroll: Option<usize>,
    /// The depth body's last visible-row count, stashed by the render loop **after**
    /// each draw (`src/ui/driver.rs`), off the pure draw — the render loop owns
    /// geometry (#48 P2-02). The scroll handler reads it to clamp the offset to the
    /// viewport so an at-limit (or fits-entirely) press changes nothing and forces no
    /// redraw. `0` until the depth screen has drawn at least once.
    pub depth_visible_rows: usize,
    /// The screen's load lifecycle (loading / ready / error).
    pub load: ScreenLoad,
    /// The cached ATM strike-row index (ascending strike order) — the chain
    /// screen's `◀ATM` marker and default scroll anchor. Recomputed **off-draw**
    /// only when a poll changes the strike ladder or spot ([`new`](LiveState::new)
    /// and [`apply_chain_snapshot`](LiveState::apply_chain_snapshot)); a quote
    /// patches a row but never moves the ATM, so it is not recomputed on a quote.
    /// `draw` reads it via [`atm_index`](LiveState::atm_index) in O(1) instead of
    /// rescanning the full ladder each frame (the frame-budget rule, `CLAUDE.md`).
    atm_index: Option<usize>,
}

impl LiveState {
    /// A live state bound to a chain source, seeded with its store, on the
    /// default [`LiveScreen::Chain`] screen in the [`ScreenLoad::Loading`] state.
    ///
    /// The default [`LiveScreen::Chain`] is only reachable because a live source
    /// always assembles a chain (`ChainCapability != None`); a chain-less feed
    /// (standalone dxlink) is rejected as a *source* at registry startup (#12),
    /// never reaching here. The `debug_assert` makes that non-local invariant
    /// local so a future construction path that violated it would fail fast in
    /// development rather than open on an unreachable screen.
    #[must_use]
    pub fn new(source: SourceBinding, store: ChainStore) -> Self {
        debug_assert!(
            chain_present(source.capabilities.chain),
            "a live source must assemble a chain so the default Chain screen is reachable",
        );
        // Seed the cached ATM index off-draw from the initial chain, so the first
        // frame reads it without rescanning the ladder.
        let atm_index = atm_index_of(store.chain());
        let surface = SurfacePanel::new(&store);
        Self {
            source,
            overlay: None,
            screen: LiveScreen::Chain,
            store,
            selection: Selection::default(),
            payoff_builder: PayoffBuilder::new(),
            surface,
            depth_store: DepthStore::new(),
            depth_scroll: None,
            depth_visible_rows: 0,
            load: ScreenLoad::Loading,
            atm_index,
        }
    }

    /// The cached ATM strike-row index (ascending strike order), or `None` for an
    /// empty chain — the chain screen's `◀ATM` marker and default scroll anchor.
    /// Recomputed off-draw on a poll, so `draw` reads it in O(1) rather than
    /// rescanning the strike ladder each frame.
    #[must_use]
    pub fn atm_index(&self) -> Option<usize> {
        self.atm_index
    }

    /// Bind an overlay provider (its health is tracked independently of the
    /// source's).
    #[must_use]
    pub fn with_overlay(mut self, overlay: OverlayBinding) -> Self {
        self.overlay = Some(overlay);
        self
    }

    /// Switch to `screen` **iff** it is reachable for the effective capabilities,
    /// returning whether the switch was applied. A screen is never set to an
    /// unreachable value, so the render dispatch (#13) stays total without an
    /// "unavailable" arm. The caller sets [`App::dirty`] on a `true` result; the
    /// `Tab` skip and number-key hint build on this in #14.
    #[must_use = "the returned bool reports whether the screen switch was applied"]
    pub fn set_screen(&mut self, screen: LiveScreen) -> bool {
        if self.screen_reachable(screen) {
            self.enter_screen(screen);
            true
        } else {
            false
        }
    }

    /// Set the active screen to `screen` (assumed reachable) and run its screen-entry
    /// side effect off the draw path. Entering the **Surface** screen pays the deferred
    /// geometry rebuild if a market fold marked it dirty while hidden (#106), so the
    /// fan-in path never rebuilt an invisible panel and the cost lands lazily, once, on
    /// the switch — the draw stays pure. The single seam every screen-switch path
    /// (number keys, `Tab`, [`set_screen`](Self::set_screen)) routes through, so the
    /// lazy rebuild can never be skipped.
    pub(crate) fn enter_screen(&mut self, screen: LiveScreen) {
        self.screen = screen;
        if screen == LiveScreen::Surface {
            let LiveState { store, surface, .. } = self;
            surface.rebuild_if_dirty(store);
        }
    }

    /// Whether `screen` is reachable for this state's **effective** capabilities
    /// (source ∪ overlay). Reads capabilities only — never the [`ProviderId`].
    #[must_use]
    pub fn screen_reachable(&self, screen: LiveScreen) -> bool {
        is_screen_reachable(screen, &self.effective_capabilities())
    }

    /// The capabilities the UI gates on: the source's, with the overlay's live
    /// quote/Greek and depth reach unioned in when an overlay is bound
    /// (`docs/02-tui-architecture.md` §3, the capabilities union). The structure
    /// dimensions (`chain`/`chain_poll`) always come from the source, since the
    /// overlay has no chain of its own. The remaining stream/tape union
    /// refinements are finalized with the navigation layer (#13/#14).
    #[must_use]
    pub fn effective_capabilities(&self) -> ProviderCapabilities {
        let source = self.source.capabilities;
        let Some(overlay) = self.overlay.as_ref() else {
            return source;
        };
        let overlay = overlay.capabilities;
        ProviderCapabilities::builder()
            .chain(source.chain)
            .depth(source.depth || overlay.depth)
            .greeks(max_greeks(source.greeks, overlay.greeks))
            .option_stream(source.option_stream)
            .underlying_stream(source.underlying_stream || overlay.underlying_stream)
            .chain_poll(source.chain_poll)
            .trades_tape(source.trades_tape || overlay.trades_tape)
            .auth(source.auth)
            .build()
    }

    /// The stream health a screen that consumes BOTH the chain source and any bound
    /// quote/Greek overlay must reflect (#118). The Surface screen's smile / curve /
    /// surface geometry reads Greeks/IV that a **standalone overlay** (e.g. dxlink over
    /// another provider's chain) may supply, so it degrades when EITHER contributor is
    /// not [`StreamHealth::Live`]: a stale overlay must dim + badge the surface even
    /// while the chain source is live — never a bright, trusted-looking curve over a
    /// stale feed.
    ///
    /// Returns the source health while both sides are live, else the first non-live
    /// contributor (the source preferred when both degraded), so the caller reads one
    /// `&StreamHealth` for both the stale-dim decision and the title badge. When no
    /// overlay is bound this is just the source health.
    #[must_use]
    pub fn overlay_aware_health(&self) -> &StreamHealth {
        if !matches!(self.source.health, StreamHealth::Live) {
            return &self.source.health;
        }
        match self.overlay.as_ref() {
            Some(overlay) if !matches!(overlay.health, StreamHealth::Live) => &overlay.health,
            _ => &self.source.health,
        }
    }

    /// Fold one market update into the appropriate store, returning whether the fold
    /// changed anything the screen would render (so the caller can set `dirty`).
    ///
    /// Matched exhaustively over the [`MarketUpdate`] closed set with no wildcard
    /// arm. A [`Depth`](MarketUpdate::Depth) fold goes into the depth-ladder store
    /// and never touches the chain-derived surface/payoff geometry, so it is handled
    /// apart from the chain-affecting folds (via [`fold_chain_update`]) and skips
    /// their refresh — the busy book path stays off the surface/t+0 rebuild.
    fn apply_market(&mut self, update: MarketUpdate) -> bool {
        match update {
            MarketUpdate::Quote(quote) => {
                let changed = merged(self.store.apply_quote(&quote));
                self.fold_chain_update(changed)
            }
            MarketUpdate::Greeks(greeks) => {
                let changed = merged(self.store.apply_greeks(&greeks));
                self.fold_chain_update(changed)
            }
            MarketUpdate::Depth(ladder) => self.apply_depth(ladder),
            MarketUpdate::Chain(snapshot) => {
                let changed = self.apply_chain_snapshot(snapshot);
                self.fold_chain_update(changed)
            }
            MarketUpdate::Health(provider, health) => {
                let changed = self.apply_health(&provider, health);
                self.fold_chain_update(changed)
            }
        }
    }

    /// Complete a **chain-affecting** fold: on a real change, refresh the committed
    /// payoff's t+0 curve and the active Surface geometry **off the draw path**, then
    /// report whether the screen should redraw.
    ///
    /// The t+0 refresh runs **only** while the t+0 curve is the shown one — the hot
    /// quote path does nothing when the (IV-independent) expiration curve is
    /// displayed — and re-prices the committed legs directly, never reconstructing a
    /// `CustomStrategy` (#27). The Surface rebuild bumps the panel's graph revision
    /// only when the geometry actually moved, so the view cache re-projects only on a
    /// real change (#47). A depth fold never reaches here — it touches neither.
    fn fold_chain_update(&mut self, changed: bool) -> bool {
        if changed {
            self.refresh_committed_tplus0();
            self.refresh_surface();
        }
        changed
    }

    /// Fold an order-book [`DepthLadder`] into the per-instrument depth store
    /// (#48, `docs/03-data-providers.md` §8), returning whether the frame should
    /// redraw.
    ///
    /// The bounded store always folds the ladder (latest-value-wins, or a bounded
    /// drop at capacity), but a redraw is requested **only** when the update is for
    /// the currently **selected** contract *and* the [`LiveScreen::Depth`] screen is
    /// active — a book burst for an off-screen contract, or any depth while another
    /// screen is shown, folds silently and never wakes the render loop, keeping the
    /// busiest provider path off the idle-redraw budget (`docs/06-performance.md`).
    fn apply_depth(&mut self, ladder: DepthLadder) -> bool {
        let visible = self.screen == LiveScreen::Depth
            && self.selected_depth_key().as_ref() == Some(&ladder.instrument.key);
        let applied = self.depth_store.apply(ladder);
        applied && visible
    }

    /// The provider-agnostic [`InstrumentKey`] of the contract the depth screen shows
    /// — the chain cursor's focused strike row and its focused call/put leg (#48).
    ///
    /// `None` when no strike row is focused yet (the depth screen renders its "select
    /// a contract" empty state) or when a poll shrank the chain under a stale cursor
    /// index — a `.get()`/`.nth()`-style bounded read, never an unchecked index. The
    /// underlying and absolute-UTC expiry come from the store's canonical chain key,
    /// so the key matches the one a [`DepthLadder`] carries.
    #[must_use]
    pub fn selected_depth_key(&self) -> Option<InstrumentKey> {
        let row = self.selection.focused_row?;
        let od = self.store.chain().options.iter().nth(row)?;
        let (_, underlying, expiration) = self.store.chain_key();
        let style = match self.selection.focused_leg {
            LegFocus::Call => OptionStyle::Call,
            LegFocus::Put => OptionStyle::Put,
        };
        Some(InstrumentKey {
            underlying: underlying.clone(),
            expiration_utc: *expiration,
            strike: od.strike_price,
            style,
        })
    }

    /// Reconcile the Surface panel with a data-changing market fold, off the draw path
    /// (#47, #106). When the Surface screen is **active** the geometry is rebuilt now
    /// (the smile / Greek curve / surface for the active view + axis); when it is
    /// **hidden** the panel is only marked dirty — the fan-in never rebuilds an
    /// invisible panel, and the deferred rebuild is paid once on switch-to-surface
    /// ([`enter_screen`](Self::enter_screen)). Disjoint field borrows (`store` read,
    /// `surface` mutated) so no clone and no I/O.
    fn refresh_surface(&mut self) {
        if self.screen == LiveScreen::Surface {
            let LiveState { store, surface, .. } = self;
            surface.refresh(store);
        } else {
            self.surface.mark_dirty();
        }
    }

    /// Re-price the committed strategy's t+0 curve against the current store
    /// snapshot when it is the shown curve. A cheap no-op otherwise (two field
    /// reads), so a streaming quote never rebuilds a hidden curve.
    fn refresh_committed_tplus0(&mut self) {
        if self.payoff_builder.curve() != CurveMode::TPlus0
            || self.payoff_builder.committed().is_none()
        {
            return;
        }
        let LiveState {
            store,
            payoff_builder,
            ..
        } = self;
        payoff_builder.refresh_tplus0(store);
    }

    /// Reconcile the store's structure against a fresh full re-poll delivered as
    /// a [`ChainSnapshot`]. The snapshot is lowered back into a [`ChainFetch`]
    /// and handed to [`ChainStore::apply_poll`] — the store's own tombstone /
    /// pending-drain reconciliation — using the snapshot's own poll timestamp, so
    /// the fold is deterministic and reads no wall clock. A snapshot with no poll
    /// timestamp is a pre-seed artifact and carries no structure to reconcile (a
    /// defensive no-op).
    fn apply_chain_snapshot(&mut self, snapshot: ChainSnapshot) -> bool {
        let ChainSnapshot {
            chain_key,
            chain,
            aliases,
            last_full_poll,
            source: _,
            health: _,
        } = snapshot;
        match last_full_poll {
            Some(polled) => {
                let (provider, underlying, expiration_utc) = chain_key;
                let fetch = ChainFetch::new(
                    chain,
                    ExpirySource::new(underlying, expiration_utc, provider),
                    aliases,
                );
                self.store.apply_poll(fetch, polled);
                // A poll can move spot or the strike ladder, so refresh the cached
                // ATM index off-draw here — draw never rescans the ladder.
                self.atm_index = atm_index_of(self.store.chain());
                true
            }
            None => false,
        }
    }

    /// Route a stream-health transition to the correct side by comparing the
    /// event's provider to each binding's — an equality check, never a `match` on
    /// [`ProviderId`]. Either side failing degrades **only** that side (§3): a
    /// source drop badges the structure stale and clears the store's price
    /// direction indicators; an overlay drop badges quotes/Greeks stale while the
    /// structure keeps rendering. Returns whether a side changed.
    fn apply_health(&mut self, provider: &ProviderId, health: StreamHealth) -> bool {
        let mut changed = false;
        if *provider == self.source.provider {
            self.source.health = health.clone();
            // Forward the SOURCE feed's health to the store so its price-direction
            // indicators clear on a stale/reconnecting chain feed (`docs/01` §6).
            self.store.apply_health(health.clone());
            changed = true;
        }
        if let Some(overlay) = &mut self.overlay
            && *provider == overlay.provider
        {
            overlay.health = health;
            changed = true;
        }
        changed
    }
}

/// The provider that supplies the chain structure (and possibly its own
/// quotes/Greeks) plus the capabilities the UI gates on and this side's health
/// (`docs/02-tui-architecture.md` §3).
#[derive(Debug, Clone)]
pub struct SourceBinding {
    /// The source provider's id.
    pub provider: ProviderId,
    /// Its declared capabilities — gates which screens are reachable.
    pub capabilities: ProviderCapabilities,
    /// This side's connection health/freshness.
    pub health: StreamHealth,
}

impl SourceBinding {
    /// Bind a chain source from its id, capabilities, and initial health.
    #[must_use]
    pub fn new(
        provider: ProviderId,
        capabilities: ProviderCapabilities,
        health: StreamHealth,
    ) -> Self {
        Self {
            provider,
            capabilities,
            health,
        }
    }
}

/// An optional quote/Greek overlay provider that streams contract updates but
/// has no chain of its own (standalone DXLink over another provider's chain,
/// `docs/02-tui-architecture.md` §3). Its health is tracked **per side**,
/// independent of the source's — the composite degrades one side at a time.
#[derive(Debug, Clone)]
pub struct OverlayBinding {
    /// The overlay provider's id (e.g. `dxlink`).
    pub provider: ProviderId,
    /// Its declared capabilities — unioned into the gating set.
    pub capabilities: ProviderCapabilities,
    /// This side's connection health/freshness, independent of the source's.
    pub health: StreamHealth,
}

impl OverlayBinding {
    /// Bind an overlay from its id, capabilities, and initial health.
    #[must_use]
    pub fn new(
        provider: ProviderId,
        capabilities: ProviderCapabilities,
        health: StreamHealth,
    ) -> Self {
        Self {
            provider,
            capabilities,
            health,
        }
    }
}

/// Which option leg (call or put) is focused on the selected strike row
/// (`docs/05-views-and-ux.md` §3), toggled by `c` / `p` on the chain matrix
/// (#18).
///
/// A ChainView UI-selection enum, fieldless, so `#[repr(u8)]` per the ruleset;
/// it defaults to [`Call`](LegFocus::Call). The chain matrix emphasizes the
/// focused leg on the selected row; a future leg-detail view derives that leg's
/// own ITM/OTM from its style, never off the shared row relation
/// (`docs/01-domain-model.md` §8).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum LegFocus {
    /// The call leg is focused.
    #[default]
    Call,
    /// The put leg is focused.
    Put,
}

/// The focused underlying/expiry/strike selection (`docs/02-tui-architecture.md`
/// §3). The typed cursor the chain matrix (#18) drives: the focused strike row
/// and the focused leg on it. Expiry/underlying navigation emits a [`Command`]
/// rather than living here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Selection {
    /// The focused strike-row index within the visible chain, or `None` before
    /// any row is focused. Draw reads it with `.get()` + a fallback — never an
    /// unchecked index — and clamps it to the current strike count, so a poll
    /// that shrank the chain never yields an out-of-range cursor.
    pub focused_row: Option<usize>,
    /// The focused option leg on the selected strike row, toggled by `c` / `p`
    /// (`docs/05-views-and-ux.md` §3). Defaults to the call leg.
    pub focused_leg: LegFocus,
}

/// Whether a payoff-builder leg is **bought** (long) or **sold** (short)
/// (`docs/05-views-and-ux.md` §3). A ChainView UI closed set, fieldless, so
/// `#[repr(u8)]` per the ruleset; it defaults to [`Buy`](Side::Buy) — a freshly
/// appended leg is long until `s` toggles it. The `Selection` carries no side, so
/// [`PayoffBuilder`](PayoffBuilder)'s append seeds a leg long and `s` flips it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum Side {
    /// A bought (long) leg.
    #[default]
    Buy,
    /// A sold (short) leg.
    Sell,
}

impl Side {
    /// The opposite side — `Buy ⇄ Sell` (`s` on the payoff screen). Exhaustive
    /// over the closed set with no wildcard arm.
    #[must_use]
    pub fn toggled(self) -> Self {
        match self {
            Self::Buy => Self::Sell,
            Self::Sell => Self::Buy,
        }
    }

    /// The short, color-independent label for the side (`BUY` / `SELL`), so the
    /// side reads on a monochrome terminal (color is never the only signal).
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Buy => "BUY",
            Self::Sell => "SELL",
        }
    }
}

/// One leg of the multi-leg payoff builder (`docs/05-views-and-ux.md` §3): a
/// contract at a `strike`/`style`, a `side` (buy/sell), and an integer `qty`
/// (contracts). Appended from the chain's focused leg (`a`) and edited in place by
/// the cursor keys. A `qty` of `0` is an invalid state validation rejects, so it is
/// a plain `u32`, not a `NonZero` — the zero-qty check exists precisely to catch it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuilderLeg {
    /// The strike price of the contract.
    pub strike: Positive,
    /// The option style (call or put).
    pub style: OptionStyle,
    /// Whether the leg is bought or sold.
    pub side: Side,
    /// The number of contracts; a `0` qty fails validation.
    pub qty: u32,
}

impl BuilderLeg {
    /// The leg's mark (mid) price in `chain`, or `None` when the strike is absent
    /// from the chain, the relevant side has no mid this frame, **or** the mid is the
    /// non-finite `Positive::MAX` sentinel — the `—`-not-`0` honesty rule
    /// (`docs/01-domain-model.md` §8). A pure lookup: validation and the builder
    /// widget both read the mark through this one helper so they cannot disagree on
    /// what "known" means.
    #[must_use]
    pub fn mark_in(&self, chain: &OptionChain) -> Option<Positive> {
        let od = chain
            .options
            .iter()
            .find(|o| o.strike_price == self.strike)?;
        let mid = match self.style {
            OptionStyle::Call => od.call_middle,
            OptionStyle::Put => od.put_middle,
        };
        // Honesty symmetry with the display: `fmt_price` renders the `Positive::MAX`
        // sentinel as `—` (unknown), so an infinite mid is "no mark" here too — it fails
        // validation with `NoMark`, never passing a value the widget would paint as `—`.
        mid.filter(|m| *m != Positive::MAX)
    }
}

/// Which payoff curve the screen draws (`docs/05-views-and-ux.md` §4): the
/// **expiration** payoff or the **t+0** (mark-based) curve, toggled by `t`. The
/// state lives here because the toggle is a view preference on the builder; the
/// curve itself is rendered by the payoff screen (#27). A closed set, fieldless, so
/// `#[repr(u8)]` per the ruleset; defaults to [`Expiration`](CurveMode::Expiration).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum CurveMode {
    /// The payoff at expiration.
    #[default]
    Expiration,
    /// The t+0 (current-mark) curve.
    TPlus0,
}

impl CurveMode {
    /// The other curve — `Expiration ⇄ t+0` (`t`). Exhaustive with no wildcard arm.
    #[must_use]
    pub fn toggled(self) -> Self {
        match self {
            Self::Expiration => Self::TPlus0,
            Self::TPlus0 => Self::Expiration,
        }
    }

    /// The short, color-independent label for the curve mode.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Expiration => "expiration",
            Self::TPlus0 => "t+0",
        }
    }
}

/// A single validation failure of the payoff builder, projected inline in the
/// builder panel (`docs/05-views-and-ux.md` §3, §6). A ChainView closed set matched
/// exhaustively with no wildcard arm. Leg indices are **1-based** in the message so
/// the text matches the ladder the user sees (e.g. `leg 2: no mark`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LegError {
    /// The builder has no legs — the empty state, not a per-leg failure.
    Empty,
    /// The leg at zero-based index `idx` has a zero quantity.
    ZeroQty {
        /// The zero-based index of the offending leg.
        idx: usize,
    },
    /// The leg at zero-based index `idx` has no known/fresh mark in the current
    /// chain snapshot (its strike is absent, or its side has no mid this frame).
    NoMark {
        /// The zero-based index of the offending leg.
        idx: usize,
    },
    /// The leg at zero-based index `idx` has a mark, but its stream quote went
    /// stale beyond the documented threshold (`QUOTE_STALE_AFTER`) — a cached
    /// midpoint from a feed that stopped updating must not be committed as an
    /// entry price. Mirrors the #24 kernel gate: a leg with no stream clock
    /// (poll-seeded) is not gated.
    StaleMark {
        /// The zero-based index of the offending leg.
        idx: usize,
    },
}

impl std::fmt::Display for LegError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => write!(f, "add a leg with `a`"),
            Self::ZeroQty { idx } => write!(f, "leg {}: zero quantity", idx + 1),
            Self::NoMark { idx } => write!(f, "leg {}: no mark", idx + 1),
            Self::StaleMark { idx } => write!(f, "leg {}: mark is stale", idx + 1),
        }
    }
}

/// A validated, committed multi-leg strategy (`docs/05-views-and-ux.md` §3, §4).
/// Built by [`PayoffBuilder::validate`] from a strategy that passed every check,
/// then enriched on commit with the payoff **geometry** — the expiration and t+0
/// curves, the shared price grid, and the break-even points — all sampled from
/// `optionstratlib` **off** the draw path, so the payoff screen (#27) draws the
/// cached series **without re-validating or re-pricing**.
/// `#[non_exhaustive]` so those cached fields stay a source-compatible addition; no
/// `Eq` because the cached [`GraphData`] carries display `f64` line widths.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct CommittedStrategy {
    /// The validated legs, in the order they were built.
    legs: Vec<BuilderLeg>,
    /// The shared underlying-price x-grid both curves and the t+0 refresh reuse
    /// (empty when the geometry could not be priced).
    grid: Vec<Positive>,
    /// The **frozen** commit-time positions (entry premium P0 per leg). The t+0
    /// tick refresh reprices these — mutating only the sampled underlying and the
    /// current IV — so the entry premium never re-reads the live mark and both
    /// curves share one cost basis (#27 SF-1). Empty when the geometry could not be
    /// priced.
    entry_positions: Vec<Position>,
    /// The expiration payoff as a single `GraphData::Series` (price → P&L).
    expiration: GraphData,
    /// The t+0 (mark-based) curve as a single `GraphData::Series` (price → P&L), or
    /// an empty series when a leg lacks a plausible IV (the "t+0 unavailable" state).
    tplus0: GraphData,
    /// The break-even underlying prices, read off the expiration series (#27).
    break_evens: Vec<Positive>,
    /// Whether the last geometry build/reprice was abandoned because the upstream
    /// `optionstratlib` pricing math **panicked** and the panic was contained (#131).
    /// A DIFFERENT state from "these legs cannot be priced" (which leaves the geometry
    /// empty with this flag clear), so the screen can say which one happened.
    compute_failed: bool,
}

impl CommittedStrategy {
    /// The validated legs, in build order.
    #[must_use]
    pub fn legs(&self) -> &[BuilderLeg] {
        &self.legs
    }

    /// The cached break-even underlying prices (empty when the curve could not be
    /// priced), overlaid as markers by the payoff screen (#27).
    #[must_use]
    pub fn break_even_points(&self) -> &[Positive] {
        &self.break_evens
    }

    /// Whether the cached, IV-independent **expiration** series carries renderable
    /// points — so the payoff screen can tell a t+0 curve that is unavailable purely
    /// for lack of a plausible IV (expiration still renders) from a strategy that
    /// cannot be priced at all (#27 SF-2). Exhaustive over [`GraphData`], no wildcard.
    #[must_use]
    fn has_expiration_curve(&self) -> bool {
        match &self.expiration {
            GraphData::Series(series) => !series.x.is_empty(),
            GraphData::MultiSeries(_) | GraphData::GraphSurface(_) => false,
        }
    }

    /// The cached payoff series for `curve` — the expiration or t+0
    /// `GraphData::Series` — exhaustive over [`CurveMode`] with no wildcard.
    #[must_use]
    fn active_graph(&self, curve: CurveMode) -> &GraphData {
        match curve {
            CurveMode::Expiration => &self.expiration,
            CurveMode::TPlus0 => &self.tplus0,
        }
    }

    /// Enrich a freshly-validated strategy with the payoff geometry sampled from
    /// the `store` snapshot, **off** the draw path. Leaves the geometry empty when
    /// the legs cannot be priced (a missing IV or a non-future expiry) — the
    /// screen then renders a deliberate "curve unavailable" state rather than a
    /// fabricated line — and records the DISTINCT contained-panic state (#131) when
    /// the upstream pricing math blew up, which carries its own message. Exhaustive
    /// over [`GeometryBuild`](payoff_build::GeometryBuild), no wildcard.
    fn populate_geometry(&mut self, store: &ChainStore) {
        match payoff_build::build_geometry(&self.legs, store) {
            payoff_build::GeometryBuild::Priced(geometry) => {
                self.grid = geometry.grid;
                self.entry_positions = geometry.entry_positions;
                self.expiration = geometry.expiration;
                self.tplus0 = geometry.tplus0;
                self.break_evens = geometry.break_evens;
                self.compute_failed = false;
            }
            // The legs cannot be priced: the geometry stays empty and the flag stays
            // clear, so the screen keeps its "needs marks and a future expiry" message.
            payoff_build::GeometryBuild::NotPriceable => self.compute_failed = false,
            // The upstream pricing math panicked (contained, #131): the geometry stays
            // empty AND the screen says the model failed, never "add a mark".
            payoff_build::GeometryBuild::ComputeFailed => self.compute_failed = true,
        }
    }

    /// Re-price the t+0 curve against the current `store` snapshot on the committed
    /// grid by repricing the **frozen** entry positions (the entry premium stays P0;
    /// only the sampled underlying and the current per-leg IV move), returning
    /// whether the series changed. A leg that loses its plausible IV flips the t+0
    /// curve to the empty "unavailable" series. Constructs **no** `CustomStrategy`
    /// and never touches the expiration curve or break-evens — the tick-path refresh
    /// (#27 SF-1/SF-2).
    fn refresh_tplus0(&mut self, store: &ChainStore) -> bool {
        if self.grid.is_empty() {
            return false;
        }
        // Exhaustive over [`TPlus0Build`](payoff_build::TPlus0Build), no wildcard: a
        // contained upstream panic (#131) drops the now-stale curve AND raises the
        // compute-failed flag, so the screen never keeps painting a curve whose reprice
        // blew up. A later successful reprice clears the flag again.
        let (series, compute_failed) = match payoff_build::rebuild_tplus0(
            &self.legs,
            store,
            &self.grid,
            &self.entry_positions,
        ) {
            payoff_build::TPlus0Build::Series(series) => (series, false),
            payoff_build::TPlus0Build::ComputeFailed => (payoff_build::empty_series(), true),
        };
        let changed = series != self.tplus0 || compute_failed != self.compute_failed;
        self.tplus0 = series;
        self.compute_failed = compute_failed;
        changed
    }

    /// Whether the cached geometry is missing because the upstream pricing math
    /// **panicked** (contained, #131) rather than because the legs could not be
    /// priced — the two states carry different messages on the payoff screen.
    #[must_use]
    fn curve_compute_failed(&self) -> bool {
        self.compute_failed
    }
}

/// The multi-leg payoff-builder state machine (`docs/05-views-and-ux.md` §3): an
/// ordered [`BuilderLeg`] list with a cursor, the current [`CurveMode`], the last
/// validation errors, and the committed strategy. It lives in the **application**
/// layer so the payoff screen (`src/ui/payoff.rs`) drives it through these methods
/// and reads it through the accessors — the UI never reaches into the fields
/// directly (`rules/global_rules.md`, inner fields private).
///
/// Every mutation that changes visible state bumps a monotonic
/// [`revision`](Self::revision) the render loop diffs to schedule a redraw, exactly
/// as it diffs the chain [`Selection`] (`docs/02-tui-architecture.md` §8): a builder
/// edit emits **no** [`AppEvent`], so the revision is how the loop learns the frame
/// changed.
#[derive(Debug, Clone)]
pub struct PayoffBuilder {
    /// The ordered legs being built.
    legs: Vec<BuilderLeg>,
    /// The cursor index into [`legs`](Self::legs); every in-place edit targets this
    /// leg. Kept in bounds by every mutator (or `0` when empty).
    cursor: usize,
    /// Which payoff curve the screen draws (`t` toggles); a view preference kept
    /// across a discard.
    curve: CurveMode,
    /// The validation errors from the last [`commit`](Self::commit) attempt, cleared
    /// on any edit. Rendered inline in the builder.
    errors: Vec<LegError>,
    /// The committed strategy (set by a successful [`commit`](Self::commit), cleared
    /// on any edit). `None` while the strategy is still being built.
    committed: Option<CommittedStrategy>,
    /// A monotonic edit counter the render loop diffs to schedule a redraw.
    revision: u64,
    /// A monotonic counter, **distinct** from [`revision`](Self::revision), bumped
    /// only when the **active** payoff `GraphData` changes (a commit, a curve
    /// toggle, a t+0 refresh that moved the series, or a clear) — never on a
    /// cursor-only edit that would over-invalidate the projection cache (#27).
    graph_revision: u64,
    /// The empty payoff series returned by [`active_graph_data`](Self::active_graph_data)
    /// while nothing is committed — the #23 adapter renders it as the deliberate
    /// "add a leg" empty projection.
    empty_graph: GraphData,
}

impl Default for PayoffBuilder {
    fn default() -> Self {
        Self {
            legs: Vec::new(),
            cursor: 0,
            curve: CurveMode::default(),
            errors: Vec::new(),
            committed: None,
            revision: 0,
            graph_revision: 0,
            empty_graph: payoff_build::empty_series(),
        }
    }
}

/// The default quantity of a freshly appended leg (one contract).
const DEFAULT_LEG_QTY: u32 = 1;

/// The maximum quantity a single leg's `+` can reach, so an increment can never
/// overflow `u32` (`rules/global_rules.md`, no `saturating_*`/`wrapping_*`). A
/// four-digit cap is far beyond any realistic hand-built strategy.
const MAX_LEG_QTY: u32 = 9_999;

impl PayoffBuilder {
    /// An empty payoff builder (no legs, cursor at `0`, expiration curve).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    // --- Accessors (the UI reads state; it never mutates the fields) ----------

    /// The ordered legs being built, borrowed for rendering.
    #[must_use]
    pub fn legs(&self) -> &[BuilderLeg] {
        &self.legs
    }

    /// Whether the builder has no legs (the empty state).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.legs.is_empty()
    }

    /// The cursor index into [`legs`](Self::legs) — always in bounds, or `0` when
    /// empty. The UI reads it with [`legs`](Self::legs)`.get(cursor)`, never an
    /// unchecked index.
    #[must_use]
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// The active payoff [`CurveMode`] (`t` toggles it).
    #[must_use]
    pub fn curve(&self) -> CurveMode {
        self.curve
    }

    /// The validation errors from the last commit attempt (empty when none),
    /// borrowed for the inline error render.
    #[must_use]
    pub fn errors(&self) -> &[LegError] {
        &self.errors
    }

    /// The committed strategy, or `None` while still building.
    #[must_use]
    pub fn committed(&self) -> Option<&CommittedStrategy> {
        self.committed.as_ref()
    }

    /// The monotonic edit counter the render loop diffs to schedule a redraw
    /// (`docs/02-tui-architecture.md` §8).
    #[must_use]
    pub fn revision(&self) -> u64 {
        self.revision
    }

    /// The monotonic **payoff-curve** revision, bumped only when the active payoff
    /// `GraphData` changes (`docs/05-views-and-ux.md` §4). Distinct from
    /// [`revision`](Self::revision): the ui view-cache (`src/ui/view.rs`) diffs
    /// this to decide when to re-project the payoff series **off** the draw path, so
    /// a cursor-only edit (which bumps `revision` but not this) never re-projects
    /// (#27).
    #[must_use]
    pub fn graph_revision(&self) -> u64 {
        self.graph_revision
    }

    /// The active payoff [`GraphData`] for the current [`CurveMode`] — the
    /// committed expiration or t+0 series, or a stored empty series while nothing
    /// is committed. The ui view-cache clones this off the draw path and projects
    /// it through `src/ui/graph.rs`; `draw` never builds it (#27).
    #[must_use]
    pub fn active_graph_data(&self) -> &GraphData {
        match self.committed.as_ref() {
            Some(committed) => committed.active_graph(self.curve),
            None => &self.empty_graph,
        }
    }

    /// The committed strategy's break-even underlying prices (empty while nothing
    /// is committed or the curve could not be priced), overlaid as markers by the
    /// payoff screen (#27).
    #[must_use]
    pub fn break_even_points(&self) -> &[Positive] {
        match self.committed.as_ref() {
            Some(committed) => committed.break_even_points(),
            None => &[],
        }
    }

    /// Whether the committed strategy's (IV-independent) **expiration** curve has
    /// renderable data. `false` while nothing is committed. The payoff screen reads
    /// this to render the honest "t+0 unavailable — no reliable IV" state when only
    /// the t+0 curve is missing while the expiration curve still renders (#27 SF-2).
    #[must_use]
    pub fn has_expiration_curve(&self) -> bool {
        match self.committed.as_ref() {
            Some(committed) => committed.has_expiration_curve(),
            None => false,
        }
    }

    /// Whether the committed strategy has no curve because the upstream
    /// `optionstratlib` pricing math **panicked** and the panic was contained
    /// (#131) — as opposed to the legs simply not being priceable, which leaves this
    /// `false`. `false` while nothing is committed. The payoff screen reads it to
    /// render the honest "the pricing model failed on these legs" state instead of
    /// telling a trader to fix marks that are already there.
    #[must_use]
    pub fn curve_compute_failed(&self) -> bool {
        match self.committed.as_ref() {
            Some(committed) => committed.curve_compute_failed(),
            None => false,
        }
    }

    // --- Mutations (each edit clears the stale commit + errors and bumps the
    //     revision when it changes visible state) ------------------------------
    //
    // These are `pub(crate)`: the builder is hand-driven only by the in-crate UI
    // (`payoff::handle_key`, the chain-side `a`, the driver), never by an external
    // lib consumer — so the semver-governed public surface stays the types, the read
    // accessors, and `validate`, not these mutators.

    /// Append a leg from the chain's focused `strike`/`style`, long by default, with
    /// the cursor tracking the newly added leg (`a`). Any prior commit/errors are
    /// stale once the strategy changes, so they are cleared.
    pub(crate) fn append(&mut self, strike: Positive, style: OptionStyle) {
        self.legs.push(BuilderLeg {
            strike,
            style,
            side: Side::Buy,
            qty: DEFAULT_LEG_QTY,
        });
        // The cursor tracks the leg just added; `len` is ≥ 1 here.
        self.cursor = self.legs.len().max(1) - 1;
        self.on_edit();
    }

    /// Remove the cursor leg (`x`), clamping the cursor to the new last leg (or `0`
    /// when the list becomes empty). A no-op when the cursor is out of bounds.
    pub(crate) fn remove_cursor(&mut self) {
        if self.cursor >= self.legs.len() {
            return;
        }
        let _ = self.legs.remove(self.cursor);
        if self.cursor >= self.legs.len() {
            // Removed the last leg: step the cursor back to the new last (or 0).
            self.cursor = self.legs.len().max(1) - 1;
        }
        self.on_edit();
    }

    /// Increase the cursor leg's quantity by one, capped at `MAX_LEG_QTY` so the
    /// add can never overflow (`+`). A no-op with no cursor leg or already at the cap.
    pub(crate) fn increment_qty(&mut self) {
        if let Some(leg) = self.legs.get_mut(self.cursor)
            && leg.qty < MAX_LEG_QTY
        {
            // `leg.qty < MAX_LEG_QTY < u32::MAX`, so `+ 1` cannot overflow.
            leg.qty += 1;
            self.on_edit();
        }
    }

    /// Decrease the cursor leg's quantity by one, floored at `0` (`-`). A `0`-qty leg
    /// is left in place (validation reports it) so the user can bump it back up or
    /// remove it. A no-op with no cursor leg or already at `0`.
    pub(crate) fn decrement_qty(&mut self) {
        if let Some(leg) = self.legs.get_mut(self.cursor)
            && leg.qty > 0
        {
            // `leg.qty > 0`, so `- 1` cannot underflow.
            leg.qty -= 1;
            self.on_edit();
        }
    }

    /// Toggle the cursor leg buy ⇄ sell (`s`). A no-op with no cursor leg.
    pub(crate) fn toggle_cursor_side(&mut self) {
        if let Some(leg) = self.legs.get_mut(self.cursor) {
            leg.side = leg.side.toggled();
            self.on_edit();
        }
    }

    /// Toggle the payoff curve expiration ⇄ t+0 (`t`). Selects which cached series
    /// the screen shows (#27); does not touch the built legs, so it keeps any
    /// commit/errors. Bumps [`graph_revision`](Self::graph_revision) **only when a
    /// strategy is committed** — the toggle switches the **active** payoff `GraphData`
    /// only then (with nothing committed both curves resolve to the same stored empty
    /// series), so it is symmetric with `clear`/`on_edit` and never triggers a
    /// redundant empty reprojection.
    pub(crate) fn toggle_curve(&mut self) {
        self.curve = self.curve.toggled();
        self.bump();
        if self.committed.is_some() {
            self.bump_graph();
        }
    }

    /// Re-price the committed strategy's t+0 curve against the current `store`
    /// snapshot, bumping [`graph_revision`](Self::graph_revision) only when the
    /// series changed. Called from the market-tick fold (never `draw`) and never
    /// reconstructs a `CustomStrategy` — a no-op with no committed strategy (#27).
    pub(crate) fn refresh_tplus0(&mut self, store: &ChainStore) {
        let Some(committed) = self.committed.as_mut() else {
            return;
        };
        if committed.refresh_tplus0(store) {
            self.bump_graph();
        }
    }

    /// Stage the committed strategy into the contained-pricing-panic state (#131):
    /// the empty geometry plus the compute-failed flag, exactly as
    /// [`CommittedStrategy::populate_geometry`] records a
    /// [`GeometryBuild::ComputeFailed`](payoff_build::GeometryBuild::ComputeFailed).
    /// The legs stay as committed, because a panicking build never touches them. A
    /// no-op with nothing committed.
    ///
    /// `#[cfg(test)]`, the live twin of [`LoadedReplay::force_payoff_compute_failed`]:
    /// since `optionstratlib 0.21` reports the cost-basis overflow as a typed error
    /// instead of panicking, no chain input can drive the upstream panic through
    /// `commit`, so the payoff screen's render of this state cannot otherwise be
    /// pinned by a `TestBackend` test. The builder's own boundary test drives a real
    /// panic through the production `build_geometry_with` seam; this only stages the
    /// resulting state for the render assertion.
    #[cfg(test)]
    pub(crate) fn force_curve_compute_failed(&mut self) {
        let Some(committed) = self.committed.as_mut() else {
            return;
        };
        committed.grid = Vec::new();
        committed.entry_positions = Vec::new();
        committed.expiration = payoff_build::empty_series();
        committed.tplus0 = payoff_build::empty_series();
        committed.break_evens = Vec::new();
        committed.compute_failed = true;
        self.bump_graph();
    }

    /// Discard the uncommitted strategy and return to the empty state (`Esc`): clear
    /// the legs, cursor, errors, and any commit. The [`CurveMode`] is a view
    /// preference and is **kept**. A no-op (no redraw) when already empty.
    pub(crate) fn discard(&mut self) {
        if self.legs.is_empty() && self.errors.is_empty() && self.committed.is_none() {
            return;
        }
        // Clearing a committed strategy returns the active payoff `GraphData` to the
        // empty series, so the projection cache must re-project.
        let had_committed = self.committed.is_some();
        self.legs.clear();
        self.cursor = 0;
        self.errors.clear();
        self.committed = None;
        self.bump();
        if had_committed {
            self.bump_graph();
        }
    }

    /// Validate the built strategy against the store's chain and, when valid,
    /// enrich it with the payoff geometry and store it (`Enter`); on failure store
    /// the per-leg errors and commit nothing. Returns whether the strategy
    /// committed.
    ///
    /// The whole `store` is borrowed immutably while `self` is borrowed mutably —
    /// the caller passes disjoint field borrows (`store` vs `payoff_builder`) — so
    /// the geometry build (the payoff series + break-evens, sampled from
    /// `optionstratlib`) runs here, **off** the draw path, and a successful commit
    /// bumps [`graph_revision`](Self::graph_revision) so the projection cache
    /// re-projects. Freshness reaches validation as data (#26): the store's
    /// stream-quote receipt clocks + the analytics reference instant, so a leg
    /// whose feed died is rejected with `StaleMark` instead of committing its
    /// cached midpoint. No I/O and no wall-clock read (#27).
    pub(crate) fn commit(&mut self, store: &ChainStore) -> bool {
        let clocks = store.quote_clocks();
        let as_of = store.analytics_as_of();
        match self.validate(store.chain(), &clocks, as_of) {
            Ok(mut strategy) => {
                strategy.populate_geometry(store);
                self.committed = Some(strategy);
                self.errors.clear();
                self.bump();
                self.bump_graph();
                true
            }
            Err(errors) => {
                self.committed = None;
                self.errors = errors;
                self.bump();
                false
            }
        }
    }

    /// Validate the built strategy against the current `chain` snapshot — a **pure**
    /// function of the builder and the chain, inventing and pricing nothing. The
    /// checks are: **≥ 1 leg**, **no zero-qty leg**, and **every leg has a
    /// known/fresh mark** ([`BuilderLeg::mark_in`], the `—`-not-`0` rule). The
    /// result is what the widget renders inline, so #27 draws the committed strategy
    /// without re-validating.
    ///
    /// # Errors
    ///
    /// Returns a [`Vec`] of [`LegError`] describing every failure: a lone
    /// [`LegError::Empty`] when there are no legs, else a [`LegError::ZeroQty`] /
    /// [`LegError::NoMark`] / [`LegError::StaleMark`] per offending leg (a leg
    /// can report more than one). Freshness arrives as **data** (`clocks`,
    /// `as_of` — the store's per-instrument stream-quote receipt snapshots and
    /// the pricing reference instant), so validation stays a pure read: a leg
    /// whose recorded clock is stale beyond `QUOTE_STALE_AFTER` is rejected with
    /// `StaleMark` rather than committing a cached midpoint from a dead feed; a
    /// leg with no recorded clock (poll-seeded) is not gated, mirroring the #24
    /// kernel convention.
    pub fn validate(
        &self,
        chain: &OptionChain,
        clocks: &QuoteClocks,
        as_of: DateTime<Utc>,
    ) -> Result<CommittedStrategy, Vec<LegError>> {
        if self.legs.is_empty() {
            return Err(vec![LegError::Empty]);
        }
        // The clock lookup keys on the chain's absolute-UTC expiry; a chain whose
        // expiry is not absolute (an adapter-seam invariant violation) simply
        // yields no key match, so freshness degrades to ungated rather than
        // panicking or blocking the commit.
        let expiration_utc = match chain.get_expiration() {
            Some(ExpirationDate::DateTime(dt)) => Some(dt),
            _ => None,
        };
        let mut errors = Vec::new();
        for (idx, leg) in self.legs.iter().enumerate() {
            if leg.qty == 0 {
                errors.push(LegError::ZeroQty { idx });
            }
            if leg.mark_in(chain).is_none() {
                errors.push(LegError::NoMark { idx });
            } else if let Some(expiration_utc) = expiration_utc {
                let key = InstrumentKey {
                    underlying: chain.symbol.clone(),
                    expiration_utc,
                    strike: leg.strike,
                    style: leg.style,
                };
                if let Some(received) = clocks.received(&key)
                    && quote_is_stale(received, as_of)
                {
                    errors.push(LegError::StaleMark { idx });
                }
            }
        }
        if errors.is_empty() {
            // The geometry is priced separately by [`commit`] (off the draw path);
            // `validate` stays a pure leg/mark check, so the returned strategy
            // carries empty geometry until enriched.
            Ok(CommittedStrategy {
                legs: self.legs.clone(),
                grid: Vec::new(),
                entry_positions: Vec::new(),
                expiration: payoff_build::empty_series(),
                tplus0: payoff_build::empty_series(),
                break_evens: Vec::new(),
                // No build has run yet, so nothing has panicked: the pricing-failed
                // state is only ever set by [`populate_geometry`] / [`refresh_tplus0`].
                compute_failed: false,
            })
        } else {
            Err(errors)
        }
    }

    /// Shared post-edit bookkeeping: a strategy edit invalidates the last commit and
    /// its errors, then bumps the revision so the loop redraws. Clearing a committed
    /// strategy also returns the active payoff `GraphData` to the empty series, so
    /// the projection cache is invalidated (only then, never on a cursor-only edit).
    fn on_edit(&mut self) {
        let had_committed = self.committed.is_some();
        self.committed = None;
        self.errors.clear();
        self.bump();
        if had_committed {
            self.bump_graph();
        }
    }

    /// Advance the redraw revision, wrapping to `0` on the (practically unreachable)
    /// `u64` overflow — `checked_add` avoids the banned `wrapping_add`, matching the
    /// tick counter (`docs/02-tui-architecture.md` §8).
    fn bump(&mut self) {
        self.revision = self.revision.checked_add(1).unwrap_or(0);
    }

    /// Advance the payoff-curve revision (the projection-cache invalidation signal),
    /// wrapping to `0` on the (practically unreachable) `u64` overflow.
    fn bump_graph(&mut self) {
        self.graph_revision = self.graph_revision.checked_add(1).unwrap_or(0);
    }
}

// ---------------------------------------------------------------------------
// SurfacePanel: the vol smile / Greek-curve / single-expiry-surface screen state.
// ---------------------------------------------------------------------------

/// Which of the three Surface-screen views is shown (#47,
/// `docs/05-views-and-ux.md` §4), cycled by `x`.
///
/// The screen spec calls `x` a smile ⇄ surface **toggle**; because #47 renders
/// **three** view families (the smile, a Greek curve, and the surface) the coherent
/// binding is a 3-step cycle `Smile → Curve → Surface → Smile`, whose two endpoints
/// are the smile and the surface. The #47 map's correction — that the 3D surface
/// `z`-axis is a Greek/Price, **never** IV — means the smile and the surface cannot
/// be two states of one axis; they are distinct views. A ChainView closed set,
/// fieldless, so `#[repr(u8)]`; defaults to [`Smile`](SurfaceView::Smile), the IV
/// artifact shown on the first frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum SurfaceView {
    /// The interpolated vol smile (IV vs strike).
    #[default]
    Smile,
    /// A single Greek / IV / Price curve vs strike (`g`/`G` selects the axis).
    Curve,
    /// The single-expiry Greek/Price surface over strike × volatility.
    Surface,
}

impl SurfaceView {
    /// The next view in the `Smile → Curve → Surface → Smile` cycle (`x`). Exhaustive
    /// with no wildcard arm.
    #[must_use]
    fn next(self) -> Self {
        match self {
            Self::Smile => Self::Curve,
            Self::Curve => Self::Surface,
            Self::Surface => Self::Smile,
        }
    }

    /// The short, color-independent label for the status/title.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Smile => "smile",
            Self::Curve => "curve",
            Self::Surface => "surface",
        }
    }
}

/// The Greek / IV / Price axis the Surface screen's curve and surface use (#47,
/// `docs/05-views-and-ux.md` §4), cycled by `g` (forward) / `G` (back). Maps to
/// `optionstratlib`'s [`BasicAxisTypes`].
///
/// A ChainView closed set, fieldless, so `#[repr(u8)]`; defaults to
/// [`Delta`](SurfaceAxis::Delta), the primary Greek. `Volatility` is a valid **curve**
/// axis (the per-leg IV curve) but not a **surface** axis — the 3D `z` is a
/// Greek/Price, never IV (the #47 map), so the surface build refuses it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum SurfaceAxis {
    /// Delta — the primary Greek.
    #[default]
    Delta,
    /// Gamma.
    Gamma,
    /// Theta.
    Theta,
    /// Vega.
    Vega,
    /// Implied volatility (a valid curve axis; refused for the surface).
    Volatility,
    /// The option price (Black-Scholes).
    Price,
}

impl SurfaceAxis {
    /// The cycle order for `g`/`G` (`docs/05-views-and-ux.md` §4).
    const ORDER: [SurfaceAxis; 6] = [
        SurfaceAxis::Delta,
        SurfaceAxis::Gamma,
        SurfaceAxis::Theta,
        SurfaceAxis::Vega,
        SurfaceAxis::Volatility,
        SurfaceAxis::Price,
    ];

    /// The next (`forward`) or previous axis in [`ORDER`](Self::ORDER), wrapping.
    /// `g` advances, `G` steps back — the concrete chord chooses, as the payoff
    /// `+`/`-` quantity chord does.
    #[must_use]
    fn cycled(self, forward: bool) -> Self {
        next_in_cycle(&Self::ORDER, self, forward).unwrap_or(self)
    }

    /// The `optionstratlib` [`BasicAxisTypes`] this axis maps to. Exhaustive with no
    /// wildcard arm.
    #[must_use]
    pub(crate) fn to_basic(self) -> BasicAxisTypes {
        match self {
            Self::Delta => BasicAxisTypes::Delta,
            Self::Gamma => BasicAxisTypes::Gamma,
            Self::Theta => BasicAxisTypes::Theta,
            Self::Vega => BasicAxisTypes::Vega,
            Self::Volatility => BasicAxisTypes::Volatility,
            Self::Price => BasicAxisTypes::Price,
        }
    }

    /// The short glyph/label for the screen title & axis (`Δ`/`Γ`/`Θ`/`ν`/`IV`/`price`).
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Delta => "Δ",
            Self::Gamma => "Γ",
            Self::Theta => "Θ",
            Self::Vega => "ν",
            Self::Volatility => "IV",
            Self::Price => "price",
        }
    }

    /// The ASCII metric name used to label the built `GraphData` (the chart legend),
    /// so the legend reads on a plain terminal without a Greek glyph.
    #[must_use]
    pub(crate) fn metric_name(self) -> &'static str {
        match self {
            Self::Delta => "delta",
            Self::Gamma => "gamma",
            Self::Theta => "theta",
            Self::Vega => "vega",
            Self::Volatility => "IV",
            Self::Price => "price",
        }
    }
}

/// The Surface screen's state and its **cached active geometry** (#47,
/// `docs/05-views-and-ux.md` §4): which view is shown, the active Greek axis, and the
/// one `GraphData` the screen currently renders — the smile, a Greek curve, or the
/// surface. Owned by [`LiveState`] and driven only by the in-crate UI
/// (`surface::handle_key`) and the market fold, never by an external lib consumer, so
/// the mutators are `pub(crate)`.
///
/// It mirrors [`PayoffBuilder`]'s two-revision scheme: [`revision`](Self::revision)
/// (bumped on any key that changes view/axis) is diffed by the render loop's view
/// signature to schedule a redraw, and [`graph_revision`](Self::graph_revision)
/// (bumped only when the active `GraphData` actually changes) is diffed by the ui view
/// cache to re-project **off** the draw path. The geometry is built by the off-draw
/// surface builder, never in `draw`.
#[derive(Debug, Clone)]
pub struct SurfacePanel {
    /// Which of the three views is shown (`x` cycles).
    view: SurfaceView,
    /// The active Greek/IV/Price axis (`g`/`G` cycles).
    axis: SurfaceAxis,
    /// The cached active `GraphData` — the smile / curve / surface the screen draws.
    /// Built off the draw path; the ui view cache projects it, `draw` never builds it.
    active: GraphData,
    /// The redraw revision the render loop's view signature diffs (bumped on a
    /// view/axis key).
    revision: u64,
    /// The projection-cache invalidation revision the ui view cache diffs (bumped only
    /// when [`active`](Self::active) actually changes).
    graph_revision: u64,
    /// Whether a market fold changed the chain **while the Surface screen was hidden**,
    /// so the cached geometry is stale relative to the store (#106). Set by
    /// [`mark_dirty`](Self::mark_dirty) on an off-screen fold and cleared by the next
    /// [`rebuild`](Self::rebuild); the fan-in never rebuilds an invisible panel — the
    /// switch-to-surface handler pays the cost once via [`rebuild_if_dirty`](Self::rebuild_if_dirty).
    dirty: bool,
}

impl SurfacePanel {
    /// A panel seeded on the default [`SurfaceView::Smile`] / [`SurfaceAxis::Delta`],
    /// with the smile built once from the seeded `store` (off the draw path) so the
    /// first frame renders real geometry or the deliberate "insufficient IV" state,
    /// never a blank.
    #[must_use]
    fn new(store: &ChainStore) -> Self {
        let view = SurfaceView::default();
        let axis = SurfaceAxis::default();
        let active = build_active(view, axis, store);
        Self {
            view,
            axis,
            active,
            revision: 0,
            graph_revision: 0,
            dirty: false,
        }
    }

    /// The active view (`x` cycles).
    #[must_use]
    pub fn view(&self) -> SurfaceView {
        self.view
    }

    /// The active Greek/IV/Price axis (`g`/`G` cycles).
    #[must_use]
    pub fn axis(&self) -> SurfaceAxis {
        self.axis
    }

    /// The cached active `GraphData` the ui view cache projects off the draw path;
    /// `draw` never builds it (#47).
    #[must_use]
    pub fn active_graph_data(&self) -> &GraphData {
        &self.active
    }

    /// The redraw revision the render loop's view signature diffs.
    #[must_use]
    pub fn revision(&self) -> u64 {
        self.revision
    }

    /// The projection-cache invalidation revision the ui view cache diffs to
    /// re-project the surface geometry off the draw path (#47).
    #[must_use]
    pub fn graph_revision(&self) -> u64 {
        self.graph_revision
    }

    /// Cycle the Greek axis (`g` forward / `G` back) and rebuild the active geometry
    /// against `store` — off the draw path. In the Smile view the axis is not shown,
    /// but it is still advanced so switching to the curve/surface reflects it.
    pub(crate) fn cycle_axis(&mut self, forward: bool, store: &ChainStore) {
        self.axis = self.axis.cycled(forward);
        self.bump();
        self.rebuild(store);
    }

    /// Step the view `Smile → Curve → Surface → Smile` (`x`) and rebuild the active
    /// geometry against `store` — off the draw path.
    pub(crate) fn cycle_view(&mut self, store: &ChainStore) {
        self.view = self.view.next();
        self.bump();
        self.rebuild(store);
    }

    /// Rebuild the active geometry against the current `store` snapshot on a
    /// data-changing market fold **while the Surface screen is active** (off the draw
    /// path). Bumps the graph revision only when the geometry moved.
    pub(crate) fn refresh(&mut self, store: &ChainStore) {
        self.rebuild(store);
    }

    /// Mark the cached geometry stale because the chain changed **while the Surface
    /// screen was hidden** (#106) — a cheap flag set on the fan-in path instead of a
    /// full geometry rebuild for an invisible panel. The rebuild is deferred to the
    /// switch-to-surface handler ([`rebuild_if_dirty`](Self::rebuild_if_dirty)).
    pub(crate) fn mark_dirty(&mut self) {
        self.dirty = true;
    }

    /// Rebuild the cached geometry **iff** an off-screen fold marked it dirty (#106) —
    /// run by the switch-to-surface handler so entering the Surface screen pays the
    /// deferred rebuild once, lazily, off the draw path. A no-op when already current.
    pub(crate) fn rebuild_if_dirty(&mut self, store: &ChainStore) {
        if self.dirty {
            self.rebuild(store);
        }
    }

    /// Rebuild `active` from the current `(view, axis, store)` and bump the graph
    /// revision only when it changed, so the view cache re-projects only on a real
    /// geometry change (the #27/#35 cache discipline). Clears the dirty flag — the
    /// cached geometry is now current with the store.
    fn rebuild(&mut self, store: &ChainStore) {
        let next = build_active(self.view, self.axis, store);
        if next != self.active {
            self.active = next;
            self.bump_graph();
        }
        self.dirty = false;
    }

    /// Advance the redraw revision, wrapping to `0` on the (practically unreachable)
    /// `u64` overflow.
    fn bump(&mut self) {
        self.revision = self.revision.checked_add(1).unwrap_or(0);
    }

    /// Advance the projection-cache invalidation revision, wrapping to `0` on the
    /// (practically unreachable) `u64` overflow.
    fn bump_graph(&mut self) {
        self.graph_revision = self.graph_revision.checked_add(1).unwrap_or(0);
    }
}

/// Build the active `GraphData` for a `(view, axis)` against `store`, dispatching to
/// the [`surface_build`] builders — off the draw path. Exhaustive over
/// [`SurfaceView`] with no wildcard arm.
#[must_use]
fn build_active(view: SurfaceView, axis: SurfaceAxis, store: &ChainStore) -> GraphData {
    match view {
        SurfaceView::Smile => surface_build::build_smile(store),
        SurfaceView::Curve => surface_build::build_curve(store, axis),
        SurfaceView::Surface => surface_build::build_surface(store, axis),
    }
}

/// A screen's load lifecycle (`docs/02-tui-architecture.md` §3,
/// `docs/05-views-and-ux.md` §6).
///
/// The `Empty`, `Stale`, `Not-supported`, and `Computed-Greeks` render states of
/// `docs/05` §6 are **derived** at draw time (from the store rows, the binding
/// health, and the declared capabilities), so they are not variants here; this
/// enum is the load/failure axis only. The retry **key** an [`Error`] shows
/// (`r` reconnect vs `R` re-discover) is chosen by the render/keymap layer
/// (#13/#14) from the mode, not stored here.
///
/// [`Error`]: ScreenLoad::Error
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ScreenLoad {
    /// First fetch / stream connecting — the screen renders its connecting state.
    #[default]
    Loading,
    /// The screen renders its body from the store (which may itself be empty).
    ///
    /// Producer note: the `Loading → Ready` transition is driven when the first
    /// chain lands — wired by the chain-matrix screen work (#18) off the store's
    /// populated state; this skeleton folds the store but does not yet flip
    /// `load`.
    Ready,
    /// A provider/fetch error — the screen renders the actionable message plus
    /// the mode's retry-key affordance (#13/#14).
    ///
    /// Producer note: no event in the current closed `AppEvent`/`MarketUpdate`
    /// set carries a provider-error message, so this state is not yet reachable
    /// by the fan-in. The error carrier that drives it lands with the live
    /// reconnect loop (#16), which will extend the closed set — a compile-fenced,
    /// source-compatible addition (every fold site is revisited by the compiler).
    Error {
        /// The actionable, non-secret error message to display.
        message: String,
    },
}

/// The status-bar model: provider health, clock, and mode
/// (`docs/02-tui-architecture.md` §3). A documented stub whose fields are
/// populated by the status line (#13/#14); `#[non_exhaustive]` so those fields
/// are a source-compatible addition.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct StatusLine;

// ---------------------------------------------------------------------------
// ReplayState: the bundle load state machine (v0.3 fills the internals).
// ---------------------------------------------------------------------------

/// Replay-mode state: the bundle directory, its load state machine, the active
/// screen, and the playback state (`docs/02-tui-architecture.md` §3). The
/// internals are filled by the v0.3 replay work; the shapes here are stable.
#[derive(Debug)]
pub struct ReplayState {
    /// The bundle directory (kept for reload via `R`).
    pub dir: PathBuf,
    /// The bundle load state machine.
    pub bundle: BundleLoad,
    /// The active Replay screen.
    pub screen: ReplayScreen,
    /// The playback state (paused / playing).
    pub play: Playback,
}

impl ReplayState {
    /// A replay state for a bundle directory: [`BundleLoad::Loading`], the
    /// default [`ReplayScreen::Replay`] screen, and paused playback. The load task
    /// ([`spawn_bundle_load`]) fills the bundle and delivers
    /// [`AppEvent::BundleLoaded`], folded by [`apply_load_result`](Self::apply_load_result).
    #[must_use]
    pub fn new(dir: PathBuf) -> Self {
        Self {
            dir,
            bundle: BundleLoad::Loading,
            screen: ReplayScreen::Replay,
            play: Playback::Paused,
        }
    }

    /// The loaded replay payload when the bundle is [`BundleLoad::Ready`], else
    /// `None` (still loading or in an error state). The replay screens (#35) read
    /// the bundle, cursor, and selection through this.
    #[must_use]
    pub fn loaded(&self) -> Option<&LoadedReplay> {
        match &self.bundle {
            BundleLoad::Ready(loaded) => Some(loaded),
            BundleLoad::Loading | BundleLoad::Error { .. } => None,
        }
    }

    /// Whether playback is currently running.
    #[must_use]
    pub fn is_playing(&self) -> bool {
        self.play.is_playing()
    }

    /// Fold the off-thread load result into the [`BundleLoad`] state machine: a
    /// success builds the timeline cursor and transitions to
    /// [`BundleLoad::Ready`]; a failure carries the actionable message into
    /// [`BundleLoad::Error`] (`R` retries). Either way playback resets to paused —
    /// a fresh bundle starts at the first step, a failed one has nothing to play.
    pub fn apply_load_result(&mut self, result: BundleLoadResult) {
        self.bundle = match result {
            BundleLoadResult::Loaded(bundle) => {
                BundleLoad::Ready(Box::new(LoadedReplay::new(*bundle)))
            }
            BundleLoadResult::Failed(message) => BundleLoad::Error { message },
        };
        self.play = Playback::Paused;
    }

    /// Reset to [`BundleLoad::Loading`] for a reload (`R`), so the load screen
    /// shows its connecting state while the data layer re-opens the bundle; the
    /// fresh cursor/selection arrive with the next [`apply_load_result`](Self::apply_load_result).
    pub fn begin_reload(&mut self) {
        self.bundle = BundleLoad::Loading;
        self.play = Playback::Paused;
    }

    /// Move the timeline cursor by `seek` (an in-memory index move, #33), returning
    /// whether the cursor position changed (so the caller sets `dirty`). A no-op
    /// until the bundle is [`BundleLoad::Ready`]. On a real move it rebuilds the
    /// cached equity series (bumping its revision) and re-clamps the drill-down
    /// selection to the fills still visible at the new head (#35) — all off the draw
    /// path.
    pub fn seek(&mut self, seek: SeekTo) -> bool {
        let BundleLoad::Ready(loaded) = &mut self.bundle else {
            return false;
        };
        // Deref the `Box` once so the cursor (mut) and the bundle (shared) are
        // disjoint field borrows of a plain `LoadedReplay`.
        let loaded: &mut LoadedReplay = loaded;
        let before = loaded.cursor;
        loaded.cursor.seek(seek, &loaded.bundle);
        if loaded.cursor == before {
            return false;
        }
        loaded.on_cursor_moved();
        true
    }

    /// Step the drill-down [`selection`](LoadedReplay::selection) to the previous
    /// (`forward == false`) or next (`forward == true`) fill visible at the head
    /// (`docs/05-views-and-ux.md` §5, #35), returning whether the selection changed
    /// (so the driver's view-signature diff schedules a redraw). A no-op until the
    /// bundle is [`BundleLoad::Ready`]; an empty fills list clears the selection to
    /// the deliberate empty state. An in-memory selection move — never I/O.
    pub fn step_fill(&mut self, forward: bool) -> bool {
        let BundleLoad::Ready(loaded) = &mut self.bundle else {
            return false;
        };
        let loaded: &mut LoadedReplay = loaded;
        loaded.step_fill(forward)
    }

    /// Fold a play/pause/speed control into the [`Playback`] state, returning
    /// whether the state changed (so the caller sets `dirty`). Play/pause toggles;
    /// the speed keys adjust an already-**playing** speed only (a no-op while
    /// paused, since paused playback carries no speed).
    pub fn apply_control(&mut self, control: ReplayControl) -> bool {
        let next = match control {
            ReplayControl::PlayPause => self.play.toggled(PlaybackSpeed::default()),
            ReplayControl::SpeedFaster => match self.play {
                Playback::Playing { speed } => Playback::playing(speed.faster()),
                Playback::Paused => return false,
            },
            ReplayControl::SpeedSlower => match self.play {
                Playback::Playing { speed } => Playback::playing(speed.slower()),
                Playback::Paused => return false,
            },
        };
        if next != self.play {
            self.play = next;
            true
        } else {
            false
        }
    }

    /// Advance the play-head one playback tick: while playing over a `Ready`
    /// bundle, seek forward by the speed quantum; the cursor clamps at `end_step`,
    /// so playback **stops at the tape end and never wraps** and this **auto-pauses**
    /// there (so the render loop parks instead of spinning on a no-op advance,
    /// `docs/04-replay-mode.md` §4). Returns whether a redraw is needed. A no-op
    /// while paused or not yet `Ready`.
    pub fn advance_playback(&mut self) -> bool {
        if !self.play.is_playing() {
            return false;
        }
        let play = self.play;
        let (moved, at_end) = match &mut self.bundle {
            BundleLoad::Ready(loaded) => {
                // Deref the `Box` once so the cursor (mut) and the bundle (shared)
                // are disjoint field borrows of a plain `LoadedReplay`.
                let loaded: &mut LoadedReplay = loaded;
                let before = loaded.cursor;
                loaded.cursor.advance_playback(play, &loaded.bundle);
                let moved = loaded.cursor != before;
                if moved {
                    // Rebuild the cached equity series + re-clamp the selection off
                    // the draw path, exactly as a manual seek does (#35).
                    loaded.on_cursor_moved();
                }
                (moved, loaded.cursor.is_at_end())
            }
            BundleLoad::Loading | BundleLoad::Error { .. } => return false,
        };
        if at_end {
            self.play = Playback::Paused;
        }
        moved || at_end
    }
}

/// The bundle load state machine (`docs/02-tui-architecture.md` §3): loading,
/// loaded, or a retryable error, so startup / failure / retry / success are all
/// representable. `R` re-issues a [`Command::ReloadBundle`].
///
/// The transitions are driven by [`AppEvent::BundleLoaded`] (the off-thread load
/// result, folded by [`ReplayState::apply_load_result`]): `Loading → Ready` on a
/// valid bundle, `Loading → Error` on a [`BundleError`](crate::BundleError). A
/// reload (`R`) resets to `Loading` via [`ReplayState::begin_reload`].
#[derive(Debug)]
pub enum BundleLoad {
    /// The bundle is being opened and validated on the load worker.
    Loading,
    /// The bundle loaded successfully. Boxed so the large loaded payload does not
    /// bloat the small `Loading`/`Error` variants and keeps the `Mode` enum small.
    Ready(Box<LoadedReplay>),
    /// The bundle failed to load — an actionable [`crate::BundleError`] message;
    /// `R` retries.
    Error {
        /// The actionable, non-secret bundle-error message to display.
        message: String,
    },
}

/// The loaded replay payload — the fully materialised bundle, its timeline cursor
/// over the integer `step` clock, the currently drilled-into fill, and the cached
/// equity geometry the screen renders (`docs/02-tui-architecture.md` §3,
/// `docs/04-replay-mode.md` §4, `docs/05-views-and-ux.md` §5).
///
/// Built by [`LoadedReplay::new`] from a [`LoadedBundle`] the load worker decoded
/// off the render thread. The equity `GraphData` + peak-drawdown figure are rebuilt
/// **off the draw path** on every cursor move, bumping
/// [`equity_revision`](Self::equity_revision) the ui view-cache diffs to re-project
/// (#35). `#[non_exhaustive]` so later replay fields stay a source-compatible addition.
#[derive(Debug)]
#[non_exhaustive]
pub struct LoadedReplay {
    /// The decoded, validated bundle (the four tables + manifest), read-only.
    pub bundle: LoadedBundle,
    /// The scrub position over the bundle's integer `step` clock (#33). Moved only
    /// through [`ReplayState::seek`] / [`ReplayState::advance_playback`], never
    /// per frame.
    pub cursor: TimelineCursor,
    /// The drilled-into fill, or `None` before any drill-down / after the selected
    /// fill scrubs out of the as-of window (`,` / `.` step it, #35).
    pub selection: Option<Fill>,
    /// The cached index of [`selection`](Self::selection) within the as-of fills tape
    /// (oldest → newest), or `None` when nothing is selected (#118). Maintained **off
    /// the draw path** in lock-step with the selection — set by [`step_fill`](Self::step_fill)
    /// and recomputed by [`reclamp_selection`](Self::reclamp_selection) on a cursor move
    /// — so the fills-list draw resolves the scroll anchor in O(1) instead of rescanning
    /// the whole visible tape every frame.
    selected_ix: Option<usize>,
    /// The off-draw equity geometry (the step → equity **cents** series up to the head
    /// plus the exact peak drawdown), seeded from the run's opening capital and
    /// maintained incrementally on a forward cursor move / rebuilt on a backward seek
    /// (#23/#35). Private — the screen reads the projection + the `Copy` peak figure,
    /// never this state.
    geometry: EquityGeometry,
    /// A monotonic counter bumped whenever [`geometry`](Self::geometry) is rebuilt
    /// (load + every cursor move), diffed by the ui view-cache to re-project the equity
    /// series only when it actually changed (#35, the payoff-cache pattern).
    equity_revision: u64,
    /// The expiration payoff `GraphData::Series` of the **open position at the head**
    /// (#49), built off the draw path from the cached open set on every cursor move and
    /// projected by the ui view-cache. Private — the payoff screen reads the projection,
    /// never this `GraphData`. An empty series is the "flat at this step" state.
    payoff_graph: GraphData,
    /// The payoff-at-head header figures the draw reads: the break-even prices, the
    /// current net mark-to-market P&L in **integer cents**, and the open-leg count —
    /// all resolved off the draw path so the panel scans no positions per frame (#49).
    payoff_head: ReplayPayoffHead,
    /// A monotonic counter bumped whenever [`payoff_graph`](Self::payoff_graph) is
    /// rebuilt (load + every cursor move), diffed by the ui view-cache to re-project the
    /// payoff series only when the open set at the head actually changed (#49).
    payoff_revision: u64,
}

/// The replay payoff-at-head **header** figures the panel renders (#49): the
/// break-even underlying prices, the current net mark-to-market P&L in **integer
/// cents** (`None` when the head is flat), and the count of open legs at the head.
///
/// Built off the draw path from the cursor's cached open set (never a per-frame scan)
/// and read by the replay payoff panel's `draw_replay` at the render edge, where the
/// cents are formatted to `$` and the break-evens overlaid as markers.
#[derive(Debug, Clone, PartialEq)]
pub struct ReplayPayoffHead {
    /// The break-even underlying prices, overlaid as markers (empty when flat).
    break_evens: Vec<Positive>,
    /// The current net mark-to-market P&L in **integer cents** (signed), or `None`
    /// when the head is flat (no open leg).
    mark_pnl_cents: Option<i64>,
    /// The number of open legs at the head (`0` ⇒ the "flat at this step" state).
    open_legs: usize,
    /// Whether the curve is missing because the upstream `optionstratlib` pricing math
    /// **panicked** and the panic was contained (#131) — a DIFFERENT state from "the
    /// open legs could not be priced", which leaves this `false`.
    curve_compute_failed: bool,
}

impl ReplayPayoffHead {
    /// The break-even underlying prices to overlay as markers (empty when flat).
    #[must_use]
    pub fn break_even_points(&self) -> &[Positive] {
        &self.break_evens
    }

    /// The current net mark-to-market P&L in **integer cents** (signed), or `None`
    /// when the head is flat. Formatted to `$` only at the render edge (#49).
    #[must_use]
    pub fn mark_pnl_cents(&self) -> Option<i64> {
        self.mark_pnl_cents
    }

    /// The number of open legs at the head — `0` is the "flat at this step" state the
    /// panel renders as its deliberate empty state (before any curve).
    #[must_use]
    pub fn open_legs(&self) -> usize {
        self.open_legs
    }

    /// Whether the payoff-at-head curve is missing because the upstream
    /// `optionstratlib` pricing math **panicked** and the panic was contained
    /// (#131) — as opposed to the open legs simply not being priceable, which leaves
    /// this `false`. The panel reads it to render the honest "the pricing model
    /// failed on these legs" state; the open-leg count and the mark P&L above stay
    /// truthful either way (they never enter the pricing math).
    #[must_use]
    pub fn curve_compute_failed(&self) -> bool {
        self.curve_compute_failed
    }
}

impl LoadedReplay {
    /// Build the loaded payload from `bundle`, resolving the timeline cursor at the
    /// first step (`docs/01-domain-model.md` §10) with no drill-down selection and the
    /// equity geometry built once for step 0 (off the draw path). The drawdown running
    /// peak is seeded from the run's **opening capital** (`config.initial_capital`, the
    /// #29 reconcile) so a step-0 loss shows its true drawdown; a manifest whose capital
    /// is unreadable (an already-validated bundle always yields it) falls back to the
    /// first equity row — the prior behaviour, never a fabricated figure.
    #[must_use]
    pub fn new(bundle: LoadedBundle) -> Self {
        let cursor = TimelineCursor::new(&bundle);
        let visible = cursor.visible_equity(&bundle);
        let seed_cents = opening_capital_cents(&bundle)
            .or_else(|| bundle.equity.first().map(|point| point.equity_cents))
            .unwrap_or(0);
        let geometry = EquityGeometry::build(visible, seed_cents);
        let (payoff_graph, payoff_head) = build_payoff_at_head(&cursor, &bundle);
        Self {
            bundle,
            cursor,
            selection: None,
            selected_ix: None,
            geometry,
            equity_revision: 0,
            payoff_graph,
            payoff_head,
            payoff_revision: 0,
        }
    }

    /// The cached equity `GraphData` (step → cents), for the ui view-cache to
    /// project off the draw path. Not read by `draw`.
    #[must_use]
    pub fn equity_graph(&self) -> &GraphData {
        self.geometry.graph()
    }

    /// The equity-series revision the ui view-cache diffs to schedule a re-project
    /// (#35): monotonic within this bundle, bumped on every cursor move.
    #[must_use]
    pub fn equity_revision(&self) -> u64 {
        self.equity_revision
    }

    /// The peak drawdown up to the head in **integer cents** (`<= 0`), measured against
    /// the opening-capital-seeded running peak and formatted to `$` at the render edge
    /// (#35). A `Copy` read — never a per-frame equity scan.
    #[must_use]
    pub fn peak_drawdown_cents(&self) -> i64 {
        self.geometry.peak_drawdown_cents()
    }

    /// The cached payoff-at-head `GraphData` (the expiration payoff of the open
    /// position at the head, #49), for the ui view-cache to project off the draw path.
    /// Not read by `draw`.
    #[must_use]
    pub fn payoff_graph(&self) -> &GraphData {
        &self.payoff_graph
    }

    /// The payoff-at-head header figures (break-evens, mark P&L in cents, open-leg
    /// count) the panel renders, resolved off the draw path (#49).
    #[must_use]
    pub fn payoff_head(&self) -> &ReplayPayoffHead {
        &self.payoff_head
    }

    /// The payoff-series revision the ui view-cache diffs to schedule a re-project
    /// (#49): monotonic within this bundle, bumped on every cursor move.
    #[must_use]
    pub fn payoff_revision(&self) -> u64 {
        self.payoff_revision
    }

    /// The `Copy` identity key of the drill-down selection — `(step, order_id,
    /// fill_seq)`, the fill's unique sort key — or `None` when nothing is selected.
    /// The driver's view-signature diffs this to turn a `,` / `.` selection move into
    /// a redraw (#35).
    #[must_use]
    pub fn selection_key(&self) -> Option<(u32, u64, u32)> {
        self.selection.as_ref().map(fill_key)
    }

    /// The cached index of the drill-down selection within the as-of fills tape
    /// (oldest → newest), or `None` when nothing is selected (#118). Resolved off the
    /// draw path (on selection step / cursor move) so the fills-list draw reads its
    /// scroll anchor in O(1) instead of rescanning the whole visible tape per frame.
    #[must_use]
    pub fn selected_fill_index(&self) -> Option<usize> {
        self.selected_ix
    }

    /// Rebuild the cached equity + payoff geometry and re-clamp the drill-down
    /// selection after the cursor moved — the single off-draw refresh both
    /// [`ReplayState::seek`] and [`ReplayState::advance_playback`] run (#35, #49).
    fn on_cursor_moved(&mut self) {
        self.rebuild_equity();
        self.rebuild_payoff();
        self.reclamp_selection();
    }

    /// Rebuild the payoff-at-head geometry from the cursor's cached open set and bump
    /// its revision, off the draw path (#49). The open set is resolved **here** (a
    /// seek-time `O(k log k)` pass), never per frame in `draw`.
    fn rebuild_payoff(&mut self) {
        let (graph, head) = build_payoff_at_head(&self.cursor, &self.bundle);
        self.payoff_graph = graph;
        self.payoff_head = head;
        self.payoff_revision = self.payoff_revision.checked_add(1).unwrap_or(0);
    }

    /// Put the cached payoff-at-head into the **contained-panic** state (#131): the
    /// empty curve plus the compute-failed flag, exactly as
    /// [`build_payoff_at_head`] produces it from
    /// [`ReplayCurve::ComputeFailed`](replay_payoff_build::ReplayCurve::ComputeFailed).
    /// The header figures are left untouched, because a panicking curve build never
    /// touches them.
    ///
    /// `#[cfg(test)]` — and deliberately the ONLY test-only seam in this change —
    /// because no valid `PositionRow` can drive the upstream panic (every money column
    /// is bounded by the checked cents→`Positive` seam, see
    /// [`replay_payoff_build::build_with`]), so the panel's render of this state cannot
    /// otherwise be pinned by a `TestBackend` test. The builder's own boundary test
    /// drives the real panic through the production `build_with` path; this only
    /// stages the resulting state for the render assertion.
    #[cfg(test)]
    pub(crate) fn force_payoff_compute_failed(&mut self) {
        self.payoff_graph = payoff_build::empty_series();
        self.payoff_head.break_evens = Vec::new();
        self.payoff_head.curve_compute_failed = true;
        self.payoff_revision = self.payoff_revision.checked_add(1).unwrap_or(0);
    }

    /// Refresh the cached equity geometry from the cursor's as-of slice and bump the
    /// revision, off the draw path. A **forward** move (the slice grew or held) folds
    /// only the newly-visible tail into the running peak and appends its samples —
    /// `O(new points)` on the playback/step path, never a full rescan. A **backward**
    /// seek (the slice shrank) cannot extend, so it rebuilds from the opening-capital
    /// seed — `O(visible)`, but only on an arbitrary jump, not per tick. Either way the
    /// result is a pure function of the bundle + cursor (incremental == full).
    fn rebuild_equity(&mut self) {
        let visible = self.cursor.visible_equity(&self.bundle);
        if visible.len() >= self.geometry.raw_len() {
            self.geometry.extend_forward(visible);
        } else {
            self.geometry.rebuild(visible);
        }
        self.equity_revision = self.equity_revision.checked_add(1).unwrap_or(0);
    }

    /// Drop the drill-down selection when its fill is no longer visible at the head
    /// (the head scrubbed back past it) — "the selection follows the visible fills at
    /// the cursor" (#35) — and otherwise refresh the cached selection index against the
    /// new as-of tape (#118). A no-op when nothing is selected. The position scan runs
    /// **here**, off the draw path on a cursor move, so the fills-list draw never
    /// rescans the tape per frame.
    fn reclamp_selection(&mut self) {
        let key = match &self.selection {
            Some(fill) => fill_key(fill),
            None => {
                self.selected_ix = None;
                return;
            }
        };
        match self
            .cursor
            .visible_fills(&self.bundle)
            .iter()
            .position(|fill| fill_key(fill) == key)
        {
            Some(ix) => self.selected_ix = Some(ix),
            None => {
                self.selection = None;
                self.selected_ix = None;
            }
        }
    }

    /// Step the selection to the previous / next visible fill, returning whether it
    /// changed. From no selection, either direction lands on the most recent visible
    /// fill (nearest the head); thereafter `forward` walks toward the head and back
    /// steps toward the run start, clamped at both ends. An empty fills list clears
    /// the selection (the deliberate empty state). Index arithmetic is checked — no
    /// unchecked index, no `saturating_*`.
    fn step_fill(&mut self, forward: bool) -> bool {
        let (next, next_ix) = {
            let visible = self.cursor.visible_fills(&self.bundle);
            match visible.len().checked_sub(1) {
                // Empty fills list: clear any stale selection.
                None => (None, None),
                Some(last) => {
                    let current = self.selection.as_ref().and_then(|fill| {
                        let key = fill_key(fill);
                        visible.iter().position(|f| fill_key(f) == key)
                    });
                    let idx = match (current, forward) {
                        (None, _) => last,
                        (Some(i), true) => i.checked_add(1).map_or(last, |j| j.min(last)),
                        // Step back one, clamped at the run start. `Some(0)` matches
                        // first, so the `i - 1` arm has `i >= 1` and never underflows —
                        // no `saturating_sub` needed (`rules/global_rules.md`).
                        (Some(0), false) => 0,
                        (Some(i), false) => i - 1,
                    };
                    (visible.get(idx).cloned(), Some(idx))
                }
            }
        };
        if selection_key(self.selection.as_ref()) == selection_key(next.as_ref()) {
            return false;
        }
        // Cache the resolved index in lock-step with the selection (#118): `next_ix` is
        // `Some(idx)` exactly when `next` is `Some(fill)`, so the fills-list draw reads
        // its scroll anchor without a per-frame position scan.
        self.selected_ix = next.as_ref().and(next_ix);
        self.selection = next;
        true
    }
}

/// The run's opening capital in **integer cents** (the drawdown baseline), projected
/// once from the validated manifest's `config.initial_capital` via the typed
/// [`CapitalConfig`](crate::replay::CapitalConfig) (#29). `None` only when the manifest
/// capital is unreadable — an already-validated bundle always yields `Some`, so the
/// `None` fallback is reserved for synthetic in-memory bundles. Money stays integer
/// cents; no `f64`, no panic (the checked `u64 → i64` narrowing is discarded to `None`
/// rather than propagated, since the seed has an honest first-equity-row fallback).
#[must_use]
fn opening_capital_cents(bundle: &LoadedBundle) -> Option<i64> {
    bundle.manifest.capital_config().ok()?.capital_cents().ok()
}

/// The `Copy` identity key of a fill — its unique `(step, order_id, fill_seq)` sort
/// key (`docs/04-replay-mode.md` §2.2) — used to locate and compare the drill-down
/// selection without cloning a whole [`Fill`].
#[must_use]
fn fill_key(fill: &Fill) -> (u32, u64, u32) {
    (fill.step, fill.order_id, fill.fill_seq)
}

/// The optional [`fill_key`] of an optional selection, for a cheap change check.
#[must_use]
fn selection_key(selection: Option<&Fill>) -> Option<(u32, u64, u32)> {
    selection.map(fill_key)
}

/// Resolve the open-position set at the head (the #33 contract — a seek-time `Vec`,
/// never a per-frame call) and build the cached payoff-at-head geometry from it (#49):
/// the expiration payoff `GraphData::Series` and the header figures. Off the draw
/// path — run only on load and on a cursor move.
///
/// Exhaustive over [`ReplayCurve`](replay_payoff_build::ReplayCurve) with no wildcard:
/// a contained upstream panic (#131) yields the empty series AND raises the panel's
/// compute-failed flag, so the "the pricing model failed" state stays distinguishable
/// from the honest "these legs could not be priced" one.
#[must_use]
fn build_payoff_at_head(
    cursor: &TimelineCursor,
    bundle: &LoadedBundle,
) -> (GraphData, ReplayPayoffHead) {
    let open = cursor.open_positions(bundle);
    let head_ts_ns = cursor.head_equity(bundle).map(|point| point.ts_ns);
    let geometry = replay_payoff_build::build(&open, head_ts_ns);
    let (graph, break_evens, curve_compute_failed) = match geometry.curve {
        replay_payoff_build::ReplayCurve::Priced { graph, break_evens } => {
            (graph, break_evens, false)
        }
        replay_payoff_build::ReplayCurve::ComputeFailed => {
            (payoff_build::empty_series(), Vec::new(), true)
        }
    };
    let head = ReplayPayoffHead {
        break_evens,
        mark_pnl_cents: geometry.mark_pnl_cents,
        open_legs: geometry.open_legs,
        curve_compute_failed,
    };
    (graph, head)
}

// ---------------------------------------------------------------------------
// Capability-driven screen reachability (reads capabilities, never ProviderId).
// ---------------------------------------------------------------------------

/// Whether a [`LiveScreen`] is reachable for a declared [`ProviderCapabilities`]
/// set (`docs/02-tui-architecture.md` §3, `docs/03-data-providers.md` §11.4).
///
/// Reads capability dimensions only — there is **no `match` on [`ProviderId`]**,
/// so a built-in and an externally registered provider are gated identically.
/// The `Tab`/`S-Tab` skip and number-key hint that consume this land in #14.
#[must_use]
pub fn is_screen_reachable(screen: LiveScreen, caps: &ProviderCapabilities) -> bool {
    match screen {
        // The chain and its payoff need a chain to exist.
        LiveScreen::Chain | LiveScreen::Payoff => chain_present(caps.chain),
        // The depth ladder needs an order book.
        LiveScreen::Depth => caps.depth,
        // The vol smile/surface needs IV, i.e. some Greeks source.
        LiveScreen::Surface => greeks_available(caps.greeks),
    }
}

/// Whether the provider produces a chain at all. Exhaustive over
/// [`ChainCapability`] (not `matches!`) so a new variant forces this gate to
/// decide how it degrades (`CLAUDE.md` "Key Decisions").
fn chain_present(chain: ChainCapability) -> bool {
    match chain {
        ChainCapability::Native | ChainCapability::Assemble | ChainCapability::Partial => true,
        ChainCapability::None => false,
    }
}

/// Whether IV/Greeks are available (provided or computed locally). Exhaustive
/// over [`GreeksCapability`] so a new variant forces this gate to decide.
fn greeks_available(greeks: GreeksCapability) -> bool {
    match greeks {
        GreeksCapability::Provided | GreeksCapability::ComputedLocally => true,
        GreeksCapability::None => false,
    }
}

/// The more-capable of two Greeks sources for the capability union:
/// `Provided > ComputedLocally > None`. Exhaustive so a new variant forces a
/// decision.
fn max_greeks(a: GreeksCapability, b: GreeksCapability) -> GreeksCapability {
    match (a, b) {
        (GreeksCapability::Provided, _) | (_, GreeksCapability::Provided) => {
            GreeksCapability::Provided
        }
        (GreeksCapability::ComputedLocally, _) | (_, GreeksCapability::ComputedLocally) => {
            GreeksCapability::ComputedLocally
        }
        (GreeksCapability::None, GreeksCapability::None) => GreeksCapability::None,
    }
}

/// Whether a merge outcome changed what the screen would render (an applied patch
/// or a newly-refused overlay leg both do; a buffered or dropped update does
/// not).
fn merged(outcome: MergeOutcome) -> bool {
    match outcome {
        MergeOutcome::Applied | MergeOutcome::OverlayRefused => true,
        MergeOutcome::Buffered
        | MergeOutcome::DroppedOutOfOrder
        | MergeOutcome::DroppedTombstoned
        | MergeOutcome::DroppedCrossed => false,
    }
}

// ---------------------------------------------------------------------------
// Screen navigation policy (number-key slots, cycle order, reachability, names).
// ---------------------------------------------------------------------------

/// The live screens in number-key / cycle order (`docs/05-views-and-ux.md` §2).
const LIVE_SCREEN_ORDER: [LiveScreen; 4] = [
    LiveScreen::Chain,
    LiveScreen::Depth,
    LiveScreen::Surface,
    LiveScreen::Payoff,
];

/// The replay screens in number-key / cycle order (`docs/05-views-and-ux.md` §2).
const REPLAY_SCREEN_ORDER: [ReplayScreen; 2] = [ReplayScreen::Replay, ReplayScreen::Payoff];

/// The live screen a number-key slot selects (`docs/05-views-and-ux.md` §2):
/// `1`=Chain, `2`=Depth, `3`=Surface, `4`=Payoff; any other slot is unbound.
#[must_use]
fn live_screen_for_slot(slot: u8) -> Option<LiveScreen> {
    match slot {
        1 => Some(LiveScreen::Chain),
        2 => Some(LiveScreen::Depth),
        3 => Some(LiveScreen::Surface),
        4 => Some(LiveScreen::Payoff),
        _ => None,
    }
}

/// The replay screen a number-key slot selects (`docs/05-views-and-ux.md` §2):
/// `1`=Replay, `2`=Payoff (the payoff-at-head panel, #49); any other slot is unbound.
#[must_use]
fn replay_screen_for_slot(slot: u8) -> Option<ReplayScreen> {
    match slot {
        1 => Some(ReplayScreen::Replay),
        2 => Some(ReplayScreen::Payoff),
        _ => None,
    }
}

/// Whether a [`ReplayScreen`] is reachable in the current build
/// (`docs/05-views-and-ux.md` §2.1). Both replay screens are reachable from **v0.5**:
/// the equity/attribution/drill-down screen, and the **payoff-at-head** panel (#49),
/// which renders the payoff of the open position at the scrub head. This is a
/// build/version gate, not a capability or [`ProviderId`] gate (replay has no live
/// provider) — the payoff panel degrades to its "flat at this step" empty state when
/// no position is open at the head, so it is always navigable.
#[must_use]
pub fn is_replay_screen_reachable(screen: ReplayScreen) -> bool {
    match screen {
        ReplayScreen::Replay | ReplayScreen::Payoff => true,
    }
}

/// The display name of a live screen for the keybar and hints
/// (`docs/05-views-and-ux.md` §8).
#[must_use]
pub(crate) fn live_screen_name(screen: LiveScreen) -> &'static str {
    match screen {
        LiveScreen::Chain => "Chain",
        LiveScreen::Depth => "Depth",
        LiveScreen::Surface => "Surface",
        LiveScreen::Payoff => "Payoff",
    }
}

/// The display name of a replay screen for the keybar and hints
/// (`docs/05-views-and-ux.md` §8).
#[must_use]
pub(crate) fn replay_screen_name(screen: ReplayScreen) -> &'static str {
    match screen {
        ReplayScreen::Replay => "Replay",
        ReplayScreen::Payoff => "Payoff",
    }
}

/// The keybar hint for an unavailable replay screen (`docs/05-views-and-ux.md`
/// §2.1). Both replay screens are reachable from v0.5 (#49), so this is now purely
/// defensive — it keeps the number-key switch total and wildcard-free without ever
/// flashing in practice.
#[must_use]
fn replay_unavailable_hint(screen: ReplayScreen) -> String {
    match screen {
        ReplayScreen::Replay | ReplayScreen::Payoff => "screen not available".to_owned(),
    }
}

/// The next element after `current` in `items`, wrapping, moving `forward` or
/// backward (`docs/05-views-and-ux.md` §2). Returns `None` when `items` is empty
/// or `current` is absent. Uses `.get()` + modular indexing — no unchecked index
/// and no `saturating_*`/`wrapping_*` arithmetic.
#[must_use]
fn next_in_cycle<T: PartialEq + Copy>(items: &[T], current: T, forward: bool) -> Option<T> {
    let idx = items.iter().position(|item| *item == current)?;
    let len = items.len();
    if len == 0 {
        return None;
    }
    let next = if forward {
        (idx + 1) % len
    } else {
        (idx + len - 1) % len
    };
    items.get(next).copied()
}

/// The current wall-clock instant from `std`'s clock (chrono's `clock` feature is
/// off, so `Utc::now` is unavailable) — the decay reference the tick handler stamps
/// onto [`App::now`] so `draw` reads a cached instant and never touches a wall clock
/// itself (`docs/02-tui-architecture.md` §7). Clamps a pathological system time to
/// the representable range and never `unwrap`s.
#[must_use]
fn now_utc() -> DateTime<Utc> {
    let since = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or(std::time::Duration::ZERO);
    let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX);
    DateTime::<Utc>::from_timestamp(secs, since.subsec_nanos()).unwrap_or(DateTime::<Utc>::MIN_UTC)
}

/// The index (ascending strike order) of the strike nearest spot — the chain
/// screen's `◀ATM` row and default scroll anchor, cached on [`LiveState`] and
/// recomputed off-draw on a poll so `draw` never rescans the ladder. `None` for an
/// empty chain. Uses only `optionstratlib` chain types, so it is a domain-facing
/// projection the application layer may compute (no dependency on `src/ui`).
#[must_use]
pub(crate) fn atm_index_of(chain: &OptionChain) -> Option<usize> {
    let spot = chain.underlying_price.to_dec();
    let mut best: Option<(usize, Decimal)> = None;
    for (idx, od) in chain.options.iter().enumerate() {
        let diff = (od.strike_price.to_dec() - spot).abs();
        let better = match best {
            Some((_, best_diff)) => diff < best_diff,
            None => true,
        };
        if better {
            best = Some((idx, diff));
        }
    }
    best.map(|(idx, _)| idx)
}

/// Shared, crate-internal test constructors for a fully-formed [`App`] in any
/// reachable state, used by both this module's tests and the `src/ui` render-loop
/// tests (#13). Kept minimal and self-contained so a render test can enumerate
/// every reachable mode × screen × load state without reaching into a provider.
#[cfg(test)]
pub(crate) mod tests_support {
    use std::collections::BTreeMap;
    use std::path::PathBuf;
    use std::time::Duration;

    use optionstratlib::chains::OptionData;
    use optionstratlib::chains::chain::OptionChain;
    use optionstratlib::prelude::Positive;
    use tokio::sync::mpsc;

    use super::{
        App, LiveScreen, LiveState, Mode, ReplayScreen, ReplayState, ScreenLoad, SourceBinding,
    };
    use crate::chain::{
        AliasCatalog, ChainFetch, ChainSource, ChainStore, ExpirySource, ProviderId, StreamHealth,
    };
    use crate::config::ThemeChoice;
    use crate::event::{BundleLoadResult, Command};
    use crate::providers::{
        ChainCapability, ChainPollCapability, GreeksCapability, ProviderCapabilities,
    };
    use crate::replay::{
        BundleManifest, EquityPoint, ExecMode, Fill, GreeksAttribution, LoadedBundle, PositionSide,
        SUPPORTED_SCHEMA,
    };

    const EXP: i64 = 1_700_000_000;

    /// A minimal manifest for an in-memory test bundle — the cursor never reads it;
    /// this only satisfies [`LoadedBundle`].
    fn replay_manifest() -> BundleManifest {
        let mut row_counts = BTreeMap::new();
        let _ = row_counts.insert("fills".to_owned(), 0u64);
        let _ = row_counts.insert("equity_curve".to_owned(), 0u64);
        let _ = row_counts.insert("positions".to_owned(), 0u64);
        let _ = row_counts.insert("greeks_attribution".to_owned(), 0u64);
        BundleManifest {
            schema: SUPPORTED_SCHEMA.to_owned(),
            run_id: "run-test".to_owned(),
            created_utc: "2026-07-17T00:00:00Z".to_owned(),
            code_version: "0.3.0".to_owned(),
            lockfile_sha256: "deadbeef".to_owned(),
            seed: 1,
            config: serde_json::json!({ "capital_cents": 1_000_000 }),
            strategy: serde_json::json!({}),
            data_source: serde_json::json!({}),
            metrics: serde_json::json!({}),
            row_counts,
        }
    }

    fn equity_point(step: u32) -> EquityPoint {
        EquityPoint {
            step,
            ts_ns: 1_700_000_000_000_000_000 + i64::from(step),
            cash_cents: 1_000,
            position_value_cents: 0,
            equity_cents: 1_000,
            drawdown: 0.0,
        }
    }

    /// A tiny in-memory bundle with a dense equity curve over `0..n_steps` (so the
    /// cursor's `end_step` is `n_steps - 1`); the other tables stay empty. Used to
    /// exercise the seek/playback folds without a Parquet round-trip.
    #[must_use]
    pub(crate) fn loaded_bundle(n_steps: u32) -> LoadedBundle {
        LoadedBundle {
            manifest: replay_manifest(),
            fills: Vec::new(),
            equity: (0..n_steps).map(equity_point).collect(),
            positions: Vec::new(),
            greeks: Vec::new(),
        }
    }

    /// A replay [`App`] with a `Ready` bundle of `n_steps` steps (cursor at the
    /// start, paused), plus its command-channel receiver — for the seek/playback
    /// folds and the driver's replay end-to-end dispatch.
    #[must_use]
    pub(crate) fn ready_replay_app(n_steps: u32) -> (App, mpsc::Receiver<Command>) {
        let (tx, rx) = mpsc::channel::<Command>(8);
        let mut replay = ReplayState::new(PathBuf::from("/bundle"));
        replay.apply_load_result(BundleLoadResult::Loaded(Box::new(loaded_bundle(n_steps))));
        let mut app = App::new(Mode::Replay(replay), ThemeChoice::Auto, tx);
        app.mark_drawn();
        (app, rx)
    }

    fn replay_fill(step: u32, order_id: u64) -> Fill {
        Fill {
            step,
            ts_ns: 1_700_000_000_000_000_000 + i64::from(step),
            strategy_run_id: "run-test".to_owned(),
            trade_id: order_id,
            position_id: order_id,
            order_id,
            fill_seq: 0,
            underlying: "BTC".to_owned(),
            expiration_ns: 1_735_286_400_000_000_000,
            contract_id: "v1:BTC:1735286400000000000:6000000:C".to_owned(),
            strike_cents: 6_000_000,
            style: optionstratlib::OptionStyle::Call,
            side: PositionSide::Long,
            quantity: 1,
            price_cents: 235,
            fees_cents: 30,
            slippage_cents: -15,
            mode: ExecMode::Realistic,
        }
    }

    fn greeks_row(step: u32) -> GreeksAttribution {
        GreeksAttribution {
            step,
            ts_ns: 1_700_000_000_000_000_000 + i64::from(step),
            theta_pnl_cents: 193_000,
            delta_pnl_cents: -42_000,
            vega_pnl_cents: 31_000,
            spread_capture_cents: 18_000,
            fees_cents: 500,
            residual_cents: -6_000,
        }
    }

    /// A `Ready` replay [`App`] carrying fills + greeks over `0..n_steps` (fills at
    /// steps 0, 0, 1), with the cursor at the **last** step so every fill is visible —
    /// for the drill-down (`,` / `.`) dispatch + render tests.
    #[must_use]
    pub(crate) fn ready_replay_app_with_fills(n_steps: u32) -> (App, mpsc::Receiver<Command>) {
        let (tx, rx) = mpsc::channel::<Command>(8);
        let bundle = LoadedBundle {
            manifest: replay_manifest(),
            fills: vec![replay_fill(0, 10), replay_fill(0, 11), replay_fill(1, 20)],
            equity: (0..n_steps).map(equity_point).collect(),
            positions: Vec::new(),
            greeks: (0..n_steps).map(greeks_row).collect(),
        };
        let mut replay = ReplayState::new(PathBuf::from("/bundle"));
        replay.apply_load_result(BundleLoadResult::Loaded(Box::new(bundle)));
        let _ = replay.seek(crate::event::SeekTo::Step(u32::MAX));
        let mut app = App::new(Mode::Replay(replay), ThemeChoice::Auto, tx);
        app.mark_drawn();
        (app, rx)
    }

    #[track_caller]
    fn pid(id: &str) -> ProviderId {
        match ProviderId::new(id) {
            Ok(p) => p,
            Err(e) => panic!("expected a valid provider id `{id}`: {e}"),
        }
    }

    #[track_caller]
    fn utc(secs: i64) -> chrono::DateTime<chrono::Utc> {
        match chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0) {
            Some(t) => t,
            None => panic!("invalid test timestamp: {secs}"),
        }
    }

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

    fn row(strike: f64) -> OptionData {
        let mut od = OptionData {
            strike_price: pos(strike),
            call_bid: Some(pos(1.0)),
            call_ask: Some(pos(1.2)),
            put_bid: Some(pos(2.0)),
            put_ask: Some(pos(2.4)),
            implied_volatility: pos(0.5),
            ..Default::default()
        };
        od.set_mid_prices();
        od
    }

    fn chain_with(strikes: &[f64]) -> OptionChain {
        let mut chain = OptionChain::new("BTC", pos(60_000.0), "2025-06-27".to_owned(), None, None);
        for strike in strikes {
            let _ = chain.options.insert(row(*strike));
        }
        chain
    }

    fn store() -> ChainStore {
        ChainStore::seed(
            ChainFetch::new(
                chain_with(&[60_000.0]),
                ExpirySource::new("BTC", utc(EXP), pid("deribit")),
                AliasCatalog::new(),
            ),
            ChainSource::Merged,
            Duration::from_secs(2),
            utc(EXP),
        )
    }

    /// A Deribit-like capability set: assembled chain, depth, provided Greeks — so
    /// every live screen is reachable and every screen body can be exercised.
    fn full_caps() -> ProviderCapabilities {
        ProviderCapabilities::builder()
            .chain(ChainCapability::Assemble)
            .depth(true)
            .greeks(GreeksCapability::Provided)
            .chain_poll(ChainPollCapability::Poll {
                interval_hint_secs: 2,
            })
            .build()
    }

    /// A live [`App`] forced onto `screen` in `load` with `help_open == help`,
    /// plus the receiver half of its command channel so a test can assert on
    /// emitted [`Command`]s. The screen is set on the `pub` field directly (the
    /// reachability gate is proven separately, #9) so any screen can be rendered.
    #[must_use]
    pub(crate) fn live_app(
        screen: LiveScreen,
        load: ScreenLoad,
        help: bool,
    ) -> (App, mpsc::Receiver<Command>) {
        let (tx, rx) = mpsc::channel::<Command>(8);
        let mut live = LiveState::new(
            SourceBinding::new(pid("deribit"), full_caps(), StreamHealth::Live),
            store(),
        );
        live.screen = screen;
        live.load = load;
        let mut app = App::new(Mode::Live(live), ThemeChoice::Auto, tx);
        app.help_open = help;
        app.mark_drawn();
        (app, rx)
    }

    /// A replay [`App`] forced onto `screen` with `help_open == help`, plus its
    /// command-channel receiver.
    #[must_use]
    pub(crate) fn replay_app(screen: ReplayScreen, help: bool) -> (App, mpsc::Receiver<Command>) {
        let (tx, rx) = mpsc::channel::<Command>(8);
        let mut replay = ReplayState::new(PathBuf::from("/bundle"));
        replay.screen = screen;
        let mut app = App::new(Mode::Replay(replay), ThemeChoice::Auto, tx);
        app.help_open = help;
        app.mark_drawn();
        (app, rx)
    }

    /// A live [`App`] in a given state, dropping the command receiver — for render
    /// tests that never assert on commands.
    #[must_use]
    pub(crate) fn live_app_on(screen: LiveScreen, load: ScreenLoad, help: bool) -> App {
        live_app(screen, load, help).0
    }

    /// A live [`App`] on the default [`LiveScreen::Chain`] screen bound to a source
    /// with the given `capabilities`, dropping the command receiver — for the
    /// reachability-skip / number-key-hint tests, which need a provider that lacks
    /// a capability (e.g. depth).
    #[must_use]
    pub(crate) fn live_app_caps(capabilities: ProviderCapabilities) -> App {
        let (tx, _rx) = mpsc::channel::<Command>(8);
        let live = LiveState::new(
            SourceBinding::new(pid("deribit"), capabilities, StreamHealth::Live),
            store(),
        );
        let mut app = App::new(Mode::Live(live), ThemeChoice::Auto, tx);
        app.mark_drawn();
        app
    }

    /// A replay [`App`] in a given state, dropping the command receiver.
    #[must_use]
    pub(crate) fn replay_app_on(screen: ReplayScreen, help: bool) -> App {
        replay_app(screen, help).0
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
    use optionstratlib::OptionStyle;
    use optionstratlib::chains::OptionData;
    use optionstratlib::chains::chain::OptionChain;
    use optionstratlib::prelude::Positive;
    use tokio::sync::mpsc;

    use super::tests_support::{loaded_bundle, ready_replay_app};
    use super::{
        App, BundleLoad, HINT_TICKS, KeyRoute, LegFocus, LiveScreen, LiveState, Mode,
        OverlayBinding, Playback, ReplayScreen, ReplayState, ScreenLoad, SourceBinding,
        is_screen_reachable,
    };
    use crate::chain::{
        AliasCatalog, ChainFetch, ChainSnapshot, ChainSource, ChainStore, ExpirySource, Instrument,
        MarketUpdate, ProviderId, QuoteUpdate, StreamHealth,
    };
    use crate::chain::{ContractSpecFingerprint, ExerciseStyle, InstrumentKey, SettlementStyle};
    use crate::config::ThemeChoice;
    use crate::event::{AppEvent, BundleLoadResult, Command, ReplayControl, SeekTo};
    use crate::providers::{
        ChainCapability, ChainPollCapability, GreeksCapability, ProviderCapabilities,
    };
    use crate::replay::PlaybackSpeed;

    const EXP: i64 = 1_700_000_000;

    // --- Test constructors (no unwrap/expect/indexing per the ruleset) -------

    #[track_caller]
    fn pid(id: &str) -> ProviderId {
        match ProviderId::new(id) {
            Ok(p) => p,
            Err(e) => panic!("expected a valid provider id `{id}`, got: {e}"),
        }
    }

    #[track_caller]
    fn utc(secs: i64) -> chrono::DateTime<chrono::Utc> {
        match chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0) {
            Some(t) => t,
            None => panic!("invalid test timestamp: {secs}"),
        }
    }

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

    fn refresh() -> std::time::Duration {
        std::time::Duration::from_secs(2)
    }

    fn spec() -> ContractSpecFingerprint {
        ContractSpecFingerprint {
            contract_multiplier: 1,
            settlement: SettlementStyle::Cash,
            exercise: ExerciseStyle::European,
            quote_currency: "USD".to_owned(),
            venue_product_code: "BTC".to_owned(),
        }
    }

    fn ikey(strike: f64, style: OptionStyle) -> InstrumentKey {
        InstrumentKey {
            underlying: "BTC".to_owned(),
            expiration_utc: utc(EXP),
            strike: pos(strike),
            style,
        }
    }

    fn instrument(provider: &str, strike: f64, style: OptionStyle) -> Instrument {
        Instrument {
            key: ikey(strike, style),
            provider: pid(provider),
            native_symbol: format!("BTC-{strike}-{}", style.as_str()),
            stream_symbol: None,
            spec: spec(),
        }
    }

    fn quote(
        provider: &str,
        strike: f64,
        style: OptionStyle,
        bid: Option<f64>,
        ask: Option<f64>,
        received: i64,
    ) -> QuoteUpdate {
        QuoteUpdate {
            instrument: instrument(provider, strike, style),
            bid: bid.map(pos),
            ask: ask.map(pos),
            last: None,
            bid_size: None,
            ask_size: None,
            event_time: None,
            received_time: utc(received),
        }
    }

    fn row(strike: f64) -> OptionData {
        let mut od = OptionData {
            strike_price: pos(strike),
            call_bid: Some(pos(1.0)),
            call_ask: Some(pos(1.2)),
            put_bid: Some(pos(2.0)),
            put_ask: Some(pos(2.4)),
            implied_volatility: pos(0.5),
            ..Default::default()
        };
        od.set_mid_prices();
        od
    }

    fn chain_with(strikes: &[f64]) -> OptionChain {
        let mut chain = OptionChain::new("BTC", pos(60_000.0), "2025-06-27".to_owned(), None, None);
        for strike in strikes {
            let _ = chain.options.insert(row(*strike));
        }
        chain
    }

    fn fetch(strikes: &[f64], provider: &str) -> ChainFetch {
        ChainFetch::new(
            chain_with(strikes),
            ExpirySource::new("BTC", utc(EXP), pid(provider)),
            AliasCatalog::new(),
        )
    }

    fn store(strikes: &[f64], provider: &str) -> ChainStore {
        ChainStore::seed(
            fetch(strikes, provider),
            ChainSource::Merged,
            refresh(),
            utc(EXP),
        )
    }

    /// Capabilities for a Deribit-like source: assembled chain, depth, provided
    /// Greeks.
    fn full_caps() -> ProviderCapabilities {
        ProviderCapabilities::builder()
            .chain(ChainCapability::Assemble)
            .depth(true)
            .greeks(GreeksCapability::Provided)
            .chain_poll(ChainPollCapability::Poll {
                interval_hint_secs: 2,
            })
            .build()
    }

    fn source_binding(provider: &str, caps: ProviderCapabilities) -> SourceBinding {
        SourceBinding::new(pid(provider), caps, StreamHealth::Live)
    }

    /// A live app over a seeded store, plus the receiver half of its command
    /// channel so tests can assert on emitted [`Command`]s.
    fn live_app(caps: ProviderCapabilities) -> (App, mpsc::Receiver<Command>) {
        let (tx, rx) = mpsc::channel::<Command>(8);
        let live = LiveState::new(
            source_binding("deribit", caps),
            store(&[60_000.0], "deribit"),
        );
        let mut app = App::new(Mode::Live(live), ThemeChoice::Auto, tx);
        app.mark_drawn();
        (app, rx)
    }

    fn replay_app(dir: &str) -> (App, mpsc::Receiver<Command>) {
        let (tx, rx) = mpsc::channel::<Command>(8);
        let mut app = App::new(
            Mode::Replay(ReplayState::new(PathBuf::from(dir))),
            ThemeChoice::Auto,
            tx,
        );
        app.mark_drawn();
        (app, rx)
    }

    #[track_caller]
    fn live(app: &App) -> &LiveState {
        match &app.mode {
            Mode::Live(live) => live,
            Mode::Replay(_) => panic!("expected a live app"),
        }
    }

    #[track_caller]
    fn key(code: KeyCode) -> AppEvent {
        AppEvent::Key(KeyEvent::new(code, KeyModifiers::NONE))
    }

    #[test]
    fn test_send_command_on_a_closed_channel_is_surfaced_not_silently_dropped() {
        let (app, rx) = live_app(full_caps());
        let mut app = app;
        assert_eq!(app.commands_dropped, 0, "healthy steady state");
        // Close the channel: the data layer is gone.
        drop(rx);
        app.send_command(Command::Reconnect);
        assert_eq!(
            app.commands_dropped, 1,
            "a dropped recovery command must be counted, never silently swallowed"
        );
        app.send_command(Command::Rediscover);
        assert_eq!(app.commands_dropped, 2);
    }

    // --- dirty: mutating vs idle ---------------------------------------------

    #[test]
    fn test_app_new_starts_dirty_so_first_frame_draws() {
        let (tx, _rx) = mpsc::channel::<Command>(8);
        let live = LiveState::new(
            source_binding("deribit", full_caps()),
            store(&[60_000.0], "deribit"),
        );
        let app = App::new(Mode::Live(live), ThemeChoice::Auto, tx);
        assert!(app.dirty);
    }

    #[test]
    fn test_on_event_tick_idle_does_not_set_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        // A ready chain on a live feed is a non-motion (idle) state; a tick must not
        // force a redraw so the render loop parks.
        match &mut app.mode {
            Mode::Live(live) => live.load = ScreenLoad::Ready,
            Mode::Replay(_) => panic!("expected a live app"),
        }
        app.on_event(AppEvent::Tick);
        assert!(
            !app.dirty,
            "an idle non-motion tick must not force a redraw"
        );
    }

    #[test]
    fn test_on_event_tick_in_motion_sets_dirty_to_animate_spinner() {
        // The default live state is `Loading` (a motion state, the initial connect),
        // so a tick must set `dirty` to advance the spinner — otherwise it freezes
        // and reads as a hang (`docs/05-views-and-ux.md` §7).
        let (mut app, _rx) = live_app(full_caps());
        assert!(matches!(
            &app.mode,
            Mode::Live(live) if matches!(live.load, ScreenLoad::Loading)
        ));
        app.on_event(AppEvent::Tick);
        assert!(app.dirty, "a motion-state tick must redraw the spinner");
    }

    #[test]
    fn test_status_hint_decays_after_n_ticks_not_immediately() {
        // A flashed hint stays visible for a readable minimum: it survives the next
        // tick (no near-zero flash) and clears only once its lifetime elapses.
        let (mut app, _rx) = live_app(full_caps());
        // Put the app in a non-motion state so only the hint drives redraws here.
        match &mut app.mode {
            Mode::Live(live) => live.load = ScreenLoad::Ready,
            Mode::Replay(_) => panic!("expected a live app"),
        }
        app.set_status_hint("Depth not available on deribit".to_owned());
        // One tick: the hint is still showing and an intermediate countdown tick does
        // not force a redraw.
        app.mark_drawn();
        app.on_event(AppEvent::Tick);
        assert!(
            app.status_hint.is_some(),
            "the hint must survive at least one tick, not flash near-zero"
        );
        assert!(!app.dirty, "an intermediate countdown tick does not redraw");
        // Keep ticking (clearing dirty each time) until the hint decays; the tick that
        // clears it dirties the frame so the keybar redraws without the hint.
        let mut cleared = false;
        for _ in 0..u32::from(HINT_TICKS) + 2 {
            app.mark_drawn();
            app.on_event(AppEvent::Tick);
            if app.status_hint.is_none() {
                assert!(app.dirty, "the decaying tick that clears the hint redraws");
                cleared = true;
                break;
            }
        }
        assert!(cleared, "the hint decays within its lifetime");
    }

    #[test]
    fn test_on_event_resize_sets_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        app.on_event(AppEvent::Resize(100, 30));
        assert!(app.dirty);
    }

    #[test]
    fn test_mark_drawn_clears_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        app.on_event(AppEvent::Resize(100, 30));
        assert!(app.dirty);
        app.mark_drawn();
        assert!(!app.dirty);
    }

    // --- Market fold: quote / chain / health ---------------------------------

    #[test]
    fn test_on_event_market_quote_applied_folds_into_store_and_sets_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        let update = MarketUpdate::Quote(quote(
            "deribit",
            60_000.0,
            OptionStyle::Call,
            Some(1.4),
            Some(1.6),
            EXP + 100,
        ));
        app.on_event(AppEvent::Market(update));
        assert!(app.dirty);
        // The store row patched to the new quote.
        let patched = live(&app)
            .store
            .chain()
            .options
            .iter()
            .find(|o| o.strike_price == pos(60_000.0))
            .map(|o| o.call_bid);
        assert_eq!(patched, Some(Some(pos(1.4))));
    }

    #[test]
    fn test_on_event_market_quote_dropped_crossed_does_not_set_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        // ask < bid on the seeded strike -> DroppedCrossed -> no visible change.
        let update = MarketUpdate::Quote(quote(
            "deribit",
            60_000.0,
            OptionStyle::Call,
            Some(2.0),
            Some(1.5),
            EXP + 100,
        ));
        app.on_event(AppEvent::Market(update));
        assert!(!app.dirty);
    }

    #[test]
    fn test_on_event_market_quote_unknown_strike_buffered_does_not_set_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        // A strike absent from the chain is buffered pending a poll, not rendered.
        let update = MarketUpdate::Quote(quote(
            "deribit",
            99_000.0,
            OptionStyle::Call,
            Some(1.0),
            Some(1.2),
            EXP + 100,
        ));
        app.on_event(AppEvent::Market(update));
        assert!(!app.dirty);
    }

    #[test]
    fn test_on_event_market_chain_snapshot_applies_poll_and_sets_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        // A re-poll introducing a new strike (61000) and dropping the old (60000).
        let snapshot = ChainSnapshot {
            chain_key: (pid("deribit"), "BTC".to_owned(), utc(EXP)),
            chain: chain_with(&[61_000.0]),
            aliases: AliasCatalog::new(),
            source: ChainSource::Merged,
            health: StreamHealth::Live,
            last_full_poll: Some(utc(EXP + 200)),
        };
        app.on_event(AppEvent::Market(MarketUpdate::Chain(snapshot)));
        assert!(app.dirty);
        assert!(live(&app).store.contains_strike(pos(61_000.0)));
        assert!(!live(&app).store.contains_strike(pos(60_000.0)));
    }

    #[test]
    fn test_on_event_market_chain_snapshot_without_poll_time_is_noop() {
        let (mut app, _rx) = live_app(full_caps());
        let snapshot = ChainSnapshot {
            chain_key: (pid("deribit"), "BTC".to_owned(), utc(EXP)),
            chain: chain_with(&[61_000.0]),
            aliases: AliasCatalog::new(),
            source: ChainSource::Merged,
            health: StreamHealth::Live,
            last_full_poll: None,
        };
        app.on_event(AppEvent::Market(MarketUpdate::Chain(snapshot)));
        assert!(!app.dirty);
        // Structure unchanged: the original strike remains, the new one absent.
        assert!(live(&app).store.contains_strike(pos(60_000.0)));
        assert!(!live(&app).store.contains_strike(pos(61_000.0)));
    }

    // --- ATM cache: computed off-draw at construction and refreshed on a poll --

    #[test]
    fn test_atm_index_of_finds_nearest_strike() {
        let chain = chain_with(&[50_000.0, 59_000.0, 70_000.0]);
        // spot 60000 -> nearest is 59000 at index 1.
        assert_eq!(super::atm_index_of(&chain), Some(1));
        assert_eq!(
            super::atm_index_of(&OptionChain::new(
                "BTC",
                pos(1.0),
                "x".to_owned(),
                None,
                None
            )),
            None
        );
    }

    #[test]
    fn test_live_state_caches_atm_index_and_refreshes_on_poll() {
        // The cache is seeded off-draw at construction and only recomputed when a
        // poll changes the ladder — draw reads it without rescanning the strikes.
        let (tx, _rx) = mpsc::channel::<Command>(8);
        let state = LiveState::new(
            source_binding("deribit", full_caps()),
            store(&[58_000.0, 60_000.0, 62_000.0], "deribit"),
        );
        // spot 60000 -> nearest is 60000 at index 1.
        assert_eq!(state.atm_index(), Some(1), "seeded from the initial chain");
        let mut app = App::new(Mode::Live(state), ThemeChoice::Auto, tx);
        // A quote patches a row but never moves the ATM, so the cache is unchanged.
        app.on_event(AppEvent::Market(MarketUpdate::Quote(quote(
            "deribit",
            60_000.0,
            OptionStyle::Call,
            Some(1.4),
            Some(1.6),
            EXP + 100,
        ))));
        assert_eq!(
            live(&app).atm_index(),
            Some(1),
            "a quote does not move the ATM"
        );
        // A poll that re-lists strikes around a new spot refreshes the cache.
        let snapshot = ChainSnapshot {
            chain_key: (pid("deribit"), "BTC".to_owned(), utc(EXP)),
            chain: chain_with(&[59_000.0, 60_000.0]),
            aliases: AliasCatalog::new(),
            source: ChainSource::Merged,
            health: StreamHealth::Live,
            last_full_poll: Some(utc(EXP + 200)),
        };
        app.on_event(AppEvent::Market(MarketUpdate::Chain(snapshot)));
        // The new ladder [59000, 60000] with spot 60000 -> nearest is index 1.
        assert_eq!(
            live(&app).atm_index(),
            Some(1),
            "the poll refreshed the cached ATM index"
        );
    }

    #[test]
    fn test_on_event_market_depth_folds_to_store_but_no_redraw_off_screen() {
        // The store path exists: the ladder IS folded into the depth store. But the
        // default screen is `Chain` (not `Depth`), so the update is not for the
        // visible selected contract and must not force a redraw.
        let (mut app, _rx) = live_app(full_caps());
        let ladder = crate::chain::DepthLadder {
            instrument: instrument("deribit", 60_000.0, OptionStyle::Call),
            bids: Vec::new(),
            asks: Vec::new(),
            event_time: None,
            received_time: utc(EXP + 100),
            change_id: None,
        };
        app.on_event(AppEvent::Market(MarketUpdate::Depth(ladder)));
        assert!(!app.dirty, "an off-screen depth fold does not redraw");
        assert_eq!(
            live(&app).depth_store.len(),
            1,
            "the ladder was still folded into the store (the store path exists)",
        );
    }

    /// A chain at realistic BTC premiums over `strikes` (IV 0.5), so the vol smile
    /// builds real geometry whose shape depends on the strike ladder — a different
    /// strike set yields a different smile (a different x-domain / point count),
    /// regardless of any local IV recompute. The fixture for the deferred-surface-
    /// rebuild test (#106).
    fn surface_store_strikes(strikes: &[f64]) -> ChainStore {
        let mut chain = OptionChain::new("BTC", pos(60_000.0), "2025-06-27".to_owned(), None, None);
        for &strike in strikes {
            let mut od = OptionData {
                strike_price: pos(strike),
                call_bid: Some(pos(3_000.0)),
                call_ask: Some(pos(3_100.0)),
                put_bid: Some(pos(2_000.0)),
                put_ask: Some(pos(2_100.0)),
                implied_volatility: pos(0.5),
                ..Default::default()
            };
            od.set_mid_prices();
            let _ = chain.options.insert(od);
        }
        ChainStore::seed(
            ChainFetch::new(
                chain,
                ExpirySource::new("BTC", utc(EXP), pid("deribit")),
                AliasCatalog::new(),
            ),
            ChainSource::Merged,
            refresh(),
            utc(EXP),
        )
    }

    #[test]
    fn test_hidden_surface_fold_defers_rebuild_until_switch_to_surface() {
        // #106: a market fold while the Surface screen is HIDDEN must NOT rebuild the
        // full surface geometry (fan-in work for an invisible panel) — it only marks the
        // panel dirty. Switching TO the Surface pays the deferred rebuild once, off the
        // draw path; determinism + the revision pattern are preserved and draw stays
        // pure.
        let mut live = LiveState::new(
            source_binding("deribit", full_caps()),
            surface_store_strikes(&[60_000.0, 62_000.0, 64_000.0]),
        );
        // Seeded on the default Chain screen: the Surface panel is hidden and clean.
        assert_eq!(live.screen, LiveScreen::Chain);
        assert!(!live.surface.dirty, "the seeded panel is clean");
        let rev0 = live.surface.graph_revision();

        // The store changes (a poll re-lists the strike ladder) while the Surface is
        // hidden. The geometry WOULD move (a different smile), but the rebuild is
        // DEFERRED — only the dirty flag is set, the revision does not move.
        live.store = surface_store_strikes(&[60_000.0, 62_000.0]);
        live.refresh_surface();
        assert!(
            live.surface.dirty,
            "a hidden-screen fold marks the surface dirty (deferred), not rebuilt",
        );
        assert_eq!(
            live.surface.graph_revision(),
            rev0,
            "the hidden fold does not rebuild the surface geometry (no revision bump)",
        );

        // Switching to the Surface pays the deferred rebuild exactly once: the geometry
        // moves (the revision bumps) and the dirty flag clears.
        live.enter_screen(LiveScreen::Surface);
        assert!(
            !live.surface.dirty,
            "the switch clears the deferred-dirty flag"
        );
        let rev1 = live.surface.graph_revision();
        assert_ne!(
            rev1, rev0,
            "switch-to-surface rebuilt the deferred geometry once"
        );

        // A fold while the Surface is ACTIVE rebuilds immediately (never deferred): the
        // geometry moves and the panel stays clean.
        live.store = surface_store_strikes(&[58_000.0, 60_000.0, 62_000.0, 64_000.0]);
        live.refresh_surface();
        assert!(
            !live.surface.dirty,
            "an active-screen fold rebuilds immediately (stays clean)",
        );
        assert_ne!(
            live.surface.graph_revision(),
            rev1,
            "an active-screen fold bumps the revision immediately",
        );
    }

    #[test]
    fn test_overlay_aware_health_combines_source_and_overlay() {
        // #118: `overlay_aware_health` reflects EITHER contributor degrading — the
        // surface consumes Greeks/IV a standalone overlay may supply, so a stale overlay
        // must surface even while the chain source is live.
        // No overlay → the source health.
        let mut live = LiveState::new(
            source_binding("deribit", full_caps()),
            surface_store_strikes(&[60_000.0, 62_000.0]),
        );
        assert!(matches!(live.overlay_aware_health(), StreamHealth::Live));
        // A stale overlay over a live source → the overlay's stale health.
        live.overlay = Some(OverlayBinding::new(
            pid("dxlink"),
            full_caps(),
            StreamHealth::Stale { since: utc(EXP) },
        ));
        assert!(
            matches!(live.overlay_aware_health(), StreamHealth::Stale { .. }),
            "a stale overlay surfaces even while the source is live",
        );
        // A stale source is preferred (shown) when both degrade.
        live.source.health = StreamHealth::Reconnecting { attempt: 2 };
        assert!(
            matches!(
                live.overlay_aware_health(),
                StreamHealth::Reconnecting { .. }
            ),
            "the source health is preferred when both sides are degraded",
        );
    }

    #[test]
    fn test_on_event_market_depth_redraws_for_visible_selected_contract() {
        // The positive counterpart: on the Depth screen with the 60000-strike call
        // row focused, a depth update for that selected contract redraws.
        let (mut app, _rx) = live_app(full_caps());
        match &mut app.mode {
            Mode::Live(live) => {
                live.screen = LiveScreen::Depth;
                live.selection.focused_row = Some(0);
                live.selection.focused_leg = LegFocus::Call;
            }
            Mode::Replay(_) => panic!("expected a live app"),
        }
        let ladder = crate::chain::DepthLadder {
            instrument: instrument("deribit", 60_000.0, OptionStyle::Call),
            bids: Vec::new(),
            asks: Vec::new(),
            event_time: None,
            received_time: utc(EXP + 100),
            change_id: Some(1),
        };
        app.on_event(AppEvent::Market(MarketUpdate::Depth(ladder)));
        assert!(
            app.dirty,
            "a depth update for the visible selected contract redraws",
        );
    }

    // --- Per-side health: source and overlay degrade independently -----------

    fn overlay_caps() -> ProviderCapabilities {
        ProviderCapabilities::builder()
            .greeks(GreeksCapability::Provided)
            .build()
    }

    fn live_app_with_overlay() -> (App, mpsc::Receiver<Command>) {
        let (tx, rx) = mpsc::channel::<Command>(8);
        let live = LiveState::new(
            source_binding("deribit", full_caps()),
            store(&[60_000.0], "deribit"),
        )
        .with_overlay(OverlayBinding::new(
            pid("dxlink"),
            overlay_caps(),
            StreamHealth::Live,
        ));
        let mut app = App::new(Mode::Live(live), ThemeChoice::Auto, tx);
        app.mark_drawn();
        (app, rx)
    }

    #[test]
    fn test_on_event_market_health_degrades_source_side_only() {
        let (mut app, _rx) = live_app_with_overlay();
        app.on_event(AppEvent::Market(MarketUpdate::Health(
            pid("deribit"),
            StreamHealth::Reconnecting { attempt: 2 },
        )));
        assert!(app.dirty);
        let live = live(&app);
        assert!(matches!(
            live.source.health,
            StreamHealth::Reconnecting { attempt: 2 }
        ));
        // The overlay side is untouched.
        match &live.overlay {
            Some(overlay) => assert!(matches!(overlay.health, StreamHealth::Live)),
            None => panic!("expected an overlay binding"),
        }
    }

    #[test]
    fn test_on_event_market_health_degrades_overlay_side_only() {
        let (mut app, _rx) = live_app_with_overlay();
        app.on_event(AppEvent::Market(MarketUpdate::Health(
            pid("dxlink"),
            StreamHealth::Stale { since: utc(EXP) },
        )));
        assert!(app.dirty);
        let live = live(&app);
        // The source side stays live; only the overlay degrades.
        assert!(matches!(live.source.health, StreamHealth::Live));
        match &live.overlay {
            Some(overlay) => assert!(matches!(overlay.health, StreamHealth::Stale { .. })),
            None => panic!("expected an overlay binding"),
        }
    }

    #[test]
    fn test_on_event_market_health_for_unknown_provider_is_noop() {
        let (mut app, _rx) = live_app(full_caps());
        app.on_event(AppEvent::Market(MarketUpdate::Health(
            pid("alpaca"),
            StreamHealth::Reconnecting { attempt: 1 },
        )));
        assert!(!app.dirty);
    }

    // --- I/O-needing keys emit the right Command -----------------------------

    #[test]
    fn test_on_key_r_emits_reconnect_command_in_live() {
        let (mut app, mut rx) = live_app(full_caps());
        app.on_event(key(KeyCode::Char('r')));
        match rx.try_recv() {
            Ok(Command::Reconnect) => {}
            other => panic!("expected Reconnect, got {other:?}"),
        }
    }

    #[test]
    fn test_on_key_shift_r_emits_rediscover_command_in_live() {
        let (mut app, mut rx) = live_app(full_caps());
        app.on_event(key(KeyCode::Char('R')));
        match rx.try_recv() {
            Ok(Command::Rediscover) => {}
            other => panic!("expected Rediscover, got {other:?}"),
        }
    }

    #[test]
    fn test_on_key_shift_r_emits_reload_bundle_in_replay() {
        let (mut app, mut rx) = replay_app("/bundle");
        app.on_event(key(KeyCode::Char('R')));
        match rx.try_recv() {
            Ok(Command::ReloadBundle(dir)) => assert_eq!(dir, PathBuf::from("/bundle")),
            other => panic!("expected ReloadBundle, got {other:?}"),
        }
    }

    #[test]
    fn test_on_key_r_in_replay_emits_no_command() {
        let (mut app, mut rx) = replay_app("/bundle");
        app.on_event(key(KeyCode::Char('r')));
        assert!(rx.try_recv().is_err(), "`r` has no replay binding");
    }

    #[track_caller]
    fn replay(app: &App) -> &ReplayState {
        match &app.mode {
            Mode::Replay(replay) => replay,
            Mode::Live(_) => panic!("expected a replay app"),
        }
    }

    #[track_caller]
    fn cursor_position(app: &App) -> u32 {
        match replay(app).loaded() {
            Some(loaded) => loaded.cursor.position(),
            None => panic!("expected a Ready bundle"),
        }
    }

    #[test]
    fn test_on_replay_seek_folds_into_cursor_no_command() {
        // Seeking is an in-memory cursor move (#33): it emits NO command and
        // advances the play-head directly, marking the frame dirty.
        let (mut app, mut rx) = ready_replay_app(6);
        app.on_event(AppEvent::ReplaySeek(SeekTo::Step(3)));
        assert!(app.dirty, "a seek that moves the cursor redraws");
        assert_eq!(cursor_position(&app), 3);
        assert!(rx.try_recv().is_err(), "a seek emits no command (#33)");
    }

    #[test]
    fn test_on_replay_seek_step_by_walks_and_clamps() {
        let (mut app, _rx) = ready_replay_app(4);
        // `end_step` is 3; a forward step moves, and a step past the end clamps.
        app.on_event(AppEvent::ReplaySeek(SeekTo::StepBy(1)));
        assert_eq!(cursor_position(&app), 1);
        app.on_event(AppEvent::ReplaySeek(SeekTo::Step(u32::MAX)));
        assert_eq!(cursor_position(&app), 3, "Step clamps to end_step");
        app.mark_drawn();
        // A no-op seek (already at end, step forward) does not redraw.
        app.on_event(AppEvent::ReplaySeek(SeekTo::StepBy(1)));
        assert!(!app.dirty, "a clamped no-op seek requests no redraw");
        assert_eq!(cursor_position(&app), 3);
    }

    #[test]
    fn test_on_replay_seek_while_loading_is_noop() {
        // Before the bundle is Ready there is no cursor to move: the seek folds to
        // a no-op with no redraw and no command.
        let (mut app, mut rx) = replay_app("/bundle");
        app.on_event(AppEvent::ReplaySeek(SeekTo::Step(3)));
        assert!(!app.dirty, "a seek with no loaded bundle is a no-op");
        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn test_on_replay_seek_in_live_is_noop() {
        let (mut app, mut rx) = live_app(full_caps());
        app.on_event(AppEvent::ReplaySeek(SeekTo::StepBy(1)));
        assert!(!app.dirty);
        assert!(
            rx.try_recv().is_err(),
            "a scrub is meaningless in live mode"
        );
    }

    // --- Bundle-load transitions: Loading -> Ready / Error, reload ------------

    #[test]
    fn test_bundle_loaded_transitions_loading_to_ready() {
        let (mut app, _rx) = replay_app("/bundle");
        assert!(matches!(replay(&app).bundle, BundleLoad::Loading));
        app.on_event(AppEvent::BundleLoaded(BundleLoadResult::Loaded(Box::new(
            loaded_bundle(5),
        ))));
        assert!(app.dirty, "a completed load redraws");
        match replay(&app).loaded() {
            Some(loaded) => {
                assert_eq!(loaded.cursor.position(), 0, "the cursor starts at step 0");
                assert_eq!(loaded.cursor.end_step(), 4, "end_step is n_steps - 1");
                assert!(loaded.selection.is_none(), "no drill-down yet");
            }
            None => panic!("expected Ready after a successful load"),
        }
    }

    #[test]
    fn test_bundle_loaded_transitions_loading_to_error() {
        let (mut app, _rx) = replay_app("/bundle");
        app.on_event(AppEvent::BundleLoaded(BundleLoadResult::Failed(
            "invariant violated: equity != cash + position at step 3".to_owned(),
        )));
        assert!(app.dirty);
        match &replay(&app).bundle {
            BundleLoad::Error { message } => {
                assert!(message.contains("equity"), "the message is actionable");
            }
            other => panic!("expected Error, got {other:?}"),
        }
    }

    #[test]
    fn test_shift_r_resets_ready_bundle_to_loading_and_reloads() {
        // `R` on a loaded bundle resets to Loading (the load screen shows the
        // connecting state) AND re-issues ReloadBundle for the re-open I/O.
        let (mut app, mut rx) = ready_replay_app(5);
        assert!(replay(&app).loaded().is_some());
        app.on_event(key(KeyCode::Char('R')));
        assert!(app.dirty);
        assert!(
            matches!(replay(&app).bundle, BundleLoad::Loading),
            "reload resets to Loading",
        );
        match rx.try_recv() {
            Ok(Command::ReloadBundle(dir)) => assert_eq!(dir, PathBuf::from("/bundle")),
            other => panic!("expected ReloadBundle, got {other:?}"),
        }
    }

    #[test]
    fn test_shift_r_on_a_closed_command_channel_keeps_prior_state_not_loading() {
        // Finding 2 (#34): the reload flips to `Loading` only AFTER the
        // `ReloadBundle` command actually enqueues. A dropped send (a closed command
        // channel — the data layer is gone) must NOT strand the load screen at
        // `Loading` with no load in flight: the prior `Ready` bundle is kept, the
        // drop is counted (#9), and a one-line hint is flashed.
        let (mut app, rx) = ready_replay_app(5);
        assert!(replay(&app).loaded().is_some(), "starts Ready");
        // Close the command channel: the data layer is gone.
        drop(rx);
        app.on_event(key(KeyCode::Char('R')));
        assert!(
            replay(&app).loaded().is_some(),
            "a dropped reload send keeps the prior Ready bundle, not a stuck Loading",
        );
        assert!(
            !matches!(replay(&app).bundle, BundleLoad::Loading),
            "the load screen must not spin forever with no load in flight",
        );
        assert_eq!(app.commands_dropped, 1, "the dropped reload is counted");
        assert!(
            app.status_hint.is_some(),
            "a dropped reload flashes a hint instead of silently no-op'ing",
        );
    }

    #[test]
    fn test_reload_after_error_returns_to_loading() {
        // The retry key on a bundle Error is `R`: Error -> (R) -> Loading -> Ready.
        let (mut app, mut rx) = replay_app("/bundle");
        app.on_event(AppEvent::BundleLoaded(BundleLoadResult::Failed(
            "missing table: fills.parquet".to_owned(),
        )));
        assert!(matches!(replay(&app).bundle, BundleLoad::Error { .. }));
        app.on_event(key(KeyCode::Char('R')));
        assert!(matches!(replay(&app).bundle, BundleLoad::Loading));
        assert!(matches!(rx.try_recv(), Ok(Command::ReloadBundle(_))));
        // A subsequent successful load recovers.
        app.on_event(AppEvent::BundleLoaded(BundleLoadResult::Loaded(Box::new(
            loaded_bundle(3),
        ))));
        assert!(replay(&app).loaded().is_some());
    }

    #[test]
    fn test_bundle_loaded_in_live_is_ignored() {
        // A stray bundle-load result in live mode is a no-op — never a panic, never
        // a mode switch.
        let (mut app, _rx) = live_app(full_caps());
        app.on_event(AppEvent::BundleLoaded(BundleLoadResult::Loaded(Box::new(
            loaded_bundle(3),
        ))));
        assert!(!app.dirty);
        assert!(matches!(app.mode, Mode::Live(_)));
    }

    // --- Playback fold: play/pause/speed + tick advance ----------------------

    #[test]
    fn test_replay_control_play_pause_toggles() {
        let (mut app, _rx) = ready_replay_app(6);
        assert!(!replay(&app).is_playing());
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        assert!(app.dirty);
        assert!(replay(&app).is_playing());
        assert_eq!(replay(&app).play, Playback::playing(PlaybackSpeed::X1));
        app.mark_drawn();
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        assert!(app.dirty);
        assert_eq!(replay(&app).play, Playback::Paused);
    }

    #[test]
    fn test_replay_control_speed_adjusts_only_while_playing() {
        let (mut app, _rx) = ready_replay_app(6);
        // Paused: a speed key is a no-op.
        app.on_event(AppEvent::ReplayControl(ReplayControl::SpeedFaster));
        assert!(!app.dirty, "speed while paused is a no-op");
        assert_eq!(replay(&app).play, Playback::Paused);
        // Playing: + steps the speed up, clamped at the fastest.
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        app.mark_drawn();
        app.on_event(AppEvent::ReplayControl(ReplayControl::SpeedFaster));
        assert_eq!(replay(&app).play, Playback::playing(PlaybackSpeed::X2));
        app.on_event(AppEvent::ReplayControl(ReplayControl::SpeedSlower));
        assert_eq!(replay(&app).play, Playback::playing(PlaybackSpeed::X1));
        app.mark_drawn();
        // Already at the slowest: another `-` is a no-op.
        app.on_event(AppEvent::ReplayControl(ReplayControl::SpeedSlower));
        assert!(!app.dirty, "speed clamped at the slowest is a no-op");
    }

    #[test]
    fn test_tick_advances_play_head_only_while_playing() {
        let (mut app, _rx) = ready_replay_app(6);
        // Paused: a tick does not move the cursor.
        app.on_event(AppEvent::Tick);
        assert_eq!(cursor_position(&app), 0);
        // Playing at ×1: each tick advances one step.
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        app.on_event(AppEvent::Tick);
        assert_eq!(cursor_position(&app), 1);
        app.on_event(AppEvent::Tick);
        assert_eq!(cursor_position(&app), 2);
    }

    #[test]
    fn test_tick_advance_stops_and_auto_pauses_at_end() {
        let (mut app, _rx) = ready_replay_app(3);
        // Jump near the end, then play: the head reaches end_step and auto-pauses,
        // so the loop parks instead of spinning.
        app.on_event(AppEvent::ReplaySeek(SeekTo::Step(1)));
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        app.on_event(AppEvent::Tick); // 1 -> 2 (== end_step)
        assert_eq!(cursor_position(&app), 2);
        assert_eq!(
            replay(&app).play,
            Playback::Paused,
            "playback auto-pauses at the tape end"
        );
        app.mark_drawn();
        // A further tick neither moves the head nor redraws (parked).
        app.on_event(AppEvent::Tick);
        assert!(!app.dirty, "a paused tick at the end does not spin");
        assert_eq!(cursor_position(&app), 2);
    }

    #[test]
    fn test_replay_control_in_live_is_ignored() {
        let (mut app, _rx) = live_app(full_caps());
        app.on_event(AppEvent::ReplayControl(ReplayControl::PlayPause));
        assert!(!app.dirty);
    }

    // --- Quit / help ----------------------------------------------------------

    #[test]
    fn test_on_key_q_requests_quit_and_sets_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        app.on_event(key(KeyCode::Char('q')));
        assert!(app.should_quit);
        assert!(app.dirty);
    }

    #[test]
    fn test_on_key_ctrl_c_requests_quit() {
        let (mut app, _rx) = live_app(full_caps());
        app.on_event(AppEvent::Key(KeyEvent::new(
            KeyCode::Char('c'),
            KeyModifiers::CONTROL,
        )));
        assert!(app.should_quit);
    }

    #[test]
    fn test_on_key_question_toggles_help_and_sets_dirty() {
        let (mut app, _rx) = live_app(full_caps());
        assert!(!app.help_open);
        app.on_event(key(KeyCode::Char('?')));
        assert!(app.help_open);
        assert!(app.dirty);
        app.mark_drawn();
        app.on_event(key(KeyCode::Char('?')));
        assert!(!app.help_open);
        assert!(app.dirty);
    }

    // --- Two-level key dispatch: global route vs. forward-to-screen ----------

    #[track_caller]
    fn key_event(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn test_dispatch_key_global_bound_global_is_consumed() {
        let (mut app, _rx) = live_app(full_caps());
        // A bound global (`q`) is consumed at the global level, never forwarded.
        assert_eq!(
            app.dispatch_key_global(key_event(KeyCode::Char('q'))),
            KeyRoute::Consumed
        );
        assert!(app.should_quit);
    }

    #[test]
    fn test_dispatch_key_global_unbound_key_routes_to_screen() {
        let (mut app, _rx) = live_app(full_caps());
        // An unbound key (`j`, a chain-nav key owned by the screen) is forwarded.
        assert_eq!(
            app.dispatch_key_global(key_event(KeyCode::Char('j'))),
            KeyRoute::ToScreen
        );
        assert!(!app.dirty, "forwarding a key mutates no global state");
    }

    #[test]
    fn test_dispatch_key_global_modal_help_swallows_and_never_forwards() {
        let (mut app, _rx) = live_app(full_caps());
        assert_eq!(
            app.dispatch_key_global(key_event(KeyCode::Char('?'))),
            KeyRoute::Consumed
        );
        assert!(app.help_open);
        app.mark_drawn();
        // With help open, an unbound key is swallowed (Consumed), NOT forwarded to
        // the screen behind the overlay — the modal intercept.
        assert_eq!(
            app.dispatch_key_global(key_event(KeyCode::Char('j'))),
            KeyRoute::Consumed
        );
        assert!(app.help_open, "a swallowed key leaves the overlay open");
        assert!(!app.dirty, "a swallowed key mutates no state");
        // `Esc` closes the modal overlay.
        assert_eq!(
            app.dispatch_key_global(key_event(KeyCode::Esc)),
            KeyRoute::Consumed
        );
        assert!(!app.help_open);
        assert!(app.dirty);
    }

    #[test]
    fn test_dispatch_key_global_non_press_is_consumed_not_forwarded() {
        let (mut app, _rx) = live_app(full_caps());
        let release = KeyEvent::new_with_kind(
            KeyCode::Char('j'),
            KeyModifiers::NONE,
            KeyEventKind::Release,
        );
        assert_eq!(app.dispatch_key_global(release), KeyRoute::Consumed);
    }

    #[test]
    fn test_dispatch_key_global_modal_swallows_out_of_vocab_key() {
        // A key OUTSIDE the keymap vocabulary (an F-key, PageUp, …) must be swallowed
        // while the overlay is modal — it must never reach the hidden screen behind
        // it (the intercept runs before the vocabulary check).
        let (mut app, _rx) = live_app(full_caps());
        assert_eq!(
            app.dispatch_key_global(key_event(KeyCode::Char('?'))),
            KeyRoute::Consumed
        );
        assert!(app.help_open);
        app.mark_drawn();
        for code in [
            KeyCode::F(5),
            KeyCode::PageUp,
            KeyCode::Insert,
            KeyCode::Delete,
        ] {
            assert_eq!(
                app.dispatch_key_global(key_event(code)),
                KeyRoute::Consumed,
                "an out-of-vocab key must be swallowed while modal, not forwarded"
            );
            assert!(app.help_open, "the overlay stays open");
            assert!(!app.dirty, "a swallowed key mutates no state");
        }
    }

    // --- Capability-driven reachability (no ProviderId match) ----------------

    #[test]
    fn test_is_screen_reachable_depth_gated_on_capability() {
        let with_depth = full_caps();
        assert!(is_screen_reachable(LiveScreen::Depth, &with_depth));
        let without_depth = ProviderCapabilities::builder()
            .chain(ChainCapability::Assemble)
            .greeks(GreeksCapability::Provided)
            .build();
        assert!(!is_screen_reachable(LiveScreen::Depth, &without_depth));
        // Chain/Payoff still reachable; Surface still reachable (Greeks present).
        assert!(is_screen_reachable(LiveScreen::Chain, &without_depth));
        assert!(is_screen_reachable(LiveScreen::Payoff, &without_depth));
        assert!(is_screen_reachable(LiveScreen::Surface, &without_depth));
    }

    #[test]
    fn test_is_screen_reachable_surface_gated_on_greeks() {
        let no_greeks = ProviderCapabilities::builder()
            .chain(ChainCapability::Assemble)
            .greeks(GreeksCapability::None)
            .build();
        assert!(!is_screen_reachable(LiveScreen::Surface, &no_greeks));
        assert!(is_screen_reachable(LiveScreen::Chain, &no_greeks));
    }

    #[test]
    fn test_set_screen_refuses_unreachable_and_keeps_prior() {
        let no_depth = ProviderCapabilities::builder()
            .chain(ChainCapability::Assemble)
            .greeks(GreeksCapability::Provided)
            .depth(false)
            .build();
        let (mut app, _rx) = live_app(no_depth);
        let switched = match &mut app.mode {
            Mode::Live(live) => (live.set_screen(LiveScreen::Depth), live.screen),
            Mode::Replay(_) => panic!("expected live"),
        };
        assert!(!switched.0, "an unreachable screen switch is refused");
        assert_eq!(switched.1, LiveScreen::Chain, "the prior screen is kept");
    }

    #[test]
    fn test_set_screen_switches_to_reachable() {
        let (mut app, _rx) = live_app(full_caps());
        let (switched, screen) = match &mut app.mode {
            Mode::Live(live) => (live.set_screen(LiveScreen::Surface), live.screen),
            Mode::Replay(_) => panic!("expected live"),
        };
        assert!(switched);
        assert_eq!(screen, LiveScreen::Surface);
    }

    #[test]
    fn test_effective_capabilities_unions_overlay_depth_and_greeks() {
        // A source with neither depth nor Greeks, plus an overlay that adds
        // Greeks — the union makes the Surface screen reachable.
        let bare_source = ProviderCapabilities::builder()
            .chain(ChainCapability::Assemble)
            .depth(false)
            .greeks(GreeksCapability::None)
            .build();
        let overlay_with_greeks = ProviderCapabilities::builder()
            .depth(true)
            .greeks(GreeksCapability::ComputedLocally)
            .build();
        let live = LiveState::new(source_binding("ig", bare_source), store(&[60_000.0], "ig"))
            .with_overlay(OverlayBinding::new(
                pid("dxlink"),
                overlay_with_greeks,
                StreamHealth::Live,
            ));
        assert!(live.screen_reachable(LiveScreen::Surface));
        assert!(live.screen_reachable(LiveScreen::Depth));
        let effective = live.effective_capabilities();
        assert!(effective.depth);
        assert_eq!(effective.greeks, GreeksCapability::ComputedLocally);
    }

    // --- Compile fences: closed sets are matched wildcard-free ---------------

    #[test]
    fn test_mode_and_screen_matches_are_wildcard_free() {
        // These exhaustive, wildcard-free matches mirror the render/fan-in
        // discipline: adding a `Mode`, `LiveScreen`, or `ReplayScreen` variant
        // breaks THESE matches at compile time.
        fn mode_label(mode: &Mode) -> &'static str {
            match mode {
                Mode::Live(_) => "live",
                Mode::Replay(_) => "replay",
            }
        }
        fn live_label(screen: LiveScreen) -> &'static str {
            match screen {
                LiveScreen::Chain => "chain",
                LiveScreen::Depth => "depth",
                LiveScreen::Surface => "surface",
                LiveScreen::Payoff => "payoff",
            }
        }
        fn replay_label(screen: ReplayScreen) -> &'static str {
            match screen {
                ReplayScreen::Replay => "replay",
                ReplayScreen::Payoff => "payoff",
            }
        }
        let (app, _rx) = live_app(full_caps());
        assert_eq!(mode_label(&app.mode), "live");
        assert_eq!(live_label(LiveScreen::Chain), "chain");
        assert_eq!(replay_label(ReplayScreen::Replay), "replay");
    }

    #[test]
    fn test_out_of_mode_screen_pair_is_unrepresentable() {
        // A `Mode::Replay` owns a `ReplayScreen`, never a `LiveScreen`, so
        // `Replay` + `Chain` cannot be constructed — the type system, not a
        // runtime fallback, prevents it. This asserts the mode-scoped defaults;
        // the impossibility is proven by the fact that assigning a `LiveScreen`
        // to `ReplayState::screen` would not compile.
        let replay = ReplayState::new(PathBuf::from("/bundle"));
        assert_eq!(replay.screen, ReplayScreen::Replay);
        assert!(matches!(replay.bundle, BundleLoad::Loading));
        assert_eq!(replay.play, Playback::Paused);
    }

    #[test]
    fn test_screen_load_default_is_loading() {
        assert_eq!(ScreenLoad::default(), ScreenLoad::Loading);
        let error = ScreenLoad::Error {
            message: "no chain for BTC".to_owned(),
        };
        assert_ne!(error, ScreenLoad::Loading);
    }
}