File size: 38,635 Bytes
f8506a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Why is this forecast this value? — AR decomposition explorer</title>
<style>
  :root {
    --bg: #0a0a12;
    --panel: #12121e;
    --border: #2a2a3a;
    --text: #e8e8f0;
    --dim: #8888a0;
    --accent: #6cf;
    --good: #6cdc78;
    --bad: #ff5566;
    --obs: #7ab8ff;
  }
  * { box-sizing: border-box; }
  body {
    margin: 0;
    background: var(--bg);
    color: var(--text);
    font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;
    font-size: 14px;
    line-height: 1.55;
  }
  header {
    padding: 18px 24px;
    border-bottom: 1px solid var(--border);
  }
  header h1 {
    margin: 0 0 4px;
    font-size: 18px;
    font-weight: 600;
  }
  header p {
    margin: 0;
    color: var(--dim);
    font-size: 13px;
    max-width: 900px;
  }
  header code {
    background: #1e1e2e;
    padding: 1px 5px;
    border-radius: 3px;
    font-size: 12px;
  }
  main {
    display: grid;
    grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr);
    gap: 16px;
    padding: 16px;
    max-width: 1600px;
    margin: 0 auto;
  }
  @media (max-width: 1100px) {
    main { grid-template-columns: 1fr; }
  }
  .col { display: flex; flex-direction: column; gap: 16px; }
  .panel {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 8px;
    overflow: hidden;
  }
  .panel-header {
    padding: 10px 14px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
  }
  .panel-header h2 {
    margin: 0;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--dim);
  }
  .controls {
    display: flex;
    gap: 10px;
    align-items: center;
    flex-wrap: wrap;
    font-size: 12px;
  }
  .controls label {
    display: flex;
    align-items: center;
    gap: 5px;
    color: var(--dim);
  }
  .controls input[type=range] {
    width: 80px;
    accent-color: var(--accent);
  }
  .controls select, .controls input[type=file] {
    background: #0e0e1a;
    color: var(--text);
    border: 1px solid var(--border);
    border-radius: 4px;
    padding: 3px 8px;
    font-size: 12px;
    font-family: inherit;
  }
  .controls input[type=file] {
    padding: 2px 6px;
    cursor: pointer;
  }
  .controls input[type=file]::file-selector-button {
    background: #1e1e2e;
    color: var(--text);
    border: 1px solid var(--border);
    border-radius: 3px;
    padding: 3px 8px;
    font-family: inherit;
    font-size: 11px;
    cursor: pointer;
    margin-right: 6px;
  }
  canvas {
    display: block;
    width: 100%;
    height: auto;
    background: #080810;
  }
  #mainCanvas { cursor: crosshair; }
  .hint {
    padding: 9px 14px;
    font-size: 11.5px;
    color: var(--dim);
    border-top: 1px solid var(--border);
    background: rgba(255,255,255,0.02);
    line-height: 1.5;
  }
  .hint b { color: var(--text); }
  #explanation {
    padding: 14px 16px;
    font-size: 13px;
    max-height: 400px;
    overflow-y: auto;
  }
  #explanation h3 {
    margin: 0 0 10px;
    font-size: 13px;
    color: var(--accent);
    font-weight: 600;
  }
  #explanation p { margin: 8px 0; }
  .verdict {
    padding: 8px 12px;
    border-radius: 4px;
    margin: 10px 0;
    font-weight: 600;
    font-size: 13px;
  }
  .verdict.bad {
    background: rgba(255,85,102,0.12);
    color: #ff8a99;
    border-left: 3px solid #ff5566;
  }
  .verdict.good {
    background: rgba(102, 204, 255, 0.12);
    color: #9ddcff;
    border-left: 3px solid #6cf;
  }
  #explanation table {
    width: 100%;
    border-collapse: collapse;
    font-family: ui-monospace, monospace;
    font-size: 11.5px;
    margin: 8px 0;
  }
  #explanation th, #explanation td {
    text-align: right;
    padding: 3px 6px;
    border-bottom: 1px solid var(--border);
  }
  #explanation th:first-child,
  #explanation td:first-child { text-align: left; }
  #explanation th { color: var(--dim); font-weight: 500; }
  .note {
    color: var(--dim);
    font-size: 12px;
    border-top: 1px solid var(--border);
    padding-top: 10px;
    margin-top: 14px;
    line-height: 1.6;
  }
  kbd {
    background: #1e1e2e;
    border: 1px solid var(--border);
    border-radius: 3px;
    padding: 1px 5px;
    font-size: 10.5px;
    font-family: ui-monospace, monospace;
  }
</style>
</head>
<body>
<header>
  <h1>Why is this forecast this value?</h1>
  <p>
    Hover over the time series to see how each forecast point decomposes into
    contributions from the clamped past. The dashed cyan line is the
    <code>F<sup>h</sup></code> leap; red bands are <b>voids</b> (unobserved times)
    that coast rather than decay. Upload any CSV, pick a numeric column, set the
    AR order <code>p</code> and the horizon <code>h</code>.
  </p>
