File size: 58,989 Bytes
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1e8b0d
 
 
 
 
 
 
 
 
 
 
 
 
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1e8b0d
 
 
 
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e94a0b
 
 
 
 
 
 
 
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e94a0b
 
 
 
 
 
 
 
8028640
 
 
 
 
 
 
 
 
 
1e94a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8028640
442b828
 
 
 
 
 
 
 
 
 
 
 
 
 
8028640
 
 
 
 
 
 
 
 
 
 
 
1e94a0b
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442b828
 
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92f614c
 
 
8028640
 
 
 
 
92f614c
 
 
 
 
 
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3453c02
 
 
 
 
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3453c02
8028640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The Arena's visible layer: the design's own markup, rendered from state.

Gradio is the backend here and nothing else -- one `gr.HTML` sink, a hidden
textbox the click bridge writes into, and a hidden button it clicks. Every
control on the page is the `<button>` the design specifies, carrying a
`data-bit` action, because the design is built from 13 buttons against 2 inputs
and Gradio renders something structurally different for the same concepts.

The one rule to keep when editing: **render from capabilities, never from a
model's name.** `caps["output"] == "ohlcv_paths"` is what decides whether the
ghost-path control exists. There is no branch anywhere below that mentions
Kronos, Chronos or TimesFM.
"""

from __future__ import annotations

import pandas as pd
from bit_ui import icons, palette, sidebar
from bit_ui.markup import a, e

from .. import config, view
from ..view import DASH, count, grade_color, num, pct
from . import chart
from .chrome import emit

STYRENE = ("font-family:var(--font-styrene);text-transform:uppercase;"
           "letter-spacing:var(--tracking-wide)")
PANEL = "border:1px solid var(--border-default);background:var(--bg-panel)"
HEAD = ("display:flex;align-items:center;gap:8px;padding:7px 10px;"
        "border-bottom:1px solid var(--border-default)")


def bit(action: str, value: str = "") -> str:
    """The full `data-bit` attribute for an action, escaped.

    `emit()` returns the attribute *value*, not the attribute. Interpolating it
    bare renders `<button run:go>`, which is not a data attribute at all: the
    delegated listener never matches it and the control does nothing, with no
    error anywhere. This wrapper is the only way actions are attached below.
    """
    return f'type="button" data-bit="{a(emit(action, value))}"'


def _panel_title(text: str, right: str = "") -> str:
    return (f'<div style="{HEAD}">'
            f'<span style="{STYRENE};font-size:var(--text-sm)">{e(text)}</span>'
            f'{right}</div>')


# --------------------------------------------------------------------------
# Header
# --------------------------------------------------------------------------


def header(state: dict, data: dict) -> str:
    archived = data.get("archived_total")
    resolved = data.get("resolved_total")
    tally = (f"ARCHIVE: {count(archived)} FORECASTS · {count(resolved)} RESOLVED"
             if archived is not None else "ARCHIVE: BUILDING")

    # The session line, not a sign-in prompt: the prompt is Gradio's own
    # LoginButton, parked in this corner by `#bit-login` in chrome.py.
    # Rendering another one here would be two buttons for one action.
    signed_in = bool(state.get("signed_in"))
    if signed_in:
        who = str(state.get("user") or "").strip().upper()
        account = (f"ACCOUNT \u00b7 {who} \u00b7 GPU TIER ON YOUR QUOTA" if who
                   else "ACCOUNT \u00b7 GPU TIER ON YOUR QUOTA")
    else:
        left = max(0, config.ANON_SESSION_CAP - int(state.get("session_forecasts", 0)))
        account = (f"ANONYMOUS SESSION \u00b7 CPU-TIER MODELS \u00b7 "
                   f"{left} FORECASTS LEFT")
    dot = "var(--fin-up)" if signed_in else "var(--mute-orange)"

    return (
        '<header style="position:sticky;top:0;z-index:20;background:var(--bg-panel);'
        'border-bottom:1px solid var(--border-default)">'
        '<div style="display:flex;align-items:center;gap:10px;padding:8px 14px;'
        'min-height:48px;flex-wrap:wrap">'
        '<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto">'
        '<span style="display:inline-block;width:6px;height:6px;'
        'background:var(--fin-up);animation:bitPulse 2s ease-in-out infinite"></span>'
        f'<span style="{STYRENE};font-size:var(--text-sm);color:var(--text-secondary)">Arena</span>'
        '</div>'
        f'<a href="{a(data.get("store_url", "#"))}" target="_blank" rel="noopener" '
        'style="display:flex;align-items:center;gap:8px;padding:3px 8px;'
        'border:1px solid var(--accent-amber-dim);color:var(--accent-amber-strong);'
        'flex:0 0 auto;text-decoration:none">'
        f'<span class="mono-data" style="font-size:var(--text-xs)">{e(tally)}</span></a>'
        '<div style="flex:1 1 auto;min-width:180px;max-width:400px">'
        f'{palette.search_bar(state.get("q", ""), emit, count_label="")}'
        '</div>'
        '<span style="display:inline-flex;align-items:center;gap:6px;padding:3px 8px;'
        # The right margin is the width the fixed LoginButton occupies,
        # so the session line and the sign-in control do not overlap.
        'border:1px solid var(--border-default);margin-left:auto;'
        'margin-right:268px">'
        f'<span style="display:inline-block;width:5px;height:5px;background:{dot}"></span>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-secondary);white-space:nowrap">{e(account)}</span></span>'
        '</div>'
        '</header>'
    )


# --------------------------------------------------------------------------
# Stats and title
# --------------------------------------------------------------------------


def title_row(state: dict, data: dict) -> str:
    deep = ""
    if state.get("deep_linked"):
        deep = ('<span style="display:inline-flex;align-items:center;gap:7px;'
                'padding:4px 8px;border:1px solid var(--accent-amber-dim);'
                'background:var(--bg-raised)">'
                '<span class="pixel-text" style="color:var(--accent-amber-strong)">→</span>'
                '<span class="mono-data" style="font-size:var(--text-2xs);'
                f'color:var(--text-secondary)">DEEP LINK ?model={e(state["selected"][0])}'
                ' · PRESELECTED</span></span>')

    ran = data.get("resolver_last_ran") or DASH
    return (
        '<div style="display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap">'
        '<div style="display:flex;flex-direction:column;gap:3px;min-width:0">'
        f'<h1 style="{STYRENE};font-weight:500;font-size:var(--text-2xl);'
        'line-height:var(--leading-tight);margin:0">Forecast Arena</h1>'
        '<span style="color:var(--text-secondary);font-size:var(--text-base)">'
        'Every model forecasts. Every forecast is remembered.</span></div>'
        f'{deep}'
        '<span style="display:inline-flex;align-items:center;gap:6px;padding:4px 8px;'
        f'border:1px solid var(--border-default);background:var(--bg-panel);margin-left:auto">'
        '<span style="display:inline-block;width:5px;height:5px;'
        'background:var(--accent-amber);animation:bitPulse 2s ease-in-out infinite"></span>'
        '<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-secondary);white-space:nowrap">RESOLVER LAST RAN {e(ran)}</span>'
        '</span></div>'
    )


def stats_bar(stats: list[dict]) -> str:
    cells = []
    for s in stats:
        cells.append(
            f'<div style="padding:10px 12px;border-right:1px solid var(--border-subtle);'
            f'border-left:2px solid {a(s["mark"])}">'
            f'<div style="{STYRENE};font-weight:300;font-size:var(--text-2xs);'
            f'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
            f'white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{e(s["label"])}</div>'
            f'<div class="mono-data" style="font-size:var(--text-2xl);line-height:1.15;'
            f'white-space:nowrap;color:{a(s["color"])}">{e(s["value"])}</div>'
            f'<div style="font-size:var(--text-2xs);color:var(--text-tertiary);'
            f'white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{e(s["note"])}</div>'
            f'</div>')
    return ('<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));'
            f'{PANEL}">{"".join(cells)}</div>')


# --------------------------------------------------------------------------
# Model picker
# --------------------------------------------------------------------------


def models_section(state: dict, data: dict) -> str:
    mode = state["mode"]
    selected = state["selected"]
    sel_note = (f"MATCHUP · {len(selected)} OF {view.MAX_MATCHUP} SELECTED"
                if mode == "matchup" else "PLAYGROUND · SINGLE MODEL")

    tabs = []
    for i, (key, label) in enumerate((("playground", "Playground"),
                                      ("matchup", "Matchup"))):
        on = mode == key
        tabs.append(
            f'<button {bit("mode", key)} style="padding:4px 12px;'
            f'background:{"var(--accent-amber)" if on else "transparent"};'
            f'border:1px solid var(--border-default);border-left-width:{"1px" if i == 0 else "0"};'
            f'color:{"var(--stone-950)" if on else "var(--text-secondary)"};{STYRENE};'
            f'font-size:var(--text-xs);cursor:pointer;transition:background 1s ease">'
            f'{e(label)}</button>')

    cards = "".join(_model_card(m, m["slug"] in selected, data)
                    for m in data["models"])

    add = (
        f'<button {bit("enroll", "focus")} style="text-align:left;display:flex;'
        'flex-direction:column;gap:6px;justify-content:center;padding:10px 11px;'
        'background:transparent;border:0;border-left:1px dashed var(--border-default);'
        'cursor:pointer;color:var(--text-tertiary)">'
        '<span class="mono-data" style="font-size:var(--text-lg)">+</span>'
        f'<span style="{STYRENE};font-size:var(--text-sm)">Add a fine-tune</span>'
        '<span style="font-size:var(--text-2xs);text-wrap:pretty">Any Hub model with a '
        'Kronos, Chronos or TimesFM adapter family</span></button>')

    return (
        f'<section style="{PANEL}">'
        '<div style="display:flex;align-items:center;gap:10px;padding:8px 12px;'
        'border-bottom:1px solid var(--border-default);flex-wrap:wrap">'
        f'<span style="{STYRENE};font-size:var(--text-md)">Models</span>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary)">{e(sel_note)}</span>'
        f'<div style="display:flex;margin-left:auto">{"".join(tabs)}</div></div>'
        f'<div class="fa-picker">{cards}{add}</div></section>'
    )


def _model_card(model: dict, on: bool, data: dict) -> str:
    """One model card. Rendered from declared capabilities only."""
    color = model["color"]
    caps = model["caps"]

    # The two capability chips the design specifies: what the model emits, and
    # what hardware it costs. Both come from the adapter's declaration.
    paths = caps.get("output") == "ohlcv_paths"
    gpu = caps.get("hardware") == "gpu"
    chips = [
        ("OHLCV paths" if paths else "quantile line",
         "var(--accent-amber-strong)" if paths else "var(--text-secondary)",
         "var(--accent-amber-dim)" if paths else "var(--border-default)"),
        ("your GPU quota" if gpu else "CPU · instant",
         "var(--mute-orange)" if gpu else "var(--accent-moss-strong)",
         "var(--mute-orange)" if gpu else "var(--accent-moss-dim)"),
    ]
    chip_html = "".join(
        f'<span class="mono-data fa-tag" style="color:{a(fg)};border-color:{a(bd)}">'
        f'{e(label)}</span>' for label, fg, bd in chips)

    chk_style = (f'background:{a(color)};color:var(--stone-950);border-color:{a(color)}'
                 if on else "")
    return (
        f'<button {bit("pick", model["slug"])} class="fa-card{" on" if on else ""}" '
        f'style="border-top-color:{a(color) if on else "transparent"}">'
        '<div class="fa-card-top">'
        f'<span class="mono-data fa-tag" style="color:{a(color) if on else "var(--text-tertiary)"};'
        f'border-color:{a(color) if on else "var(--border-default)"}">{e(model["family"].upper())}</span>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary)">{e(model["size"])}</span>'
        f'<span class="fa-chk" style="{chk_style}">{"✓" if on else ""}</span></div>'
        f'<div class="fa-card-name">{e(model["name"])}</div>'
        f'<div class="fa-card-caps">{chip_html}</div>'
        '<div class="fa-card-cal">'
        '<span class="pixel-text" style="color:var(--text-tertiary)">CALIBRATION</span>'
        f'<span class="mono-data" style="font-size:var(--text-md);'
        f'color:{a(model["grade_color"])};margin-left:auto">{e(model["grade"])}</span>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary)">{e(model["resolved_label"])}</span></div>'
        '</button>')


# --------------------------------------------------------------------------
# Controls
# --------------------------------------------------------------------------


def controls(state: dict, data: dict) -> str:
    assets = "".join(
        f'<button {bit("asset", slug)} class="fa-pill'
        f'{" on" if state["asset"] == slug else ""}">{e(spec.display)}</button>'
        for slug, spec in config.ASSETS.items())

    tfs = "".join(
        f'<button {bit("tf", slug)} class="fa-seg{" first" if i == 0 else ""}'
        f'{" on" if state["tf"] == slug else ""}">{e(slug)}</button>'
        for i, slug in enumerate(config.TIMEFRAMES))

    options = _horizon_options(state["tf"])
    hzs = "".join(
        f'<button {bit("hz", str(h))} class="fa-seg{" first" if i == 0 else ""}'
        f'{" on" if int(state["horizon"]) == h else ""}">{h} steps</button>'
        for i, h in enumerate(options))

    hours = state["horizon"] * (1 if state["tf"] == "1h" else 24)
    hz_note = f"= {hours}H AHEAD"

    gear = _gear(state) if state.get("gear") else ""
    quota = _quota_banner(data) if data.get("quota_blocked") else ""

    run_label = ("▶ Forecast" if state["mode"] == "playground"
                 else f"▶ Forecast {len(state['selected'])} models")
    runtime = data.get("runtime_hint", DASH)
    blocked = bool(data.get("quota_blocked"))

    return (
        f'<section style="{PANEL};display:flex;align-items:center;gap:14px;'
        'padding:9px 12px;flex-wrap:wrap">'
        '<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">'
        '<span class="pixel-text" style="color:var(--text-tertiary)">ASSET</span>'
        f'{assets}</div>'
        '<div style="width:1px;height:22px;background:var(--border-subtle)"></div>'
        '<div style="display:flex;align-items:center;gap:6px">'
        '<span class="pixel-text" style="color:var(--text-tertiary)">TIMEFRAME</span>'
        f'<div style="display:flex">{tfs}</div></div>'
        '<div style="width:1px;height:22px;background:var(--border-subtle)"></div>'
        '<div style="display:flex;align-items:center;gap:6px">'
        '<span class="pixel-text" style="color:var(--text-tertiary)">HORIZON</span>'
        f'<div style="display:flex">{hzs}</div>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary)">{e(hz_note)}</span></div>'
        '<div style="position:relative;margin-left:auto;display:flex;'
        'align-items:center;gap:8px">'
        f'<button {bit("gear", "toggle")} title="Sampling and seed" '
        f'style="width:26px;height:26px;background:'
        f'{"var(--bg-raised)" if state.get("gear") else "transparent"};'
        f'border:1px solid {"var(--accent-amber)" if state.get("gear") else "var(--border-default)"};'
        f'color:{"var(--accent-amber-strong)" if state.get("gear") else "var(--text-tertiary)"};'
        'cursor:pointer;display:flex;align-items:center;justify-content:center">'
        f'{icons.icon("sliders", size="13px")}</button>'
        f'{gear}{quota}'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary);padding:3px 7px;'
        f'border:1px solid var(--border-subtle)">{e(runtime)}</span>'
        f'<button {bit("run", "go")} '
        f'style="padding:6px 14px;background:'
        f'{"var(--bg-raised)" if blocked else "var(--accent-amber)"};'
        f'border:1px solid {"var(--border-default)" if blocked else "var(--accent-amber)"};'
        f'color:{"var(--text-disabled)" if blocked else "var(--stone-950)"};'
        f'{STYRENE};font-size:var(--text-xs);'
        f'cursor:{"not-allowed" if blocked else "pointer"}">{e(run_label)}</button>'
        '</div></section>'
    )


def _horizon_options(timeframe: str) -> list[int]:
    """Horizon choices, capped at what the timeframe allows."""
    ceiling = config.MAX_HORIZON.get(timeframe, 96)
    return [h for h in (12, 24, 48, 96) if h <= ceiling] or [ceiling]


def _gear(state: dict) -> str:
    rows = [
        ("Sampled paths", str(state.get("n_samples", config.DEFAULT_N_SAMPLES))),
        ("Quantiles", "/".join(f"{q:g}" for q in config.QUANTILE_LEVELS)),
        ("Seed", str(state.get("seed", 42))),
    ]
    body = "".join(
        '<div style="display:flex;align-items:center;gap:8px">'
        f'<span style="flex:1 1 auto;{STYRENE};font-weight:300;'
        f'font-size:var(--text-xs);color:var(--text-secondary)">{e(label)}</span>'
        f'<span class="mono-data" style="font-size:var(--text-xs);'
        f'color:var(--text-primary);border:1px solid var(--border-default);'
        f'padding:2px 7px">{e(value)}</span></div>'
        for label, value in rows)
    return (
        '<div style="position:absolute;top:32px;right:0;z-index:40;width:230px;'
        'background:var(--bg-raised);border:1px solid var(--border-strong);'
        'padding:10px 12px;display:flex;flex-direction:column;gap:9px">'
        f'<span style="{STYRENE};font-weight:300;font-size:var(--text-xs);'
        'color:var(--text-tertiary)">Sampling</span>'
        f'{body}'
        '<span class="pixel-text" style="color:var(--text-tertiary)">'
        'SEED IS ARCHIVED WITH THE FORECAST</span></div>')


def _quota_banner(data: dict) -> str:
    return (
        '<span style="display:inline-flex;align-items:center;gap:7px;padding:4px 9px;'
        'border:1px solid var(--mute-orange);background:var(--bg-raised)">'
        '<span class="pixel-text" style="color:var(--mute-orange)">⚠</span>'
        f'<span style="font-size:var(--text-xs);color:var(--text-secondary)">'
        f'{e(data.get("quota_msg", "GPU-tier model — sign in to use your quota"))}</span>'
        f'<a href="{a(data.get("login_url", "#"))}" style="font-family:var(--font-mono);'
        'font-size:var(--text-2xs);white-space:nowrap">SIGN IN ↗</a></span>')


# --------------------------------------------------------------------------
# Chart panel
# --------------------------------------------------------------------------


def chart_section(state: dict, data: dict) -> str:
    runs = data.get("runs", [])
    mode = state["mode"]
    primary = runs[0] if runs else None

    title = "Matchup" if mode == "matchup" else "Forecast"
    who = (f"{len(runs)} MODELS" if mode == "matchup"
           else (data["models_by_slug"].get(state["selected"][0], {}).get("name", "")
                 .upper() if state["selected"] else ""))
    meta = f'{state["asset"]} · {state["tf"]} · H+{state["horizon"]} · {who}'

    # The capability gate, in one place. `ghost_capable` is true when the
    # *selected* model declares OHLCV paths -- not when a result happens to
    # carry them.
    emits_paths = bool(primary
                       and primary.capabilities.get("output") == "ohlcv_paths"
                       and mode == "playground")
    # A model can emit paths and still have none to draw: forecasts archived
    # before paths were stored keep their quantiles and nothing else. Offering
    # a toggle that renders nothing is worse than saying why it is empty.
    paths_missing = bool(emits_paths and primary.result.paths is None)
    ghost_capable = emits_paths and not paths_missing
    ghost_locked = bool(primary
                        and primary.capabilities.get("output") != "ohlcv_paths"
                        and mode == "playground")

    if ghost_capable:
        on = state.get("ghosts", True)
        toggle = (
            f'<button {bit("ghosts", "toggle")} style="display:inline-flex;'
            'align-items:center;gap:6px;padding:3px 8px;background:'
            f'{"var(--bg-raised)" if on else "transparent"};'
            f'border:1px solid {"var(--accent-amber)" if on else "var(--border-default)"};'
            f'color:{"var(--accent-amber-strong)" if on else "var(--text-secondary)"};'
            'cursor:pointer">'
            f'<span class="mono-data" style="font-size:var(--text-2xs)">{"✓" if on else ""}</span>'
            f'<span style="{STYRENE};font-size:var(--text-xs)">Sampled OHLCV paths</span>'
            '</button>')
    elif paths_missing:
        toggle = (
            '<span style="display:inline-flex;align-items:center;gap:6px;padding:3px 8px;'
            'border:1px dashed var(--border-default);color:var(--text-disabled)" '
            'title="This forecast predates path archiving. Run it again to get them.">'
            '<span class="mono-data" style="font-size:var(--text-2xs)">✕</span>'
            f'<span style="{STYRENE};font-size:var(--text-xs)">'
            'Paths not archived — forecast again to see them</span></span>')
    elif ghost_locked:
        toggle = (
            '<span style="display:inline-flex;align-items:center;gap:6px;padding:3px 8px;'
            'border:1px dashed var(--border-default);color:var(--text-disabled)">'
            '<span class="mono-data" style="font-size:var(--text-2xs)">✕</span>'
            f'<span style="{STYRENE};font-size:var(--text-xs)">'
            'Quantile line only — no OHLCV paths</span></span>')
    else:
        toggle = ""

    if primary:
        frozen = (f'FROZEN {primary.issued_ts.strftime("%Y-%m-%d %H:%M")} UTC · '
                  f'SEED {primary.result.seed}')
    else:
        frozen = "NO FORECAST ISSUED YET"

    # A forecast rebuilt from the archive has to say how old it is. Showing
    # only its issue timestamp reads as current at a glance.
    provenance = ""
    if primary is not None and getattr(primary, "from_cache", False):
        age = view.age_label(primary.issued_ts)
        badge = "LAST ARCHIVED"
        if getattr(primary, "backfilled", False):
            badge = "LAST ARCHIVED · BACKFILL"
        provenance = (
            '<span style="display:inline-flex;align-items:center;gap:6px;'
            'padding:3px 8px;border:1px solid var(--border-default);'
            'background:var(--bg-raised)">'
            f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(badge)}</span>'
            f'<span class="mono-data" style="font-size:var(--text-2xs);'
            f'color:var(--accent-amber-strong)">ISSUED {e(age.upper())}</span></span>')

        # How it is actually doing. The point of showing an old forecast is
        # that the answer is already partly known.
        score = view.live_scorecard(primary)
        if score:
            err = (f' · {score["median_err"]:.2f}% ERR'
                   if score["median_err"] is not None else "")
            provenance += (
                '<span style="display:inline-flex;align-items:center;gap:6px;'
                f'padding:3px 8px;border:1px solid {a(score["colour"])}">'
                f'<span class="mono-data" style="font-size:var(--text-2xs);'
                f'color:{a(score["colour"])}">{e(score["label"])}{e(err)}</span>'
                f'<span class="pixel-text" style="color:var(--text-tertiary)">'
                f'{e(score["note"].upper())}</span></span>')

    drawing = data.get("chart") or {}
    body = _chart_body(drawing) if drawing.get("svg") else _chart_empty(data)

    return (
        f'<section style="{PANEL}">'
        '<div style="display:flex;align-items:center;gap:10px;padding:8px 12px;'
        'border-bottom:1px solid var(--border-default);flex-wrap:wrap">'
        f'<span style="{STYRENE};font-size:var(--text-md)">{e(title)}</span>'
        f'<span class="mono-data" style="font-size:var(--text-xs);'
        'color:var(--text-secondary);padding:2px 7px;'
        f'border:1px solid var(--border-default)">{e(meta)}</span>'
        '<div style="display:flex;align-items:center;gap:8px;margin-left:auto;'
        f'flex-wrap:wrap">{provenance}{toggle}'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary)">{e(frozen)}</span></div></div>'
        f'{_legend(data)}{body}</section>'
    )


def _legend(data: dict) -> str:
    runs = data.get("runs", [])
    if not runs:
        return ""
    items = []
    for i, run in enumerate(runs):
        color = chart.series_color(i)
        panel = data["panels"].get(run.model_slug, {})
        name = data["models_by_slug"].get(run.model_slug, {}).get("name", run.model_slug)
        width = panel.get("width")
        band = (f'10 / 50 / 90 · {pct(width, 1)} MEAN WIDTH' if width is not None
                else "10 / 50 / 90")
        grade = panel.get("grade", "-")
        dash = chart.FAN_DASH[i % 3] if len(runs) > 1 else "none"
        items.append(
            '<div style="display:flex;align-items:center;gap:8px">'
            '<svg width="34" height="12" viewBox="0 0 34 12" '
            'style="flex:0 0 auto;display:block">'
            f'<rect x="0" y="2" width="34" height="8" fill="{a(color)}" opacity="0.16"></rect>'
            f'<line x1="0" y1="6" x2="34" y2="6" stroke="{a(color)}" '
            f'stroke-width="1.6" stroke-dasharray="{a(dash)}"></line></svg>'
            f'<span style="{STYRENE};font-size:var(--text-sm)">{e(name)}</span>'
            f'<span class="mono-data" style="font-size:var(--text-2xs);'
            f'color:var(--text-tertiary)">{e(band)}</span>'
            f'<span class="mono-data" style="font-size:var(--text-xs);'
            f'color:{a(grade_color(grade))};border:1px solid {a(grade_color(grade))};'
            f'padding:1px 5px">{e(grade)}</span>'
            f'<span style="font-size:var(--text-2xs);'
            f'color:{a(panel.get("verdict_color", "var(--text-tertiary)"))}">'
            f'{e(panel.get("verdict_short", ""))}</span></div>')
    return ('<div style="display:flex;align-items:center;gap:14px;padding:7px 12px;'
            'border-bottom:1px solid var(--border-subtle);background:var(--bg-raised);'
            f'flex-wrap:wrap">{"".join(items)}</div>')


def _chart_body(drawing: dict) -> str:
    axis = "".join(
        f'<span class="mono-data" style="position:absolute;right:6px;top:{a(g["top"])};'
        'transform:translateY(-50%);font-size:var(--text-2xs);'
        f'color:var(--text-tertiary);white-space:nowrap">{e(g["label"])}</span>'
        for g in drawing.get("grid", []))
    times = "".join(
        f'<span class="mono-data" style="position:absolute;left:{a(t["left"])};'
        'transform:translateX(-50%);font-size:var(--text-2xs);'
        f'color:var(--text-tertiary);white-space:nowrap">{e(t["label"])}</span>'
        for t in drawing.get("time_labels", []))
    left = a(drawing.get("now_left", "50%"))
    return (
        '<div class="fa-chart"><div style="position:relative;flex:1 1 auto;min-width:0">'
        f'{drawing["svg"]}'
        f'<span class="mono-data" style="position:absolute;left:{left};top:5px;'
        'transform:translateX(-100%);padding-right:6px;font-size:var(--text-2xs);'
        f'color:var(--accent-amber-strong);white-space:nowrap">'
        f'{e(drawing.get("boundary_label", "NOW"))} '
        f'{e(drawing.get("now_time", ""))}</span>'
        f'<span class="mono-data" style="position:absolute;left:{left};top:5px;'
        'padding-left:6px;font-size:var(--text-2xs);color:var(--text-tertiary);'
        'white-space:nowrap">FORECAST →</span>'
        '<span class="mono-data" style="position:absolute;left:4px;top:76%;'
        'font-size:var(--text-2xs);color:var(--text-tertiary)">VOLUME</span>'
        '<div style="position:absolute;left:0;right:0;bottom:0;height:16px">'
        f'{times}</div></div>'
        f'<div class="fa-axis">{axis}</div></div>')


def _chart_empty(data: dict) -> str:
    err = data.get("error")
    if err:
        return _error_state(err)
    return (
        '<div style="display:flex;flex-direction:column;align-items:center;gap:8px;'
        'padding:52px 16px;background:var(--bg-sunken)">'
        '<span class="mono-data" style="font-size:var(--text-2xl);'
        'color:var(--text-disabled)">▱</span>'
        f'<span style="{STYRENE};font-size:var(--text-md);color:var(--text-secondary)">'
        'No forecast issued</span>'
        '<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
        'text-align:center;max-width:340px;text-wrap:pretty">'
        'Pick a model and press Forecast. The result is frozen at issue and '
        'archived before it is drawn.</span></div>')


def _error_state(err: dict) -> str:
    """The designed failure states: quota, load failure, rejected enrollment."""
    kind = err.get("kind", "load_failure")
    glyph = {"quota": "⚠", "load_failure": "✕", "enroll": "✕",
             "no_data": "∅", "no_gpu": "⚠"}.get(kind, "✕")
    color = {"quota": "var(--mute-orange)",
             "no_gpu": "var(--mute-orange)"}.get(kind, "var(--fin-down)")
    extra = ""
    if kind == "quota":
        extra = (f'<a href="{a(err.get("login_url", "#"))}" '
                 'style="font-family:var(--font-mono);font-size:var(--text-2xs)">'
                 'SIGN IN ↗</a>')
    elif kind == "no_gpu":
        # Nothing the visitor can do here, so the only honest offer is a Space
        # they control with hardware they choose.
        extra = (f'<a href="{a(err.get("duplicate_url", "#"))}" target="_blank" '
                 'rel="noopener" style="font-family:var(--font-mono);'
                 'font-size:var(--text-2xs)">RUN IT ON YOUR OWN HARDWARE ↗</a>')
    elif kind == "load_failure":
        # A model that will not load on this hardware is not always a bug in
        # the Space: duplicating it gives the user a box they control.
        extra = (f'<a href="{a(err.get("duplicate_url", "#"))}" target="_blank" '
                 'rel="noopener" style="font-family:var(--font-mono);'
                 'font-size:var(--text-2xs)">DUPLICATE THIS SPACE ↗</a>')
    return (
        '<div style="display:flex;flex-direction:column;align-items:center;gap:9px;'
        'padding:44px 16px;background:var(--bg-sunken)">'
        f'<span class="mono-data" style="font-size:var(--text-2xl);color:{a(color)}">'
        f'{e(glyph)}</span>'
        f'<span style="{STYRENE};font-size:var(--text-md);color:var(--text-secondary)">'
        f'{e(err.get("title", "Forecast failed"))}</span>'
        '<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
        'text-align:center;max-width:420px;text-wrap:pretty">'
        f'{e(err.get("message", ""))}</span>'
        f'<div style="display:flex;gap:10px;align-items:center">{extra}'
        f'<button {bit("dismiss", "error")} style="padding:3px 9px;'
        'background:transparent;border:1px solid var(--border-default);'
        'color:var(--text-secondary);cursor:pointer;font-family:var(--font-mono);'
        'font-size:var(--text-2xs)">DISMISS</button></div></div>')


# --------------------------------------------------------------------------
# Track record
# --------------------------------------------------------------------------


def trackrecord_section(state: dict, data: dict) -> str:
    mode = state["mode"]
    slugs = state["selected"]
    scope = (f'{state["asset"]} · {state["tf"]} · H+{state["horizon"]} · '
             f'LAST {view.THUMBS} RESOLVED').upper()

    if mode == "matchup" and len(slugs) > 1:
        question = "Same stats, side by side — best in row highlighted."
        body = _scoreboard(state, data)
    else:
        primary = slugs[0] if slugs else None
        panel = data["panels"].get(primary, {})
        name = data["models_by_slug"].get(primary, {}).get("name", primary or "")
        question = f"How wrong has {name} been here recently?"
        body = _empty_record() if panel.get("empty", True) else _playground_record(panel, data)

    return (
        f'<section style="{PANEL}">'
        '<div style="display:flex;align-items:center;gap:10px;padding:8px 12px;'
        'border-bottom:1px solid var(--border-default);'
        'border-left:3px solid var(--accent-amber);flex-wrap:wrap">'
        f'<span style="{STYRENE};font-size:var(--text-md)">Track record</span>'
        f'<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
        f'{e(question)}</span>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary);margin-left:auto">{e(scope)}</span></div>'
        f'{body}</section>')


def _empty_record() -> str:
    return (
        '<div style="display:flex;flex-direction:column;align-items:center;gap:8px;'
        'padding:26px 16px">'
        '<span class="mono-data" style="font-size:var(--text-2xl);'
        'color:var(--text-disabled)">∅</span>'
        f'<span style="{STYRENE};font-size:var(--text-md);color:var(--text-secondary)">'
        'No history yet</span>'
        '<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
        'text-align:center;max-width:340px;text-wrap:pretty">Forecasts made here start '
        'the record. The first resolved forecast for this model, asset and timeframe '
        'appears in this panel.</span>'
        f'<button {bit("run", "go")} style="margin-top:2px;padding:4px 9px;'
        'background:transparent;border:1px solid var(--border-default);'
        'color:var(--text-secondary);cursor:pointer;font-family:var(--font-mono);'
        'font-size:var(--text-2xs)">MAKE THE FIRST FORECAST →</button></div>')


def _playground_record(panel: dict, data: dict) -> str:
    stats = [
        ("Empirical 80% coverage", pct(panel.get("coverage")),
         f'target 80% · {count(panel.get("resolved"))} resolved',
         panel.get("verdict_color", "var(--text-primary)")),
        ("Median abs error", pct(panel.get("median_err", 0) / 100
                                 if panel.get("median_err") is not None else None, 2),
         "at horizon close", "var(--text-primary)"),
        ("Mean band width", pct(panel.get("width"), 1),
         "10→90 span, % of price", "var(--text-primary)"),
        ("Backfilled share", pct(panel.get("backfilled_share")),
         "labelled in the record", "var(--mute-blue)"),
    ]
    stat_html = "".join(
        '<div style="padding:9px 12px;border-right:1px solid var(--border-subtle)">'
        f'<div style="{STYRENE};font-weight:300;font-size:var(--text-2xs);'
        f'letter-spacing:var(--tracking-wider);color:var(--text-tertiary)">{e(label)}</div>'
        f'<div class="mono-data" style="font-size:var(--text-xl);line-height:1.2;'
        f'color:{a(color)}">{e(value)}</div>'
        f'<div style="font-size:var(--text-2xs);color:var(--text-tertiary)">{e(note)}</div>'
        '</div>'
        for label, value, note, color in stats)

    cells = "".join(_thumb(t, data) for t in panel.get("thumbs", []))
    vcolor = panel.get("verdict_color", "var(--text-tertiary)")

    return (
        '<div><div style="display:grid;'
        'grid-template-columns:repeat(auto-fit,minmax(168px,1fr));'
        f'border-bottom:1px solid var(--border-default)">{stat_html}</div>'
        f'<div class="fa-trstrip">{cells}</div>'
        '<div style="display:flex;align-items:center;gap:10px;padding:7px 12px;'
        'border-top:1px solid var(--border-subtle);background:var(--bg-raised);'
        'flex-wrap:wrap">'
        f'<span class="mono-data" style="font-size:var(--text-xs);'
        f'color:{a(vcolor)};border:1px solid {a(vcolor)};padding:2px 7px">'
        f'{e(panel.get("verdict", ""))}</span>'
        '<span style="font-size:var(--text-xs);color:var(--text-secondary);'
        f'text-wrap:pretty">{e(_verdict_note(panel))}</span>'
        f'<a href="{a(data.get("store_url", "#"))}" target="_blank" rel="noopener" '
        'style="margin-left:auto;font-family:var(--font-mono);font-size:var(--text-2xs);'
        f'white-space:nowrap">ALL {e(count(panel.get("total")))} ARCHIVED ↗</a>'
        '</div></div>')


def _verdict_note(panel: dict) -> str:
    coverage = panel.get("coverage")
    if coverage is None:
        return ("Not enough resolved forecasts here to say anything about "
                "calibration yet.")
    gap = coverage - config.NOMINAL_COVERAGE
    if abs(gap) <= 0.05:
        return ("Bands hold up on this pair: the realized path stayed inside the "
                "80% envelope about as often as it should.")
    if gap < 0:
        return ("Bands are narrower than the realized error justifies here. "
                "Read the median, not the confidence.")
    return ("Bands are wider than the realized error justifies here — the model "
            "is hedging more than this pair has needed.")


def _thumb(t: dict, data: dict) -> str:
    spark = t["spark"]
    backfill = ('<span class="pixel-text" style="color:var(--mute-blue);'
                'margin-left:auto">BACKFILL</span>' if t["backfilled"] else "")
    return (
        f'<div class="fa-trcell{" miss" if t["miss"] else ""}">'
        '<div style="display:flex;align-items:center;gap:5px">'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary)">{e(t["date"])}</span>'
        f'<span class="mono-data" style="font-size:var(--text-xs);'
        f'color:{a(t["hit_color"])};margin-left:auto">{e(t["hit"])}</span></div>'
        '<svg width="94" height="38" viewBox="0 0 94 38" style="display:block">'
        f'<path d="{a(spark["band"])}" fill="var(--accent-amber-strong)" opacity="0.2"></path>'
        f'<path d="{a(spark["mid"])}" fill="none" stroke="var(--accent-amber-strong)" '
        'stroke-width="1.2" stroke-dasharray="3 2"></path>'
        f'<path d="{a(spark["real"])}" fill="none" stroke="var(--text-primary)" '
        'stroke-width="1.4"></path></svg>'
        '<div style="display:flex;align-items:center;gap:4px">'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-secondary)">{e(t["err"])}</span>{backfill}</div></div>')


def _scoreboard(state: dict, data: dict) -> str:
    """The matchup table: same stats, aligned, best in row highlighted."""
    slugs = [s for s in state["selected"] if s in data["panels"]]
    if not slugs:
        return _empty_record()
    panels = [data["panels"][s] for s in slugs]
    cols = f'1.15fr repeat({len(slugs)},minmax(0,1fr))'

    heads = "".join(
        '<div style="padding:7px 12px;border-right:1px solid var(--border-subtle);'
        f'border-top:3px solid {a(chart.series_color(i))};display:flex;'
        'align-items:center;gap:7px">'
        f'<span style="{STYRENE};font-size:var(--text-sm);white-space:nowrap;'
        'overflow:hidden;text-overflow:ellipsis">'
        f'{e(data["models_by_slug"].get(s, {}).get("name", s))}</span>'
        f'<span class="mono-data" style="font-size:var(--text-xs);'
        f'color:{a(grade_color(p.get("grade", "-")))};'
        f'border:1px solid {a(grade_color(p.get("grade", "-")))};'
        f'padding:1px 5px;margin-left:auto">{e(p.get("grade", "-"))}</span></div>'
        for i, (s, p) in enumerate(zip(slugs, panels)))

    # (label, hint, value fn, "best" fn or None). Coverage is scored on
    # distance from nominal, not on being highest -- a narrower band is not a
    # better one, and the design says so on the page.
    rows = [
        ("80% band coverage", "TARGET 80%",
         lambda p: pct(p.get("coverage")),
         lambda p: (-abs(p["coverage"] - config.NOMINAL_COVERAGE)
                    if p.get("coverage") is not None else None)),
        ("Median abs error", "LOWER BETTER",
         lambda p: pct(p["median_err"] / 100 if p.get("median_err") is not None else None, 2),
         lambda p: (-p["median_err"] if p.get("median_err") is not None else None)),
        ("Mean band width", "CONTEXT ONLY",
         lambda p: pct(p.get("width"), 1), None),
        ("Resolved forecasts", "SAMPLE SIZE",
         lambda p: count(p.get("resolved")),
         lambda p: p.get("resolved")),
        ("Calibration verdict", "FROM RESOLVED ONLY",
         lambda p: p.get("verdict", DASH), None),
    ]

    body = []
    for label, hint, value_of, best_of in rows:
        best_index = None
        if best_of is not None:
            scored = [(i, best_of(p)) for i, p in enumerate(panels)]
            scored = [(i, v) for i, v in scored if v is not None]
            if scored:
                best_index = max(scored, key=lambda kv: kv[1])[0]
        cells = []
        for i, p in enumerate(panels):
            is_best = i == best_index
            fg = ("var(--accent-moss-strong)" if is_best else "var(--text-primary)")
            if label.startswith("Calibration"):
                fg = p.get("verdict_color", "var(--text-primary)")
            cells.append(
                '<div style="padding:7px 12px;border-right:1px solid var(--border-subtle);'
                f'background:{"var(--bg-raised)" if is_best else "transparent"};'
                'display:flex;align-items:center;gap:7px">'
                f'<span class="mono-data" style="font-size:var(--text-md);'
                f'color:{a(fg)}">{e(value_of(p))}</span>'
                '<span class="mono-data" style="font-size:var(--text-2xs);'
                f'color:var(--text-tertiary);margin-left:auto">{"BEST" if is_best else ""}</span>'
                '</div>')
        body.append(
            f'<div style="display:grid;grid-template-columns:{cols};'
            'border-bottom:1px solid var(--border-subtle)">'
            '<div style="padding:7px 12px;border-right:1px solid var(--border-subtle);'
            'display:flex;flex-direction:column;gap:1px">'
            f'<span style="{STYRENE};font-weight:300;font-size:var(--text-xs);'
            f'color:var(--text-secondary)">{e(label)}</span>'
            f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(hint)}</span>'
            f'</div>{"".join(cells)}</div>')

    return (
        f'<div><div style="display:grid;grid-template-columns:{cols};'
        'border-bottom:1px solid var(--border-default);background:var(--bg-raised)">'
        '<div style="padding:7px 12px;border-right:1px solid var(--border-subtle)">'
        '<span class="pixel-text" style="color:var(--text-tertiary)">METRIC</span></div>'
        f'{heads}</div>{"".join(body)}'
        '<div style="display:flex;align-items:center;gap:10px;padding:7px 12px;'
        'background:var(--bg-raised);flex-wrap:wrap">'
        '<span class="pixel-text" style="color:var(--accent-amber-strong)">i</span>'
        '<span style="font-size:var(--text-xs);color:var(--text-secondary);'
        'text-wrap:pretty">Highlighted cell is best in row. Coverage closest to 80% '
        'wins — a narrower band is not a better one.</span></div></div>')


# --------------------------------------------------------------------------
# Rail
# --------------------------------------------------------------------------


def rail(state: dict, data: dict) -> str:
    return ('<aside class="fa-rail">'
            f'{_standings(state, data)}{_volatility(data)}{_log(state, data)}'
            f'{_extend(state, data)}{_enroll(state, data)}</aside>')


def _standings(state: dict, data: dict) -> str:
    rows = data.get("standings_rows", [])
    enrolled = len(data.get("models", []))

    tabs = "".join(
        f'<button {bit("cls", c)} style="flex:1 1 auto;padding:4px 5px;'
        f'background:{"var(--bg-raised)" if state["cls"] == c else "transparent"};'
        'border:0;border-right:1px solid var(--border-subtle);'
        f'color:{"var(--accent-amber-strong)" if state["cls"] == c else "var(--text-tertiary)"};'
        f'{STYRENE};font-size:var(--text-2xs);cursor:pointer">{e(c)}</button>'
        for c in ("All", "Crypto", "Equities"))

    if rows:
        body = "".join(
            f'<button {bit("stand", r["slug"])} class="fa-stand'
            f'{" on" if r["selected"] else ""}" '
            f'style="border-left-color:{a(chart.series_color(0)) if r["selected"] else "transparent"}">'
            f'<span class="mono-data" style="font-size:var(--text-2xs);'
            f'color:var(--text-tertiary);flex:0 0 auto">{e(r["rank"])}</span>'
            '<span class="fa-stand-mid">'
            f'<span class="mono-data fa-stand-name">{e(r["name"])}</span>'
            f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(r["meta"])}</span>'
            '</span>'
            f'<span class="mono-data" style="font-size:var(--text-md);'
            f'color:{a(r["grade_color"])};flex:0 0 auto">{e(r["grade"])}</span></button>'
            for r in rows)
    else:
        body = ('<div style="padding:18px 10px;text-align:center">'
                '<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
                'text-wrap:pretty">No forecasts have resolved yet. Standings appear '
                'once the resolver has outcomes to score.</span></div>')

    right = ('<span class="mono-data" style="font-size:var(--text-2xs);'
             f'color:var(--text-tertiary);margin-left:auto">{enrolled} ENROLLED</span>')

    return (
        f'<div style="{PANEL}">'
        f'{_panel_title("Arena standings", right)}'
        f'<div style="display:flex;border-bottom:1px solid var(--border-subtle)">{tabs}</div>'
        f'{body}'
        '<div style="padding:6px 10px;display:flex;align-items:center">'
        '<span class="pixel-text" style="color:var(--text-tertiary)">'
        'GRADES FROM RESOLVED FORECASTS ONLY</span>'
        f'<a href="{a(data.get("standings_url", "#"))}" target="_blank" rel="noopener" '
        'style="margin-left:auto;font-family:var(--font-mono);font-size:var(--text-2xs)">'
        'FULL TABLE ↗</a></div></div>')


def _volatility(data: dict) -> str:
    vol = data.get("volatility") or {}
    rows = vol.get("rows", [])
    if not rows:
        return ""
    body = "".join(
        '<div style="display:flex;flex-direction:column;gap:4px">'
        '<div style="display:flex;align-items:center;gap:8px">'
        f'<span style="{STYRENE};font-weight:300;font-size:var(--text-2xs);'
        f'color:var(--text-secondary)">{e(r["label"])}</span>'
        f'<span class="mono-data" style="font-size:var(--text-xs);'
        f'color:{a(r["fg"])};margin-left:auto">{e(r["value"])}</span></div>'
        '<div style="height:5px;background:var(--bg-sunken);'
        'border:1px solid var(--border-subtle);position:relative;overflow:hidden">'
        f'<div style="position:absolute;left:0;top:0;bottom:0;width:{a(r["pct"])};'
        f'background:{a(r["fg"])}"></div></div></div>'
        for r in rows)
    right = ('<span class="mono-data" style="font-size:var(--text-2xs);'
             f'color:var(--text-tertiary);margin-left:auto">{e(vol.get("verdict", ""))}</span>')
    return (
        f'<div style="{PANEL}">{_panel_title("Volatility read", right)}'
        '<div style="padding:10px;display:flex;flex-direction:column;gap:9px">'
        f'{body}'
        '<span style="font-size:var(--text-2xs);color:var(--text-tertiary);'
        f'text-wrap:pretty">{e(vol.get("note", ""))}</span></div></div>')


def _log(state: dict, data: dict) -> str:
    entries = state.get("log", [])[:view.LOG_LIMIT]
    if entries:
        body = "".join(
            '<div style="display:flex;align-items:center;gap:8px;padding:6px 10px;'
            'border-bottom:1px solid var(--border-subtle)">'
            f'<span class="mono-data" style="font-size:var(--text-2xs);'
            f'color:var(--text-tertiary);flex:0 0 auto">{e(l["time"])}</span>'
            '<span class="fa-stand-mid">'
            f'<span class="mono-data fa-stand-name">{e(l["name"])}</span>'
            f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(l["meta"])}</span>'
            '</span>'
            f'<button {bit("reopen", l["id"])} style="background:transparent;border:0;'
            'color:var(--accent-amber-strong);cursor:pointer;font-family:var(--font-mono);'
            'font-size:var(--text-2xs);flex:0 0 auto">RE-OPEN</button></div>'
            for l in entries)
    else:
        body = ('<div style="padding:14px 10px">'
                '<span style="font-size:var(--text-xs);color:var(--text-tertiary)">'
                'Forecasts you issue this session appear here.</span></div>')
    right = ('<span class="mono-data" style="font-size:var(--text-2xs);'
             'color:var(--text-tertiary);margin-left:auto">THIS SESSION</span>')
    return (
        f'<div style="{PANEL}">{_panel_title("Forecast log", right)}{body}'
        '<div style="padding:6px 10px">'
        '<span class="pixel-text" style="color:var(--text-tertiary)">'
        'ARCHIVED IMMUTABLY · SEED + CONFIG SAVED</span></div></div>')


def _extend(state: dict, data: dict) -> str:
    cov = data.get("coverage") or {}
    pct_label = cov.get("pct_label", DASH)
    width = cov.get("pct_width", "0%")
    rows = "".join(
        '<div style="display:flex;align-items:center;gap:8px">'
        f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(label)}</span>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-secondary);margin-left:auto">{e(value)}</span></div>'
        for label, value in cov.get("rows", []))

    label = "Contribute a backfill run (uses your quota)"
    note = state.get("backfill_note")
    note_html = (f'<span class="mono-data" style="font-size:var(--text-2xs);'
                 f'color:var(--accent-moss-strong);text-wrap:pretty">{e(note)}</span>'
                 if note else "")
    return (
        f'<div style="{PANEL}">{_panel_title("Extend the record")}'
        '<div style="padding:10px;display:flex;flex-direction:column;gap:8px">'
        '<div style="display:flex;align-items:center;gap:8px">'
        f'<span style="font-size:var(--text-xs);color:var(--text-secondary)">'
        f'{e(cov.get("scope", ""))}</span>'
        f'<span class="mono-data" style="font-size:var(--text-md);'
        f'color:var(--accent-amber-strong);margin-left:auto">{e(pct_label)}</span></div>'
        '<div style="height:6px;background:var(--bg-sunken);'
        'border:1px solid var(--border-subtle);position:relative;overflow:hidden">'
        f'<div style="position:absolute;left:0;top:0;bottom:0;width:{a(width)};'
        'background:var(--accent-amber)"></div></div>'
        f'<div style="display:flex;flex-direction:column;gap:3px">{rows}</div>'
        f'<button {bit("backfill", "run")} style="width:100%;padding:6px;'
        'background:transparent;border:1px solid var(--border-default);'
        f'color:var(--text-secondary);cursor:pointer;{STYRENE};'
        f'font-size:var(--text-xs)">{e(label)}</button>'
        f'{note_html}'
        '<span class="pixel-text" style="color:var(--text-tertiary)">'
        'BACKFILLED ENTRIES ARE LABELLED IN THE RECORD</span></div></div>')


def _enroll(state: dict, data: dict) -> str:
    note = state.get("enroll_note") or "A smoke test runs before a model is enrolled"
    ok = state.get("enroll_ok")
    color = ("var(--accent-moss-strong)" if ok else
             "var(--fin-down)" if ok is False else "var(--text-tertiary)")

    families = "".join(
        f'<button {bit("family", f)} class="fa-pill'
        f'{" on" if state.get("family") == f else ""}" '
        f'style="font-size:var(--text-2xs)">{e(f)}</button>'
        for f in data.get("families", ()))

    return (
        f'<div style="{PANEL}">{_panel_title("Enroll a model")}'
        '<div style="padding:10px;display:flex;flex-direction:column;gap:8px">'
        f'<input value="{a(state.get("hfid", ""))}" '
        f'data-bit-input="hfid" placeholder="author/model-name" '
        'style="width:100%;padding:5px 7px;background:var(--bg-sunken);'
        'border:1px solid var(--border-default);outline:none;'
        'font-family:var(--font-mono);font-size:var(--text-xs);'
        'color:var(--text-primary)" />'
        f'<div style="display:flex;gap:4px;flex-wrap:wrap">{families}</div>'
        '<div style="display:flex;align-items:center;gap:7px">'
        f'<button {bit("enroll", "run")} style="padding:5px 10px;'
        'background:transparent;border:1px solid var(--border-default);'
        f'color:var(--text-secondary);cursor:pointer;{STYRENE};'
        'font-size:var(--text-xs)">Smoke-test</button></div>'
        f'<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:{a(color)};text-wrap:pretty">{e(note)}</span>'
        '<span style="font-size:var(--text-2xs);color:var(--text-tertiary);'
        'text-wrap:pretty">Only models loadable through a vetted adapter family are '
        'accepted. No user-supplied code is ever executed.</span></div></div>')


# --------------------------------------------------------------------------
# Footer
# --------------------------------------------------------------------------


def methodology(data: dict) -> str:
    return (
        '<div style="display:flex;align-items:flex-start;gap:10px;padding:9px 12px;'
        'border:1px solid var(--border-subtle);background:var(--bg-panel)">'
        '<span class="pixel-text" style="color:var(--accent-amber-strong);'
        'flex:0 0 auto;margin-top:2px">i</span>'
        '<span style="font-size:var(--text-xs);color:var(--text-secondary);'
        'text-wrap:pretty">Forecasts are frozen at issue and never revised; quantiles '
        'from N sampled paths where applicable; seeds shown; backfilled entries '
        'labelled; grades computed from resolved forecasts only. Nothing here is '
        'financial advice.</span>'
        f'<a href="{a(data.get("methodology_url", "#"))}" target="_blank" rel="noopener" '
        'style="margin-left:auto;font-family:var(--font-mono);font-size:var(--text-2xs);'
        'white-space:nowrap;flex:0 0 auto">METHODOLOGY ↗</a></div>')


def footer(data: dict) -> str:
    nav = data.get("nav") or {}
    products = [i.get("name", "") for i in nav.get("items", [])][:12]
    prod_html = "".join(
        f'<span style="color:var(--text-secondary);font-size:var(--text-xs)">{e(p)}</span>'
        for p in products)
    resources = "".join(
        f'<a href="{a(url)}" target="_blank" rel="noopener" '
        f'style="color:var(--text-secondary);font-size:var(--text-xs)">{e(label)}</a>'
        for label, url in data.get("footer_resources", ()))

    return (
        f'<footer style="{PANEL}">'
        '<div class="fa-foot">'
        '<div style="padding:14px;border-right:1px solid var(--border-subtle)">'
        f'<div style="{STYRENE};font-size:var(--text-2xs);'
        'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
        'margin-bottom:8px">Products</div>'
        '<div style="display:grid;grid-template-columns:1fr 1fr;gap:3px 12px">'
        f'{prod_html}</div></div>'
        '<div style="padding:14px;border-right:1px solid var(--border-subtle)">'
        f'<div style="{STYRENE};font-size:var(--text-2xs);'
        'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
        'margin-bottom:8px">Resources</div>'
        '<div style="display:flex;flex-direction:column;gap:3px">'
        f'{resources}</div></div>'
        '<div style="padding:14px;border-right:1px solid var(--border-subtle)">'
        f'<div style="{STYRENE};font-size:var(--text-2xs);'
        'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
        'margin-bottom:8px">Method</div>'
        '<div style="display:flex;flex-direction:column;gap:3px">'
        '<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
        'Frozen at issue</span>'
        '<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
        'Seeded and reproducible</span>'
        '<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
        'Backfill labelled</span>'
        '<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
        'Graded on resolved only</span></div></div>'
        '<div style="padding:14px;background:var(--bg-raised)">'
        '<div style="display:flex;align-items:center;gap:6px;margin-bottom:8px">'
        '<span class="pixel-text" style="color:var(--accent-amber-strong)">⚠</span>'
        f'<span style="{STYRENE};font-size:var(--text-2xs);'
        'letter-spacing:var(--tracking-wider);color:var(--accent-amber-strong)">'
        'Disclaimer</span></div>'
        '<div class="styrene-text" style="font-size:var(--text-xs);'
        'text-transform:uppercase;letter-spacing:var(--tracking-wide);'
        'color:var(--text-secondary);line-height:var(--leading-normal);'
        'text-wrap:pretty">The Bit Trading Company publishes research tools and '
        'educational software. Nothing here is financial advice. Forecasts are model '
        'output, not predictions. Past performance does not predict future results.'
        '</div></div></div>'
        '<div style="display:flex;align-items:center;gap:14px;padding:8px 14px;'
        'border-top:1px solid var(--border-subtle);flex-wrap:wrap">'
        '<span style="display:inline-block;width:6px;height:6px;background:var(--fin-up);'
        'animation:bitPulse 2s ease-in-out infinite"></span>'
        '<span class="mono-data" style="font-size:var(--text-2xs);'
        f'color:var(--text-tertiary)">{e(data.get("status_line", ""))}</span>'
        '<span class="mono-data" style="font-size:var(--text-2xs);'
        'color:var(--text-tertiary);margin-left:auto">'
        '© 2026 THE BIT TRADING COMPANY</span></div></footer>')


# --------------------------------------------------------------------------
# The page
# --------------------------------------------------------------------------


def page(state: dict, data: dict) -> str:
    """The whole document body, from state. Pure -- no I/O anywhere below."""
    return (
        '<div class="bit-root" style="background:var(--bg-canvas);'
        'color:var(--text-primary);display:flex;align-items:stretch;'
        'font-family:var(--font-body);font-size:var(--text-base)">'
        f'{sidebar.render(data.get("nav") or {}, active="Forecast Arena", emit=emit)}'
        '<div style="flex:1 1 auto;min-width:0;display:flex;flex-direction:column">'
        f'{header(state, data)}'
        '<main style="flex:1 1 auto;min-width:0;padding:12px;display:flex;'
        'flex-direction:column;gap:12px">'
        f'{title_row(state, data)}'
        f'{stats_bar(data.get("stats", []))}'
        f'{models_section(state, data)}'
        f'{controls(state, data)}'
        '<div class="fa-zones">'
        '<div class="fa-main">'
        f'{chart_section(state, data)}'
        f'{trackrecord_section(state, data)}'
        '</div>'
        f'{rail(state, data)}'
        '</div>'
        f'{methodology(data)}'
        f'{footer(data)}'
        '</main></div></div>')