</header>
<main>
  <div class="col">
    <div class="panel">
      <div class="panel-header">
        <h2>Time series &amp; forecast</h2>
        <div class="controls">
          <input type="file" id="fileInput" accept=".csv,.txt,.tsv">
          <select id="colSelect" title="numeric column"></select>
          <label>p <input type="range" id="pSlider" min="1" max="6" value="2" step="1"><span id="pVal">2</span></label>
          <label>h <input type="range" id="hSlider" min="1" max="80" value="25" step="1"><span id="hVal">25</span></label>
        </div>
      </div>
      <canvas id="mainCanvas" width="960" height="460"></canvas>
      <div class="hint">
        <b>Blue dots</b>: observed (clamp rows). <b>Dashed cyan</b>: forecast
        (free boundary coasting on <code>F<sup>h</sup></code>). <b>Red bands</b>:
        gaps — treated as voids, not zeros. Drop a CSV onto the window to load it.
      </div>
    </div>
  </div>

  <div class="col">
    <div class="panel">
      <div class="panel-header"><h2>Decomposition of the hovered point</h2></div>
      <canvas id="attrCanvas" width="520" height="300"></canvas>
    </div>

    <div class="panel">
      <div class="panel-header"><h2>Spectrum — the arrow of time</h2></div>
      <canvas id="specCanvas" width="520" height="300"></canvas>
    </div>

    <div class="panel">
      <div id="explanation">
        <p style="color:var(--dim)">Hover over the time series to inspect a point.</p>
      </div>
    </div>
  </div>
</main>

<script>
"use strict";

// =====================================================================
// State
// =====================================================================
const state = {
  series: [],
  dataRows: null,
  header: null,
  numericCols: [],
  selectedCol: null,
  p: 2,
  horizon: 25,
  model: null,
  forecast: null,        // { forecast: [...], startT, state: [...] }
  hoverIdx: null,
};

// =====================================================================
// Canvas setup
// =====================================================================
const mainCanvas = document.getElementById("mainCanvas");
const mainCtx = mainCanvas.getContext("2d");
const attrCanvas = document.getElementById("attrCanvas");
const attrCtx = attrCanvas.getContext("2d");
const specCanvas = document.getElementById("specCanvas");
const specCtx = specCanvas.getContext("2d");
const explanationEl = document.getElementById("explanation");

const COL = {
  obs: "#7ab8ff",
  fc: "#6cf",
  pos: "rgba(108, 220, 120, 0.85)",
  neg: "rgba(255, 110, 130, 0.85)",
  gap: "rgba(255, 85, 102, 0.10)",
  grid: "#14141f",
  axis: "#2a2a3a",
};

// =====================================================================
// Small linear algebra (plain 2D arrays)
// =====================================================================
function zeros(n, m) { return Array.from({length: n}, () => new Array(m).fill(0)); }
function eye(n) { const I = zeros(n, n); for (let i = 0; i < n; i++) I[i][i] = 1; return I; }
function matmul(A, B) {
  const n = A.length, m = B[0].length, k = B.length;
  const C = zeros(n, m);
  for (let i = 0; i < n; i++)
    for (let j = 0; j < m; j++) {
      let s = 0;
      for (let q = 0; q < k; q++) s += A[i][q] * B[q][j];
      C[i][j] = s;
    }
  return C;
}
function matpow(A, k) {
  const n = A.length;
  let R = eye(n), B = A.map(r => r.slice());
  while (k > 0) {
    if (k & 1) R = matmul(R, B);
    B = matmul(B, B);
    k >>= 1;
  }
  return R;
}
function solveLinear(A, b) {
  const n = A.length;
  const M = A.map((row, i) => [...row, b[i]]);
  for (let col = 0; col < n; col++) {
    let pivot = col;
    for (let r = col + 1; r < n; r++)
      if (Math.abs(M[r][col]) > Math.abs(M[pivot][col])) pivot = r;
    if (Math.abs(M[pivot][col]) < 1e-12) return null;
    [M[col], M[pivot]] = [M[pivot], M[col]];
    const pv = M[col][col];
    for (let r = col + 1; r < n; r++) {
      const f = M[r][col] / pv;
      for (let c = col; c <= n; c++) M[r][c] -= f * M[col][c];
    }
  }
  const x = new Array(n).fill(0);
  for (let i = n - 1; i >= 0; i--) {
    let s = M[i][n];
    for (let j = i + 1; j < n; j++) s -= M[i][j] * x[j];
    x[i] = s / M[i][i];
  }
  return x;
}

// Complex helpers for polynomial roots
const cx = (re, im = 0) => ({ re, im });
const cadd = (a, b) => ({ re: a.re + b.re, im: a.im + b.im });
const csub = (a, b) => ({ re: a.re - b.re, im: a.im - b.im });
const cmul = (a, b) => ({ re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re });
const cdiv = (a, b) => {
  const d = b.re * b.re + b.im * b.im;
  return { re: (a.re * b.re + a.im * b.im) / d, im: (a.im * b.re - a.re * b.im) / d };
};
function evalPoly(coeffs, z) {
  // coeffs descending: c[0] z^n + c[1] z^{n-1} + ... + c[n]
  let r = cx(coeffs[0]);
  for (let i = 1; i < coeffs.length; i++) r = cadd(cmul(r, z), cx(coeffs[i]));
  return r;
}
function polyRoots(arCoeffs) {
  // roots of z^p - a1 z^{p-1} - ... - ap
  const p = arCoeffs.length;
  const c = [1];
  for (const a of arCoeffs) c.push(-a);
  // Durand–Kerner
  const n = p;
  let roots = [];
  for (let k = 0; k < n; k++) {
    const ang = (2 * Math.PI * k) / n + 0.4;
    roots.push(cx(Math.cos(ang), Math.sin(ang)));
  }
  for (let iter = 0; iter < 300; iter++) {
    let maxStep = 0;
    for (let i = 0; i < n; i++) {
      let num = evalPoly(c, roots[i]);
      let den = cx(1, 0);
      for (let j = 0; j < n; j++) if (j !== i) den = cmul(den, csub(roots[i], roots[j]));
      const d = cdiv(num, den);
      roots[i] = csub(roots[i], d);
      maxStep = Math.max(maxStep, Math.hypot(d.re, d.im));
    }
    if (maxStep < 1e-12) break;
  }
  return roots;
}

// =====================================================================
// CSV parsing
// =====================================================================
function parseLine(line) {
  const out = [];
  let cur = "", inQ = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    if (ch === '"') { inQ = !inQ; continue; }
    if ((ch === ',' || ch === '\t' || ch === ';') && !inQ) { out.push(cur); cur = ""; continue; }
    cur += ch;
  }
  out.push(cur);
  return out;
}
function parseCSV(text) {
  const lines = text.replace(/^\uFEFF/, "").trim().split(/\r?\n/).filter(l => l.trim());
  return lines.map(parseLine);
}
function analyzeColumns(rows) {
  if (!rows.length) return null;
  const first = rows[0];
  const isHeader = first.some(v => v !== "" && isNaN(parseFloat(v)));
  let header, dataRows;
  if (isHeader) { header = first; dataRows = rows.slice(1); }
  else {
    header = first.map((_, i) => `col${i + 1}`);
    dataRows = rows;
  }
  const numeric = [];
  for (let j = 0; j < header.length; j++) {
    let ok = 0, tot = 0;
    for (const r of dataRows) {
      const v = r[j];
      if (v === undefined || v === "") continue;
      tot++;
      if (isFinite(parseFloat(v))) ok++;
    }
    if (tot > 0 && ok / tot > 0.6) numeric.push(j);
  }
  return { header, dataRows, numeric };
}
function extractColumn(dataRows, col) {
  return dataRows.map(r => {
    const v = parseFloat(r[col]);
    return isFinite(v) ? v : NaN;
  });
}

// =====================================================================
// Model: AR(p) with intercept, OLS fit with tiny ridge
// =====================================================================
function fitAR(series, p) {
  const X = [], y = [];
  for (let t = p; t < series.length; t++) {
    if (!isFinite(series[t])) continue;
    const row = [1];
    let ok = true;
    for (let k = 1; k <= p; k++) {
      const v = series[t - k];
      if (!isFinite(v)) { ok = false; break; }
      row.push(v);
    }
    if (!ok) continue;
    X.push(row); y.push(series[t]);
  }
  if (X.length < p + 4) return null;

  const n = p + 1;
  const XtX = zeros(n, n), Xty = new Array(n).fill(0);
  for (let i = 0; i < X.length; i++) {
    for (let a = 0; a < n; a++) {
      for (let b = 0; b < n; b++) XtX[a][b] += X[i][a] * X[i][b];
      Xty[a] += X[i][a] * y[i];
    }
  }
  // Ridge on AR coefficients (not intercept)
  let trace = 0;
  for (let i = 0; i < n; i++) trace += XtX[i][i];
  for (let i = 1; i < n; i++) XtX[i][i] += 1e-8 * trace;

  const beta = solveLinear(XtX, Xty);
  if (!beta) return null;
  const intercept = beta[0];
  const coeffs = beta.slice(1);
  const roots = polyRoots(coeffs);
  return { intercept, coeffs, roots, nPoints: X.length };
}

function findLastValidWindow(series, p) {
  for (let t = series.length - 1; t >= p - 1; t--) {
    let ok = true;
    for (let k = 0; k < p; k++) if (!isFinite(series[t - k])) { ok = false; break; }
    if (ok) return t;
  }
  return -1;
}

function runForecast(series, model, h) {
  const p = model.coeffs.length;
  const startT = findLastValidWindow(series, p);
  if (startT < 0) return null;
  const s = [];
  for (let k = 0; k < p; k++) s.push(series[startT - k]);
  const out = [];
  const work = s.slice();
  for (let i = 0; i < h; i++) {
    let nx = model.intercept;
    for (let k = 0; k < p; k++) nx += model.coeffs[k] * work[k];
    out.push(nx);
    work.unshift(nx); work.pop();
  }
  return { forecast: out, startT, state: s };
}

// Attribution of x_{T+h} into (F^h s)_k contributions + bias
function attribution(model, stateVec, h) {
  const p = model.coeffs.length;
  const F = zeros(p, p);
  for (let j = 0; j < p; j++) F[0][j] = model.coeffs[j];
  for (let i = 1; i < p; i++) F[i][i - 1] = 1;
  const Fh = matpow(F, h);
  const contributions = [];
  for (let k = 0; k < p; k++) contributions.push(Fh[0][k] * stateVec[k]);
  // bias = c * sum_{j=0}^{h-1} (F^j)[0][0]
  let sum00 = 0;
  let Fj = eye(p);
  for (let j = 0; j < h; j++) {
    sum00 += Fj[0][0];
    Fj = matmul(Fj, F);
  }
  const bias = model.intercept * sum00;
  return { contributions, bias };
}

// Route multiplicity: p-bonacci at distance d
function routeCount(d, p) {
  if (d < 0) return 0;
  if (d === 0) return 1;
  const R = [1];
  for (let i = 1; i <= d; i++) {
    let s = 0;
    for (let k = 1; k <= Math.min(p, i); k++) s += R[i - k];
    R.push(s);
  }
  return R[d];
}
function totalRoutes(h, p) {
  let s = 0;
  for (let k = 0; k < p; k++) s += routeCount(h + k, p);
  return s;
}

// =====================================================================
// Demo series
// =====================================================================
function generateDemo(n = 220) {
  const x = [0, 0.4];
  for (let t = 2; t < n; t++) {
    x.push(0.75 * x[t - 1] - 0.25 * x[t - 2] + 0.25 * (Math.random() - 0.5));
  }
  // introduce some void gaps
  const gaps = [[28, 34], [72, 88], [130, 137], [180, 183]];
  for (const [a, b] of gaps) for (let i = a; i <= b; i++) x[i] = NaN;
  return x;
}

// =====================================================================
// Drawing — main time series
// =====================================================================
let viewScale = 1; // for potential future use

function drawMain() {
  const W = mainCanvas.width, H = mainCanvas.height;
  const ctx = mainCtx;
  ctx.clearRect(0, 0, W, H);
  ctx.fillStyle = "#080810";
  ctx.fillRect(0, 0, W, H);

  const series = state.series;
  if (!series || series.length === 0) return;
  const N = series.length;
  const fc = state.forecast ? state.forecast.forecast : [];
  const NF = fc.length;

  const pad = { l: 60, r: 24, t: 28, b: 36 };
  const plotW = W - pad.l - pad.r;
  const plotH = H - pad.t - pad.b;

  // y range
  let ymin = Infinity, ymax = -Infinity;
  for (const v of series) if (isFinite(v)) { if (v < ymin) ymin = v; if (v > ymax) ymax = v; }
  for (const v of fc) { if (v < ymin) ymin = v; if (v > ymax) ymax = v; }
  if (!isFinite(ymin)) { ymin = 0; ymax = 1; }
  if (ymax - ymin < 1e-9) { ymax = ymin + 1; }
  const yPad = (ymax - ymin) * 0.1;
  ymin -= yPad; ymax += yPad;

  const xmax = Math.max(N - 1, 1) + NF;
  const xToPx = t => pad.l + (t / xmax) * plotW;
  const yToPx = v => pad.t + (1 - (v - ymin) / (ymax - ymin)) * plotH;

  // grid
  ctx.strokeStyle = COL.grid;
  ctx.lineWidth = 1;
  ctx.font = "10px ui-monospace, monospace";
  ctx.fillStyle = "#666";
  ctx.textAlign = "right";
  ctx.textBaseline = "middle";
  const nY = 5;
  for (let i = 0; i <= nY; i++) {
    const y = pad.t + (i / nY) * plotH;
    ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(W - pad.r, y); ctx.stroke();
    const v = ymax - (i / nY) * (ymax - ymin);
    ctx.fillText(v.toFixed(2), pad.l - 6, y);
  }

  // gap bands
  let gapStart = -1;
  for (let i = 0; i <= N; i++) {
    const isGap = i < N && !isFinite(series[i]);
    if (isGap && gapStart < 0) gapStart = i;
    if (!isGap && gapStart >= 0) {
      const x0 = xToPx(gapStart - 0.5);
      const x1 = xToPx(i - 0.5);
      ctx.fillStyle = COL.gap;
      ctx.fillRect(x0, pad.t, x1 - x0, plotH);
      ctx.strokeStyle = "rgba(255, 85, 102, 0.35)";
      ctx.setLineDash([3, 3]);
      ctx.beginPath(); ctx.moveTo(x0, pad.t); ctx.lineTo(x0, pad.t + plotH); ctx.stroke();
      ctx.beginPath(); ctx.moveTo(x1, pad.t); ctx.lineTo(x1, pad.t + plotH); ctx.stroke();
      ctx.setLineDash([]);
      gapStart = -1;
    }
  }

  // forecast band
  if (NF > 0 && state.forecast) {
    const xStart = xToPx(state.forecast.startT + 0.5);
    const xEnd = xToPx(N - 0.5 + NF);
    ctx.fillStyle = "rgba(102, 204, 255, 0.05)";
    ctx.fillRect(xStart, pad.t, xEnd - xStart, plotH);
    ctx.strokeStyle = "rgba(102, 204, 255, 0.25)";
    ctx.setLineDash([3, 5]);
    ctx.beginPath();
    ctx.moveTo(xStart, pad.t);
    ctx.lineTo(xStart, pad.t + plotH);
    ctx.stroke();
    ctx.setLineDash([]);
  }

  // observed line (broken at gaps)
  ctx.strokeStyle = COL.obs;
  ctx.lineWidth = 1.6;
  ctx.beginPath();
  let pen = false;
  for (let i = 0; i < N; i++) {
    if (isFinite(series[i])) {
      const px = xToPx(i), py = yToPx(series[i]);
      if (!pen) { ctx.moveTo(px, py); pen = true; }
      else ctx.lineTo(px, py);
    } else pen = false;
  }
  ctx.stroke();

  // forecast dashed line, connected to last valid observed
  if (NF > 0 && state.forecast) {
    const T = state.forecast.startT;
    ctx.strokeStyle = COL.fc;
    ctx.setLineDash([5, 4]);
    ctx.lineWidth = 1.9;
    ctx.beginPath();
    ctx.moveTo(xToPx(T), yToPx(series[T]));
    for (let i = 0; i < NF; i++) {
      ctx.lineTo(xToPx(N + i), yToPx(fc[i]));
    }
    ctx.stroke();
    ctx.setLineDash([]);
    for (let i = 0; i < NF; i++) {
      ctx.fillStyle = COL.fc;
      ctx.beginPath();
      ctx.arc(xToPx(N + i), yToPx(fc[i]), 2.4, 0, Math.PI * 2);
      ctx.fill();
    }
  }

  // observed dots
  for (let i = 0; i < N; i++) {
    if (isFinite(series[i])) {
      ctx.fillStyle = COL.obs;
      ctx.beginPath();
      ctx.arc(xToPx(i), yToPx(series[i]), 2.1, 0, Math.PI * 2);
      ctx.fill();
    }
  }

  // hover overlay
  if (state.hoverIdx != null) {
    const t = state.hoverIdx;
    // vertical line
    ctx.strokeStyle = "rgba(255,255,255,0.18)";
    ctx.setLineDash([2, 4]);
    ctx.beginPath();
    ctx.moveTo(xToPx(t), pad.t);
    ctx.lineTo(xToPx(t), pad.t + plotH);
    ctx.stroke();
    ctx.setLineDash([]);

    // If hovering a forecast point, draw contribution arcs
    if (state.forecast && t >= N && t < N + NF && state.model) {
      const h = t - N + 1;
      const attr = attribution(state.model, state.forecast.state, h);
      const T = state.forecast.startT;
      const total = fc[h - 1];
      const denom = Math.max(Math.abs(total), 1e-9);

      for (let k = 0; k < attr.contributions.length; k++) {
        const srcT = T - k;
        if (srcT < 0 || !isFinite(series[srcT])) continue;
        const c = attr.contributions[k];
        const w = Math.abs(c) / denom;
        const alpha = Math.min(0.85, 0.15 + w * 1.2);
        const color = c >= 0
          ? `rgba(108, 220, 120, ${alpha})`
          : `rgba(255, 110, 130, ${alpha})`;
        ctx.strokeStyle = color;
        ctx.lineWidth = Math.max(1, Math.min(4.5, 0.5 + w * 5));
        const x0 = xToPx(srcT), y0 = yToPx(series[srcT]);
        const x1 = xToPx(t), y1 = yToPx(fc[h - 1]);
        const mx = (x0 + x1) / 2;
        const my = Math.min(y0, y1) - 30 - 8 * k;
        ctx.beginPath();
        ctx.moveTo(x0, y0);
        ctx.quadraticCurveTo(mx, my, x1, y1);
        ctx.stroke();
      }

      // ring around hovered forecast
      ctx.strokeStyle = "#6cf";
      ctx.lineWidth = 1.6;
      ctx.beginPath();
      ctx.arc(xToPx(t), yToPx(fc[h - 1]), 6, 0, Math.PI * 2);
      ctx.stroke();
    } else if (t < N && isFinite(series[t])) {
      ctx.strokeStyle = "#ffffff";
      ctx.lineWidth = 1.6;
      ctx.beginPath();
      ctx.arc(xToPx(t), yToPx(series[t]), 5, 0, Math.PI * 2);
      ctx.stroke();
    } else if (t < N) {
      // hovering a gap: mark void
      ctx.fillStyle = "#ff5566";
      ctx.font = "10px ui-monospace, monospace";
      ctx.textAlign = "center";
      ctx.textBaseline = "bottom";
      ctx.fillText("void", xToPx(t), pad.t + plotH - 4);
    }
  }

  // axis labels
  ctx.fillStyle = "#888";
  ctx.font = "11px ui-monospace, monospace";
  ctx.textAlign = "center";
  ctx.textBaseline = "top";
  ctx.fillText("t", pad.l + plotW / 2, H - 18);

  ctx.save();
  ctx.translate(14, pad.t + plotH / 2);
  ctx.rotate(-Math.PI / 2);
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillStyle = "#888";
  ctx.fillText("x_t", 0, 0);
  ctx.restore();
}

// =====================================================================
// Drawing — attribution bars
// =====================================================================
function drawAttribution() {
  const W = attrCanvas.width, H = attrCanvas.height;
  const ctx = attrCtx;
  ctx.clearRect(0, 0, W, H);
  ctx.fillStyle = "#0c0c16";
  ctx.fillRect(0, 0, W, H);

  const N = state.series.length;
  const t = state.hoverIdx;

  if (t == null || !state.forecast || t < N) {
    ctx.fillStyle = "#555";
    ctx.font = "13px ui-monospace, monospace";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText("Hover a forecast point", W / 2, H / 2 - 8);
    ctx.fillStyle = "#333";
    ctx.font = "11px ui-monospace, monospace";
    ctx.fillText("(dashed cyan region)", W / 2, H / 2 + 12);
    return;
  }

  const h = t - N + 1;
  const NF = state.forecast.forecast.length;
  if (h < 1 || h > NF) return;

  const attr = attribution(state.model, state.forecast.state, h);
  const total = state.forecast.forecast[h - 1];
  const T = state.forecast.startT;

  const items = [];
  for (let k = 0; k < attr.contributions.length; k++) {
    items.push({
      label: `a${k + 1}·x[${T - k}]`,
      value: attr.contributions[k],
      color: attr.contributions[k] >= 0 ? COL.pos : COL.neg,
    });
  }
  if (Math.abs(attr.bias) > 1e-12 || true) {
    items.push({
      label: "intercept",
      value: attr.bias,
      color: attr.bias >= 0 ? COL.pos : COL.neg,
    });
  }

  const pad = { l: 110, r: 56, t: 44, b: 22 };
  const plotW = W - pad.l - pad.r;
  const plotH = H - pad.t - pad.b;

  // scale
  let maxAbs = Math.abs(total);
  for (const it of items) maxAbs = Math.max(maxAbs, Math.abs(it.value));
  if (maxAbs < 1e-9) maxAbs = 1;
  const spanW = plotW / 2;
  const xZero = pad.l + plotW / 2;
  const xOf = v => xZero + (v / maxAbs) * spanW;

  // header label
  ctx.fillStyle = "#888";
  ctx.font = "11px ui-monospace, monospace";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText(`forecast step h = ${h}   (t = ${t})`, pad.l, 12);
  ctx.textAlign = "right";
  ctx.fillStyle = COL.fc;
  ctx.font = "bold 13px ui-monospace, monospace";
  ctx.fillText(`x̂ = ${total.toFixed(4)}`, W - pad.r, 10);

  // zero axis
  ctx.strokeStyle = "#333";
  ctx.beginPath(); ctx.moveTo(xZero, pad.t); ctx.lineTo(xZero, pad.t + plotH); ctx.stroke();

  // grid lines
  ctx.strokeStyle = "#181822";
  for (let i = 1; i <= 2; i++) {
    const xp = xZero + (i / 2) * spanW;
    const xn = xZero - (i / 2) * spanW;
    ctx.beginPath(); ctx.moveTo(xp, pad.t); ctx.lineTo(xp, pad.t + plotH); ctx.stroke();
    ctx.beginPath(); ctx.moveTo(xn, pad.t); ctx.lineTo(xn, pad.t + plotH); ctx.stroke();
  }

  // bars
  const rowH = Math.min(30, (plotH - 12) / items.length);
  const gap = 4;
  ctx.font = "11px ui-monospace, monospace";
  for (let i = 0; i < items.length; i++) {
    const it = items[i];
    const y = pad.t + i * (rowH + gap);
    // label
    ctx.fillStyle = "#aaa";
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    ctx.fillText(it.label, pad.l - 8, y + rowH / 2);
    // bar
    const x0 = xZero;
    const x1 = xOf(it.value);
    ctx.fillStyle = it.color;
    ctx.fillRect(Math.min(x0, x1), y + 3, Math.abs(x1 - x0) || 1, rowH - 6);
    // value
    ctx.fillStyle = "#ddd";
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    const labelX = it.value >= 0 ? x1 + 6 : x1 - 6;
    ctx.textAlign = it.value >= 0 ? "left" : "right";
    ctx.fillText(it.value.toFixed(3), labelX, y + rowH / 2);
  }

  // total indicator bar (below)
  const yTotal = pad.t + items.length * (rowH + gap) + 6;
  if (yTotal < H - 6) {
    ctx.strokeStyle = COL.fc;
    ctx.lineWidth = 1.4;
    ctx.beginPath();
    ctx.moveTo(xZero, yTotal);
    ctx.lineTo(xOf(total), yTotal);
    ctx.stroke();
    ctx.fillStyle = COL.fc;
    ctx.beginPath();
    ctx.arc(xOf(total), yTotal, 3.5, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "#666";
    ctx.font = "10px ui-monospace, monospace";
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    ctx.fillText("total", xZero + 6, yTotal);
  }
}

// =====================================================================
// Drawing — spectrum
// =====================================================================
function drawSpectrum() {
  const W = specCanvas.width, H = specCanvas.height;
  const ctx = specCtx;
  ctx.clearRect(0, 0, W, H);
  ctx.fillStyle = "#0c0c16";
  ctx.fillRect(0, 0, W, H);

  if (!state.model) {
    ctx.fillStyle = "#555";
    ctx.font = "13px ui-monospace, monospace";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText("no model", W / 2, H / 2);
    return;
  }

  const roots = state.model.roots;
  let maxR = 1.5;
  for (const r of roots) maxR = Math.max(maxR, Math.hypot(r.re, r.im) * 1.2);

  const cx0 = W / 2;
  const cy0 = H / 2;
  const scale = Math.min(W, H) / (2.4 * maxR);

  // unit circle
  ctx.strokeStyle = "rgba(102, 204, 255, 0.35)";
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.arc(cx0, cy0, scale, 0, Math.PI * 2);
  ctx.stroke();

  // axes
  ctx.strokeStyle = "#1a1a2a";
  ctx.beginPath();
  ctx.moveTo(cx0 - W / 2, cy0); ctx.lineTo(cx0 + W / 2, cy0);
  ctx.moveTo(cx0, cy0 - H / 2); ctx.lineTo(cx0, cy0 + H / 2);
  ctx.stroke();

  // roots
  for (const r of roots) {
    const px = cx0 + r.re * scale;
    const py = cy0 - r.im * scale;
    const mag = Math.hypot(r.re, r.im);
    let color, glow;
    if (mag > 1.005) { color = "#ff5566"; glow = "rgba(255,85,102,0.35)"; }
    else if (mag > 0.995) { color = "#ffcc44"; glow = "rgba(255,204,68,0.35)"; }
    else { color = "#6cf"; glow = "rgba(102,204,255,0.35)"; }
    // glow
    ctx.fillStyle = glow;
    ctx.beginPath(); ctx.arc(px, py, 11, 0, Math.PI * 2); ctx.fill();
    // dot
    ctx.fillStyle = color;
    ctx.beginPath(); ctx.arc(px, py, 5, 0, Math.PI * 2); ctx.fill();
    ctx.strokeStyle = "#fff";
    ctx.lineWidth = 0.8;
    ctx.stroke();
  }

  // text
  ctx.font = "10.5px ui-monospace, monospace";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillStyle = "#888";
  ctx.fillText(`roots of z^${roots.length} − Σ aₖ z^${roots.length}⁻ᵏ = 0`, 8, 8);

  // legend
  ctx.textBaseline = "bottom";
  ctx.fillStyle = "#6cf";
  ctx.fillText("● |λ| < 1   damped — arrow of time", 8, H - 26);
  ctx.fillStyle = "#ffcc44";
  ctx.fillText("● |λ| = 1   inertia — void", 8, H - 12);

  // spectral summary
  const inUnit = roots.filter(r => Math.hypot(r.re, r.im) < 0.995).length;
  const onUnit = roots.filter(r => Math.abs(Math.hypot(r.re, r.im) - 1) <= 0.005).length;
  const outUnit = roots.length - inUnit - onUnit;

  ctx.fillStyle = "#888";
  ctx.textAlign = "right";
  ctx.textBaseline = "top";
  ctx.fillText(`in ${inUnit} · on ${onUnit} · out ${outUnit}`, W - 8, 8);
}

// =====================================================================
// Explanation panel
// =====================================================================
function fmt(x, d = 4) {
  if (!isFinite(x)) return "—";
  if (Math.abs(x) < 1e-9) return "0";
  if (Math.abs(x) >= 1e6 || (Math.abs(x) < 1e-4 && x !== 0)) return x.toExponential(2);
  return x.toFixed(d);
}
function fmtC(z) {
  const re = fmt(z.re);
  const im = fmt(Math.abs(z.im));
  const sign = z.im >= 0 ? "+" : "−";
  return `${re} ${sign} ${im}i`;
}

function updateExplanation() {
  if (!state.model) {
    explanationEl.innerHTML = '<p style="color:var(--dim)">Load a CSV or use the demo to begin.</p>';
    return;
  }
  const N = state.series.length;
  const t = state.hoverIdx;
  const p = state.model.coeffs.length;
  let html = "";

  if (t == null) {
    html += `<h3>Model: AR(${p})</h3>`;
    html += `<p>Fit on <b>${state.model.nPoints}</b> valid lag-windows.</p>`;
    html += `<p>`;
    html += `c = ${fmt(state.model.intercept)}<br>`;
    for (let k = 0; k < p; k++) html += `a<sub>${k + 1}</sub> = ${fmt(state.model.coeffs[k])}<br>`;
    html += `</p>`;
    const r = state.model.roots;
    html += `<p style="color:var(--dim)">`;
    html += `Spectrum: ` + r.map(z => `|λ| = ${Math.hypot(z.re, z.im).toFixed(3)}`).join(", ");
    html += `</p>`;
    html += `<div class="note">Hover over the plot. If you hover a <b>forecast</b> point, this panel shows how the leap <code>F<sup>h</sup> s<sub>t</sub></code> decomposes into contributions from each clamped past value — the route sum is the answer, the routes themselves are the opaque residue.</div>`;
  } else if (t < N) {
    const v = state.series[t];
    if (!isFinite(v)) {
      html += `<h3>t = ${t} — void</h3>`;
      html += `<div class="verdict bad">VOID — no observation here</div>`;
      html += `<p>This time is a <b>free boundary</b>. Under ⊗-resolution the void acts as identity transport: the state coasts through without damping or driving. No force is applied.</p>`;
      html += `<div class="note">A zero fill here would be an <em>absorbing wall</em>, not a gap. The void is the unique imputation whose contamination spectrum sits on the unit circle.</div>`;
    } else {
      html += `<h3>t = ${t} — observed</h3>`;
      html += `<div class="verdict good">x<sub>t</sub> = ${fmt(v)}</div>`;
      html += `<p>This point is a <b>clamp row</b> in the spacetime system: it pins the particle exactly here. Every clamp is a Dirichlet boundary condition.</p>`;
    }
  } else {
    const h = t - N + 1;
    const fc = state.forecast.forecast[h - 1];
    const attr = attribution(state.model, state.forecast.state, h);
    const T = state.forecast.startT;

    html += `<h3>Forecast at t = ${t} (step h = ${h})</h3>`;
    html += `<div class="verdict good">x̂<sub>${t}</sub> = <b>${fmt(fc)}</b></div>`;

    html += `<p>Decomposition via <code>F<sup>${h}</sup> · s<sub>${T}</sub></code>:</p>`;
    html += `<table>`;
    html += `<tr><th>source</th><th>x</th><th>weight</th><th>contribution</th></tr>`;
    let sumCheck = 0;
    for (let k = 0; k < attr.contributions.length; k++) {
      const srcT = T - k;
      const x = state.series[srcT];
      const c = attr.contributions[k];
      sumCheck += c;
      const w = x !== 0 ? c / x : NaN;
      html += `<tr><td>x[${srcT}]</td><td>${fmt(x, 3)}</td><td>${fmt(w, 4)}</td><td>${fmt(c, 4)}</td></tr>`;
    }
    html += `<tr><td>intercept</td><td>—</td><td>—</td><td>${fmt(attr.bias, 4)}</td></tr>`;
    html += `<tr style="border-top:2px solid #2a2a3a"><td>Σ</td><td></td><td></td><td><b>${fmt(sumCheck + attr.bias)}</b></td></tr>`;
    html += `</table>`;

    const routes = totalRoutes(h, p);
    html += `<p style="color:var(--dim)">Causal route multiplicity: <b>${routes}</b> distinct lag-paths connect the past window to this forecast. The leap <code>F<sup>h</sup></code> sums them all; the individual routes are not recoverable from the sum — this is the <em>opaque residue 𝒪</em>.</p>`;

    // arrow-of-time note based on spectrum
    const roots = state.model.roots;
    const anyDamped = roots.some(r => Math.hypot(r.re, r.im) < 0.995);
    const anyVoid = roots.some(r => Math.abs(Math.hypot(r.re, r.im) - 1) < 0.005);
    if (anyDamped && !anyVoid) {
      html += `<div class="note"><b>Arrow of time present.</b> The spectrum has damped roots, so retrodiction amplifies noise as <code>|λ|<sup>−h</sup></code>. Information is destroyed going forward; the particle relaxes toward the fixed point.</div>`;
    } else if (anyVoid && !anyDamped) {
      html += `<div class="note"><b>Pure inertia.</b> All roots sit on the unit circle. The forecast is a bounded oscillation — modulus is conserved, only phase drifts. Retrodiction is exact in principle.</div>`;
    } else if (anyDamped && anyVoid) {
      html += `<div class="note"><b>Mixed spectrum.</b> Some directions damp (arrow of time) and some coast (void). Forward predictability is high; backward predictability splits by direction.</div>`;
    }
  }

  explanationEl.innerHTML = html;
}

// =====================================================================
// Main interaction
// =====================================================================
function redraw() {
  drawMain();
  drawAttribution();
  drawSpectrum();
  updateExplanation();
}

function rebuildModel() {
  if (!state.series || !state.series.length) return;
  const p = state.p;
  const model = fitAR(state.series, p);
  state.model = model;
  if (model) {
    state.forecast = runForecast(state.series, model, state.horizon);
  } else {
    state.forecast = null;
  }
  redraw();
}

mainCanvas.addEventListener("mousemove", e => {
  if (!state.series || !state.series.length) return;
  const rect = mainCanvas.getBoundingClientRect();
  const px = (e.clientX - rect.left) / rect.width * mainCanvas.width;
  const W = mainCanvas.width;
  const pad = { l: 60, r: 24, t: 28, b: 36 };
  const plotW = W - pad.l - pad.r;
  const N = state.series.length;
  const NF = state.forecast ? state.forecast.forecast.length : 0;
  const xmax = Math.max(N - 1, 1) + NF;
  // inverse of xToPx
  const tFrac = (px - pad.l) / plotW;
  let t = Math.round(tFrac * xmax);
  t = Math.max(0, Math.min(N - 1 + NF, t));
  if (t !== state.hoverIdx) {
    state.hoverIdx = t;
    redraw();
  }
});

mainCanvas.addEventListener("mouseleave", () => {
  state.hoverIdx = null;
  redraw();
});

// =====================================================================
// Controls
// =====================================================================
const fileInput = document.getElementById("fileInput");
const colSelect = document.getElementById("colSelect");
const pSlider = document.getElementById("pSlider");
const hSlider = document.getElementById("hSlider");
const pVal = document.getElementById("pVal");
const hVal = document.getElementById("hVal");

function loadCSVText(text) {
  const rows = parseCSV(text);
  if (!rows || rows.length < 3) {
    alert("CSV too short or empty.");
    return;
  }
  const info = analyzeColumns(rows);
  if (!info || info.numeric.length === 0) {
    alert("No numeric column detected.");
    return;
  }
  state.header = info.header;
  state.dataRows = info.dataRows;
  state.numericCols = info.numeric;

  colSelect.innerHTML = "";
  for (const j of info.numeric) {
    const opt = document.createElement("option");
    opt.value = j;
    opt.textContent = info.header[j] || `col${j + 1}`;
    colSelect.appendChild(opt);
  }
  state.selectedCol = info.numeric[info.numeric.length - 1];
  colSelect.value = state.selectedCol;

  applyColumn();
}

function applyColumn() {
  const col = parseInt(colSelect.value, 10);
  state.selectedCol = col;
  state.series = extractColumn(state.dataRows, col);
  // cap length for perf
  const MAX = 4000;
  if (state.series.length > MAX) {
    const step = Math.ceil(state.series.length / MAX);
    state.series = state.series.filter((_, i) => i % step === 0);
  }
  state.hoverIdx = null;
  rebuildModel();
}

fileInput.addEventListener("change", e => {
  const f = e.target.files[0];
  if (!f) return;
  const reader = new FileReader();
  reader.onload = ev => loadCSVText(ev.target.result);
  reader.readAsText(f);
});

colSelect.addEventListener("change", applyColumn);

pSlider.addEventListener("input", () => {
  state.p = parseInt(pSlider.value, 10);
  pVal.textContent = state.p;
  rebuildModel();
});

hSlider.addEventListener("input", () => {
  state.horizon = parseInt(hSlider.value, 10);
  hVal.textContent = state.horizon;
  rebuildModel();
});

// Drag & drop
["dragenter", "dragover"].forEach(ev =>
  window.addEventListener(ev, e => { e.preventDefault(); })
);
window.addEventListener("drop", e => {
  e.preventDefault();
  const f = e.dataTransfer.files[0];
  if (!f) return;
  const reader = new FileReader();
  reader.onload = ev => loadCSVText(ev.target.result);
  reader.readAsText(f);
});

// =====================================================================
// Boot
// =====================================================================
function bootWithDemo() {
  state.series = generateDemo(220);
  state.header = ["t", "demo"];
  state.numericCols = [1];
  colSelect.innerHTML = '<option value="1">demo AR(2)</option>';
  state.selectedCol = 1;
  state.p = 2;
  state.horizon = 25;
  pSlider.value = 2; pVal.textContent = "2";
  hSlider.value = 25; hVal.textContent = "25";
  rebuildModel();
}

bootWithDemo();
</script>
</body>
</html>