Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
4211 lines (3742 loc) · 183 KB
/
Copy pathapp.js
File metadata and controls
4211 lines (3742 loc) · 183 KB
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
/**
* NFL Receiving Props Agent — Client Application & Research Terminal
* Core Promise: "Find the opportunity. Verify the price. Understand the risk."
* Positioning: "See what changed in a player's role—and whether the price reflects it."
*/
// --------------------------------------------------------------------------
// Global State & Calibrated Model Constants
// --------------------------------------------------------------------------
const MODEL_ALPHA = 0.1097; // Calibrated NB dispersion (Var = mu + alpha*mu^2)
const MODEL_K = 1.555; // Calibrated Gamma shape per reception (k = 1.555)
// Empirical out-of-sample calibration error hurdles
const W1_BIAS_REC = 0.057; // Week 1 empirical bias
const W1_BIAS_YDS = 0.088; // Week 1 empirical bias
const W1_MIN_EDGE = 0.10; // 10% edge hurdle for Week 1
const W1_KELLY_CAP = 0.005; // 0.5% max bankroll cap
const STD_MIN_EDGE = 0.10; // 10% edge hurdle for regular weeks
const STD_KELLY_CAP = 0.02; // 2% max bankroll cap
const QUOTE_MAX_AGE_MS = 10 * 60 * 1000; // Live prices older than 10 minutes fail closed
const QUOTE_CLOCK_SKEW_MS = 60 * 1000;
let currentSlateKey = '2026_w7'; // '2026_w7' (Upcoming) or '2026_w1' (Historical)
let currentSeason = 2026;
let currentWeek = 7;
let isHistoricalSlate = false;
let slateData = [];
let topPicksData = [];
let gamesData = [];
let clvLogData = [];
let currentSnapshots = [];
let holdoutEvalData = null;
let selectedGameId = null; // Filter by game_id from Game Strip
let currentLeague = 'nfl';
// User Filters & View Modes
let currentFilterPos = 'ALL';
let currentFilterMarket = 'yards'; // 'yards', 'receptions'
let currentFilterBook = 'Consensus';
let currentFilterTeam = 'ALL';
let currentSearchQuery = '';
let currentQualifiedOnly = false;
let currentProjectableOnly = true;
let currentViewMode = 'verified_quotes'; // 'baseline', 'surges', 'injury_surges', 'verified_quotes', 'demo_quotes'
let currentInjuriesData = null;
let currentLiveOddsData = null;
let currentFeedFormat = 'quant'; // 'quant' (Table) or 'action' (Feed)
let currentXCardPlayerId = null;
let sortCol = 'proj_yards';
let sortAsc = false;
// Persistent User Adjustments & Saved Conditions (saved in localStorage)
let inlinePlayerLines = {};
let userSavedConditions = [];
let selectedDrawerPlayer = null;
let clvFilterType = 'all'; // 'all', 'verified', 'demo'
let activeDrawerConditionalScenario = 'BASELINE'; // 'BASELINE', 'TEAMMATE_OUT', 'LIMITED_WORKLOAD', 'TRAILING_SCRIPT'
let currentQuickFilter = 'all'; // 'all', 'qualified', 'tnf', 'injuries', 'surges'
let drawerLabTargetShift = 0; // -15 to +20 %
let drawerLabInjuryShift = 0; // 0 to +30 %
let drawerLabMatchupShift = 0; // -20 to +20 %
let deferredPwaPrompt = null;
const evaluationCache = new Map();
function getTeamLogoUrl(team) {
if (!team) return '';
const clean = String(team).trim().toUpperCase();
const map = {
'LA': 'lar',
'LAR': 'lar',
'LAC': 'lac',
'WSH': 'was',
'WAS': 'was',
'OAK': 'lv',
'SD': 'lac'
};
const slug = map[clean] || clean.toLowerCase();
return `https://a.espncdn.com/i/teamlogos/nfl/500/${slug}.png`;
}
// --------------------------------------------------------------------------
// Theme Management (Light / Dark Mode)
// --------------------------------------------------------------------------
function initTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
updateThemeToggleUI(currentTheme);
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
setTheme(newTheme);
}
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
try {
localStorage.setItem('propwire_theme', theme);
} catch (_) {}
updateThemeToggleUI(theme);
if (selectedDrawerPlayer) {
renderDrawerBodyContent();
}
}
function updateThemeToggleUI(theme) {
const label = document.getElementById('themeToggleText');
const btn = document.getElementById('themeToggleBtn');
if (label) {
label.textContent = theme === 'dark' ? 'Light' : 'Dark';
}
if (btn) {
btn.setAttribute('title', `Switch to ${theme === 'dark' ? 'Light' : 'Dark'} Mode`);
}
}
document.addEventListener('DOMContentLoaded', async () => {
initTheme();
try {
setLeague(localStorage.getItem('propwire_league') === 'nba' ? 'nba' : 'nfl', false);
} catch (_) {
setLeague('nfl', false);
}
loadStoredConditions();
loadStoredLines();
initPwaServiceWorker();
initPwaInstallPrompt();
// Keyboard shortcut: Escape to close drawer/modal
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeDrawer();
closeAdminModal();
closeXCardModal();
}
});
await initSlate(currentSlateKey);
await loadClvLedger();
});
async function initSlate(slateKey) {
currentSlateKey = slateKey;
if (slateKey === '2026_w1') {
currentWeek = 1;
isHistoricalSlate = true;
} else {
currentWeek = 7;
isHistoricalSlate = false;
}
updateSlateHeaderContext();
try {
// 1. Load games schedule
const gamesPath = isHistoricalSlate ? 'games_2026_w1.json' : 'games_2026_w7.json';
const gamesRes = await fetchWithFallback(`/api/games?slate=${slateKey}`, gamesPath);
if (gamesRes.ok) {
gamesData = await gamesRes.json();
} else {
gamesData = [];
}
// 2. Load slate projections
const slatePath = isHistoricalSlate ? 'slate_2026_w1.json' : 'slate_2026_w7.json';
const slateRes = await fetchWithFallback(`/api/slate?slate=${slateKey}`, slatePath);
if (slateRes.ok) {
slateData = await slateRes.json();
}
// 3. Load top volume picks
const picksPath = isHistoricalSlate ? 'current_picks_w1.json' : 'current_picks_w7.json';
const picksRes = await fetchWithFallback(`/api/picks?slate=${slateKey}`, picksPath);
if (picksRes.ok) {
const picksPayload = await picksRes.json();
topPicksData = picksPayload.top_projections || picksPayload.picks || [];
}
// 4. Load content-hashed snapshots
const snapPath = isHistoricalSlate ? 'snapshots_2026_w1.json' : 'snapshots_2026_w7.json';
const snapRes = await fetchWithFallback(`/api/snapshots?slate=${slateKey}`, snapPath);
if (snapRes.ok) {
currentSnapshots = await snapRes.json();
} else {
currentSnapshots = [];
}
// 5. Load chronological holdout evaluation report if available
try {
const evalRes = await fetchWithFallback(`/api/holdout-eval?season=${currentSeason}&week=${isHistoricalSlate ? 1 : currentWeek}`, 'holdout_eval_2026_w1.json');
if (evalRes.ok) {
holdoutEvalData = await evalRes.json();
} else {
holdoutEvalData = null;
}
} catch (_) {
holdoutEvalData = null;
}
// 6. Load live injury and target redistribution feed
try {
const injPath = isHistoricalSlate ? 'injuries_2026_w1.json' : 'injuries_2026_w7.json';
const injRes = await fetchWithFallback(`/api/injuries?season=${currentSeason}&week=${isHistoricalSlate ? 1 : currentWeek}`, injPath);
if (injRes.ok) {
currentInjuriesData = await injRes.json();
} else {
currentInjuriesData = null;
}
} catch (_) {
currentInjuriesData = null;
}
// 7. Load live verified odds feed
try {
const oddsRes = await fetchWithFallback('/api/live-odds', 'live_odds_feed.json');
if (oddsRes.ok) {
currentLiveOddsData = await oddsRes.json();
} else {
currentLiveOddsData = null;
}
} catch (_) {
currentLiveOddsData = null;
}
populateTeamDropdown();
populateAdminGameSelect();
renderInjuryRadar();
renderGameStrip();
renderSlateHealthStrip();
renderSnapshotStatus();
renderOpportunitySummary();
renderBestOpportunitiesGrid();
renderBoard();
populateSgpSelect();
updateConditionBadge();
} catch (err) {
console.error('Error loading slate data:', err);
showToast('Failed to load slate data.');
}
}
async function fetchWithFallback(apiPath, staticFallback) {
try {
const res = await fetch(apiPath);
if (res.ok) return res;
} catch (_) {}
return fetch(staticFallback);
}
function updateSlateHeaderContext() {
const badge = document.getElementById('dataStatusBadge');
const badgeText = document.getElementById('dataStatusText');
const noticeText = document.getElementById('slateNoticeText');
const noticeBtn = document.getElementById('slateNoticeActionBtn');
const navTitle = document.getElementById('navTitle');
const selector = document.getElementById('slateSelector');
if (selector) selector.value = currentSlateKey;
if (isHistoricalSlate) {
if (navTitle) navTitle.textContent = '2026 Week 1 Historical Audit & Calibration Review';
if (badge) badge.className = 'data-status-badge badge-prelim';
if (badgeText) badgeText.textContent = 'HISTORICAL AUDIT • SETTLED';
if (noticeText) noticeText.innerHTML = 'Showing <strong>2026 Week 1 Historical Audit</strong> (16 Matchups • Sept 10–14). Settled games evaluated against out-of-sample calibration error hurdles.';
if (noticeBtn) {
noticeBtn.textContent = 'Switch to Upcoming Slate (Week 7)';
noticeBtn.onclick = () => onSlateSelectChange('2026_w7');
}
} else {
if (navTitle) navTitle.textContent = 'See what changed in a player’s role—and whether the price reflects it.';
if (badge) badge.className = 'data-status-badge status-live';
if (badgeText) badgeText.textContent = 'LIVE • CALIBRATED BASELINE';
if (noticeText) noticeText.innerHTML = 'Showing <strong>2026 Week 7 Upcoming Slate</strong> (14 Matchups • Oct 22–26). Pre-line phase: Displaying calibrated fair-line baselines.';
if (noticeBtn) {
noticeBtn.textContent = 'Switch to Historical Audit (Week 1)';
noticeBtn.onclick = () => onSlateSelectChange('2026_w1');
}
}
}
function onSlateSelectChange(val) {
selectedGameId = null;
initSlate(val);
}
function toggleSlateContext() {
const next = isHistoricalSlate ? '2026_w7' : '2026_w1';
onSlateSelectChange(next);
}
// --------------------------------------------------------------------------
// Navigation (4 Primary Destinations)
// --------------------------------------------------------------------------
function setLeague(league, shouldScroll = true) {
currentLeague = league === 'nba' ? 'nba' : 'nfl';
const isNba = currentLeague === 'nba';
const nflButton = document.getElementById('leagueNflBtn');
const nbaButton = document.getElementById('leagueNbaBtn');
document.body.classList.toggle('nba-mode', isNba);
if (nflButton) {
nflButton.classList.toggle('active', !isNba);
nflButton.setAttribute('aria-pressed', String(!isNba));
}
if (nbaButton) {
nbaButton.classList.toggle('active', isNba);
nbaButton.setAttribute('aria-pressed', String(isNba));
}
if (isNba) {
closeDrawer();
closeAdminModal();
} else {
setDestination('board');
}
try {
localStorage.setItem('propwire_league', currentLeague);
} catch (_) {}
if (shouldScroll) window.scrollTo({ top: 0, behavior: 'smooth' });
}
function setDestination(dest) {
const tabs = ['board', 'watchlist', 'tracker', 'research'];
tabs.forEach(t => {
const btn = document.getElementById(`tab${capitalize(t)}`);
const page = document.getElementById(`${t}Destination`);
if (btn) btn.classList.toggle('active', t === dest);
if (page) page.classList.toggle('active', t === dest);
});
if (dest === 'watchlist') renderWatchlistPage();
if (dest === 'tracker') renderTrackerPage();
if (dest === 'board') {
renderBestOpportunitiesGrid();
renderBoard();
}
}
function capitalize(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
// --------------------------------------------------------------------------
// What Changed: Injury & Role Shift Radar
// --------------------------------------------------------------------------
function renderInjuryRadar() {
const container = document.getElementById('injuryRadarGrid');
const section = document.getElementById('injuryRadarSection');
const tsLabel = document.getElementById('injuryRadarTimestamp');
if (!container || !section) return;
if (isHistoricalSlate) {
section.style.display = 'none';
return;
}
section.style.display = 'block';
if (!currentInjuriesData || !currentInjuriesData.injuries || currentInjuriesData.injuries.length === 0) {
container.innerHTML = '<div style="color:var(--text-ink-tertiary); font-size:12px; padding:12px;">Loading live injury and practice reports...</div>';
return;
}
if (tsLabel && currentInjuriesData.as_of) {
tsLabel.textContent = `Feed timestamp: ${new Date(currentInjuriesData.as_of).toLocaleString()}`;
}
const escapeHtml = value => String(value ?? '').replace(/[&<>"']/g, char => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[char]));
const active = currentInjuriesData.injuries.filter(item => item.game_id !== 'BYE_WEEK_7').slice(0, 6);
container.innerHTML = active.map(item => {
const hasEvidence = typeof item.source_url === 'string' && /^https:\/\//i.test(item.source_url);
const affected = Object.values(currentInjuriesData.impacted_beneficiaries || {})
.filter(ben => ben.injury_id === item.injury_id && getValidatedBeneficiary(slateData.find(p => p.player_id === ben.player_id)));
return `
<div class="radar-card">
<div class="radar-card-top">
<div>
<div class="radar-player-name">${escapeHtml(item.player_name)}</div>
<div class="radar-matchup">${escapeHtml(item.team)} vs ${escapeHtml(item.opponent)} • ${escapeHtml(item.position)}</div>
</div>
<span class="${hasEvidence ? 'radar-pill-out' : 'radar-pill-limited'}">${hasEvidence ? escapeHtml(item.report_status) : 'UNVERIFIED SOURCE'}</span>
</div>
<div class="radar-impact-box">
<div class="radar-impact-row"><span>Reported status:</span><strong>${escapeHtml(item.report_status)} (${escapeHtml(item.injury_type)})</strong></div>
<div class="radar-impact-row"><span>Feed attribution:</span><strong>${escapeHtml(item.source || 'Not supplied')}</strong></div>
<div class="radar-impact-row"><span>Validated beneficiaries:</span><strong>${affected.length}</strong></div>
</div>
<div class="radar-invalidation-text">
<strong>${hasEvidence ? 'Evidence attached:' : 'Model adjustment disabled:'}</strong>
${hasEvidence ? 'Source URL is available for audit.' : 'No source URL or provider receipt was supplied with this record.'}
</div>
</div>`;
}).join('');
}
// --------------------------------------------------------------------------
// Slate Health Strip (4 Distinct Metric Tiles)
// --------------------------------------------------------------------------
function renderSlateHealthStrip() {
const gamesCount = document.getElementById('healthGamesCount');
const gamesPill = document.getElementById('healthGamesPill');
const teamsCount = document.getElementById('healthTeamsCount');
const teamsPill = document.getElementById('healthTeamsPill');
const playersCount = document.getElementById('healthPlayersCount');
const playersPill = document.getElementById('healthPlayersPill');
const marketsCount = document.getElementById('healthMarketsCount');
const marketsPill = document.getElementById('healthMarketsPill');
const marketsSub = document.getElementById('healthMarketsSub');
const totalGames = gamesData.length || (isHistoricalSlate ? 16 : 14);
const totalTeams = isHistoricalSlate ? 32 : 28;
const totalReceivers = slateData.length;
if (gamesCount) gamesCount.textContent = totalGames;
if (gamesPill) gamesPill.textContent = `${totalGames} / ${totalGames}`;
if (teamsCount) teamsCount.textContent = totalTeams;
if (teamsPill) teamsPill.textContent = `${totalTeams} / ${totalTeams}`;
if (playersCount) playersCount.textContent = totalReceivers;
if (playersPill) playersPill.textContent = `${totalReceivers} Calibrated`;
// Only quotes with auditable provider evidence count as verified.
const ingestedCount = (currentLiveOddsData && currentLiveOddsData.quotes) ? currentLiveOddsData.quotes.length : 0;
const verifiedQuotes = (currentLiveOddsData && currentLiveOddsData.quotes ? currentLiveOddsData.quotes : []).filter(quote => {
const player = slateData.find(p => p.player_id === quote.player_id);
return getQuoteValidation(quote, player, quote.market).isValid;
});
const verifiedCount = verifiedQuotes.length;
const verifiedBooks = [...new Set(verifiedQuotes.map(quote => quote.book))];
if (currentViewMode === 'demo_quotes') {
if (marketsCount) marketsCount.textContent = '14';
if (marketsPill) {
marketsPill.textContent = 'Simulated Scenarios';
marketsPill.className = 'health-tile-pill pill-pending';
}
if (marketsSub) marketsSub.textContent = 'Hypothetical lines active • Unverified.';
} else if (currentViewMode === 'baseline') {
if (marketsCount) marketsCount.textContent = '0';
if (marketsPill) {
marketsPill.textContent = '0 Verified Feeds';
marketsPill.className = 'health-tile-pill pill-unquoted';
}
if (marketsSub) marketsSub.textContent = 'Feeds unquoted • Displaying calibrated baselines.';
} else if (verifiedCount > 0) {
if (marketsCount) marketsCount.textContent = verifiedCount;
if (marketsPill) {
marketsPill.textContent = `${currentLiveOddsData.verified_books_count || verifiedBooks.length} Verified Books ✓`;
marketsPill.className = 'health-tile-pill pill-complete';
}
if (marketsSub) {
marketsSub.innerHTML = `<strong>Verified Feed Active:</strong> ${verifiedBooks.join(' • ')}`;
}
} else {
if (marketsCount) marketsCount.textContent = '0';
if (marketsPill) {
marketsPill.textContent = `0 Verified / ${ingestedCount} Ingested`;
marketsPill.className = 'health-tile-pill pill-unquoted';
}
if (marketsSub) marketsSub.textContent = ingestedCount > 0
? 'Provider receipt missing • qualification and stake disabled'
: 'Feeds unquoted • pipeline listening';
}
renderSnapshotStatus();
}
function renderSnapshotStatus() {
const badge = document.getElementById('headerSnapshotBadge');
const badgeText = document.getElementById('headerSnapshotText');
const freezePill = document.getElementById('healthFreezePill');
const freezeVal = document.getElementById('healthFreezeVal');
const freezeSub = document.getElementById('healthFreezeSub');
const modalCount = document.getElementById('freezeRecordCounter');
const total = currentSnapshots.length;
if (modalCount) {
modalCount.textContent = `${total} records logged`;
}
if (selectedGameId) {
const gameSnaps = currentSnapshots.filter(s => s.game_id === selectedGameId);
if (gameSnaps.length > 0) {
const isTnf = selectedGameId.includes('NE_CHI');
if (badge) badge.style.display = 'inline-flex';
if (badgeText) badgeText.textContent = isTnf ? `TNF SNAPSHOT: ${gameSnaps.length} MKTS • CONTENT HASH ✓` : `GAME SNAPSHOT: ${gameSnaps.length} MKTS • CONTENT HASH ✓`;
if (freezePill) {
freezePill.textContent = 'Game Locked ✓';
freezePill.className = 'health-tile-pill pill-frozen';
}
if (freezeVal) freezeVal.textContent = `${gameSnaps.length} Frozen`;
if (freezeSub) freezeSub.textContent = `${selectedGameId.replace('2026_07_', '').replace('_', ' @ ')} pre-kickoff • content hash`;
} else {
if (badge) badge.style.display = 'inline-flex';
if (badgeText) badgeText.textContent = `UNFROZEN GAME • PENDING LOCK`;
if (freezePill) {
freezePill.textContent = 'Pending Lock';
freezePill.className = 'health-tile-pill pill-pending';
}
if (freezeVal) freezeVal.textContent = 'Unfrozen';
if (freezeSub) freezeSub.textContent = 'Click to freeze pre-kickoff snapshot';
}
return;
}
// Full slate context
if (total > 0) {
if (badge) badge.style.display = 'inline-flex';
if (badgeText) badgeText.textContent = `SNAPSHOT ACTIVE • ${total} RECORDS • CONTENT HASH ✓`;
if (freezePill) {
freezePill.textContent = 'Locked ✓';
freezePill.className = 'health-tile-pill pill-frozen';
}
if (freezeVal) freezeVal.textContent = `${total} Records`;
if (freezeSub) freezeSub.textContent = 'TNF & Week 7 pre-kickoff • content hash';
} else {
if (badge) badge.style.display = 'none';
if (freezePill) {
freezePill.textContent = 'Pending';
freezePill.className = 'health-tile-pill pill-unquoted';
}
if (freezeVal) freezeVal.textContent = '0 Frozen';
if (freezeSub) freezeSub.textContent = 'Click to execute freeze snapshot';
}
}
// --------------------------------------------------------------------------
// Opportunity Summary & View Modes
// --------------------------------------------------------------------------
function setViewMode(mode) {
currentViewMode = mode;
syncViewModeButtons();
if (mode === 'injury_surges') {
currentQuickFilter = 'injuries';
} else if (mode === 'surges') {
currentQuickFilter = 'surges';
} else if (mode === 'verified_quotes' && !currentQualifiedOnly && !selectedGameId) {
currentQuickFilter = 'all';
}
syncQuickFilterPillsUI();
renderSlateHealthStrip();
renderOpportunitySummary();
renderBestOpportunitiesGrid();
renderBoard();
}
function syncViewModeButtons() {
['baseline', 'surges', 'injury_surges', 'verified_quotes', 'demo_quotes'].forEach(m => {
let btnId = `btnMode${capitalize(m)}`;
if (m === 'demo_quotes') btnId = 'btnModeDemoQuotes';
if (m === 'injury_surges') btnId = 'btnModeInjurySurges';
if (m === 'verified_quotes') btnId = 'btnModeVerifiedQuotes';
const btn = document.getElementById(btnId);
if (btn) btn.classList.toggle('active', m === currentViewMode);
});
}
function renderOpportunitySummary() {
const title = document.getElementById('oppSummaryTitle');
const sub = document.getElementById('oppSummarySub');
const notice = document.getElementById('emptyStateNotice');
const ingestedCount = (currentLiveOddsData && currentLiveOddsData.quotes) ? currentLiveOddsData.quotes.length : 0;
const evaluated = (currentLiveOddsData && currentLiveOddsData.quotes ? currentLiveOddsData.quotes : [])
.map(quote => slateData.find(player => player.player_id === quote.player_id))
.filter(Boolean)
.map(getEvaluatedPlayerRow);
const verifiedCount = evaluated.filter(row => row.isVerifiedQuote).length;
const verifiedQualified = evaluated.filter(row => row.isVerifiedQuote && row.isQualified).length;
const tabBadge = document.getElementById('verifiedQuotesTabCount');
if (tabBadge) tabBadge.textContent = verifiedCount;
if (currentViewMode === 'verified_quotes') {
if (title) title.textContent = `Market State: ${verifiedCount} Verified Quotes • ${ingestedCount} Ingested`;
if (sub) sub.textContent = 'A quote can qualify only after its provider receipt or source URL passes validation.';
if (notice) {
notice.innerHTML = `
<strong>Fail-Closed Market Validation:</strong>
${ingestedCount} timestamped quote assertions were ingested; ${verifiedCount} include auditable provider evidence.
<strong>${verifiedQualified} verified opportunities qualify.</strong> Unverified quotes remain visible for diagnosis but always carry a 0.00% stake.
`;
}
} else if (currentViewMode === 'injury_surges') {
const validatedInjuryCount = slateData.filter(player => Boolean(getValidatedBeneficiary(player))).length;
if (title) title.textContent = `Injury Redistribution Radar: ${validatedInjuryCount} Validated Beneficiaries`;
if (sub) sub.textContent = 'Injury adjustments require a matching player, team, game, numeric redistribution inputs, and an auditable source URL.';
if (notice) {
notice.innerHTML = `
<strong>Fail-Closed Injury Validation:</strong>
${validatedInjuryCount > 0 ? 'Validated redistribution scenarios are applied.' : 'No injury records currently include sufficient source evidence, so all role adjustments are disabled.'}
`;
}
} else if (currentViewMode === 'baseline') {
if (title) title.textContent = 'Market State: Pure Calibrated 50/50 Baselines';
if (sub) sub.textContent = 'Displaying calibrated fair lines without market quotes. The model never fabricates quotes.';
if (notice) {
notice.innerHTML = `
<strong>💡 Terminal Guidance • Pre-Line Openers Phase:</strong>
Sportsbooks typically post receiving prop lines 24–48 hours prior to kickoff. TNF (NE @ CHI) openers post first, followed by Sunday matchups.
Use the <strong>Price-to-Act Boundaries</strong> below to identify potential mispricings: when books open, any quote meeting the price boundary automatically surfaces as a verified opportunity.
`;
}
} else if (currentViewMode === 'surges') {
if (title) title.textContent = 'Role Shift Filter: 12 Key Target Surges Isolated';
if (sub) sub.textContent = 'Showing receivers whose recent target share exceeds multi-week and career baselines by >= 8%.';
if (notice) {
notice.innerHTML = `
<strong>🔍 Role-Change Detection Active:</strong>
Isolating receivers with substantial offensive volume expansion. Compare their model fair lines against pending market quotes to identify stale book lines once markets open.
<em>Note: Role classification thresholds remain provisional pending chronological holdout validation.</em>
`;
}
} else if (currentViewMode === 'demo_quotes') {
if (title) title.textContent = 'Hypothetical Scenario Explorer: Simulated Market Lines';
if (sub) sub.textContent = 'Simulating hypothetical market discounts to demonstrate price qualification and break-even advantage.';
if (notice) {
notice.innerHTML = `
<strong style="color:var(--status-amber);">⚠️ Hypothetical Scenarios Only:</strong>
Lines below include simulated book discounts for workflow demonstration purposes. These are <strong>not verified quotes</strong> and must never be treated as live betting recommendations.
`;
}
}
}
// --------------------------------------------------------------------------
// Game Strip (Horizontal Matchup Filter)
// --------------------------------------------------------------------------
function renderGameStrip() {
const track = document.getElementById('gameStripTrack');
if (!track) return;
if (gamesData.length === 0) {
track.innerHTML = '<div style="font-size:12px; color:var(--text-ink-tertiary); padding:6px;">Schedule loading...</div>';
return;
}
const allActive = selectedGameId === null ? 'active' : '';
let html = `
<div class="game-pill ${allActive}" onclick="selectGameMatchup(null)">
<div class="game-pill-teams">ALL MATCHUPS</div>
<div class="game-pill-meta"><span>14 Games</span><span>28 Teams</span></div>
</div>
`;
gamesData.forEach(g => {
const isSel = selectedGameId === g.game_id ? 'active' : '';
const spreadStr = g.spread_line !== null ? (g.spread_line > 0 ? `+${g.spread_line}` : `${g.spread_line}`) : 'PK';
const totalStr = g.total_line !== null ? `${g.total_line} O/U` : 'Total TBD';
html += `
<div class="game-pill ${isSel}" onclick="selectGameMatchup('${g.game_id}')">
<div class="game-pill-teams">
<span>${g.away_team} @ ${g.home_team}</span>
</div>
<div class="game-pill-meta">
<span>${spreadStr}</span>
<span>${totalStr}</span>
</div>
</div>
`;
});
track.innerHTML = html;
}
function selectGameMatchup(gameId) {
selectedGameId = gameId;
renderGameStrip();
updateGameFilterLabels();
renderSnapshotStatus();
renderBestOpportunitiesGrid();
renderBoard();
}
function clearMatchupFilter() {
selectGameMatchup(null);
}
function updateGameFilterLabels() {
const label = document.getElementById('activeMatchupFilterText');
const btn = document.getElementById('clearMatchupBtn');
if (!label) return;
if (selectedGameId) {
const g = gamesData.find(x => x.game_id === selectedGameId);
if (g) {
label.textContent = `${g.away_team} @ ${g.home_team}`;
if (btn) btn.style.display = 'inline';
return;
}
}
label.textContent = 'All Matchups';
if (btn) btn.style.display = 'none';
}
function populateTeamDropdown() {
const select = document.getElementById('teamFilter');
if (!select || slateData.length === 0) return;
const teams = [...new Set(slateData.map(p => p.team))].sort();
select.innerHTML = '<option value="ALL">All Teams</option>' +
teams.map(t => `<option value="${t}">${t}</option>`).join('');
}
function populateAdminGameSelect() {
const sel = document.getElementById('adminFreezeGameSelect');
if (!sel || !gamesData || gamesData.length === 0) return;
let html = `<option value="ALL">Full Slate (All ${gamesData.length} Games)</option>`;
gamesData.forEach(g => {
const isTnf = g.game_id && g.game_id.includes('NE_CHI');
const label = isTnf ? `TNF: ${g.away_team} @ ${g.home_team} (${g.game_id})` : `${g.away_team} @ ${g.home_team} (${g.game_id})`;
html += `<option value="${g.game_id}" ${isTnf ? 'selected' : ''}>${label}</option>`;
});
sel.innerHTML = html;
}
// --------------------------------------------------------------------------
// Role-Change Detection Engine (Sustained vs Noise)
// --------------------------------------------------------------------------
function detectPlayerRoleShift(p) {
const recentShare = Number(p.target_share || 0);
const baselineShare = Number(p.f_tgt_share || 0);
const careerTgts = Number(p.c_targets || 0);
const gamesPrior = Number(p.games_prior || 0);
const tgtSd = Number(p.f_tgt_sd || 3.0);
const diff = recentShare - baselineShare;
if (recentShare === 0 && baselineShare === 0) {
return {
type: 'LIMITED_SAMPLE',
label: 'LIMITED SAMPLE',
class: 'role-stable',
diff: 0,
recentShare,
baselineShare,
careerTgts,
description: 'Insufficient historical target tracking.'
};
}
// 1. Sustained Role Surge
// Target share >= +8% above multi-week baseline AND multi-week baseline >= 15% AND prior games >= 12
if (diff >= 0.08 && gamesPrior >= 12 && baselineShare >= 0.15) {
return {
type: 'SUSTAINED_SURGE',
label: 'SUSTAINED ROLE SURGE',
class: 'role-surge',
diff,
recentShare,
baselineShare,
careerTgts,
description: `Target share surged to ${(recentShare * 100).toFixed(1)}% (+${(diff * 100).toFixed(1)}% over ${(baselineShare * 100).toFixed(1)}% baseline). Sustained offensive target priority.`
};
}
// 2. One-Game Spike (High Volatility / Fluke)
// Single-game spike of >= +12% but high target SD or low prior games
if (diff >= 0.12 && (tgtSd >= 3.8 || gamesPrior < 20 || baselineShare < 0.14)) {
return {
type: 'ONE_GAME_SPIKE',
label: 'ONE-GAME SPIKE (VOLATILE)',
class: 'role-spike',
diff,
recentShare,
baselineShare,
careerTgts,
description: `Target share spiked to ${(recentShare * 100).toFixed(1)}% (+${(diff * 100).toFixed(1)}% spike), but exhibits high historical variance (SD: ${tgtSd.toFixed(1)}). Unconfirmed if sustained.`
};
}
// 3. Significant Role Drop
if (diff <= -0.08) {
return {
type: 'ROLE_CONTRACTION',
label: 'ROLE CONTRACTION',
class: 'role-drop',
diff,
recentShare,
baselineShare,
careerTgts,
description: `Target share dropped to ${(recentShare * 100).toFixed(1)}% (${(diff * 100).toFixed(1)}% below ${(baselineShare * 100).toFixed(1)}% baseline). Reduced offensive priority.`
};
}
// 4. Stable Established Volume
if (baselineShare >= 0.22 || careerTgts >= 6.5) {
return {
type: 'ESTABLISHED_VOLUME',
label: 'ESTABLISHED VOLUME',
class: 'role-stable',
diff,
recentShare,
baselineShare,
careerTgts,
description: `Consistent high-volume target earner (Career: ${careerTgts.toFixed(1)} tgts/g, Baseline: ${(baselineShare * 100).toFixed(1)}% share). Stable offensive anchor.`
};
}
return {
type: 'ROTATIONAL',
label: 'ROTATIONAL ROLE',
class: 'role-stable',
diff,
recentShare,
baselineShare,
careerTgts,
description: `Standard rotational receiver (Baseline: ${(baselineShare * 100).toFixed(1)}% target share).`
};
}
// --------------------------------------------------------------------------
// Price Boundary Calculator (Maximum Line / Minimum Odds to Act)
// --------------------------------------------------------------------------
function calculatePriceBoundaries(muRec, muYpr, market, fairLine) {
let maxOverLine = null;
let minUnderLine = null;
const step = market === 'receptions' ? 0.5 : 1.0;
// Test lower lines for Over qualification (10% edge + positive EV at -110)
for (let l = fairLine - step; l >= Math.max(0.5, fairLine - 25); l -= step) {
const res = evaluateLineAndOdds(muRec, muYpr, market, l, -110);
if (res.bestSide === 'OVER' && res.probEdge >= 0.10 && res.expectedReturn > 0) {
maxOverLine = l;
break;
}
}
// Test higher lines for Under qualification (10% edge + positive EV at -110)
for (let l = fairLine + step; l <= fairLine + 25; l += step) {
const res = evaluateLineAndOdds(muRec, muYpr, market, l, -110);
if (res.bestSide === 'UNDER' && res.probEdge >= 0.10 && res.expectedReturn > 0) {
minUnderLine = l;
break;
}
}
const atFair = evaluateLineAndOdds(muRec, muYpr, market, fairLine, -110);
const fairWinProb = atFair.decisionWinProb;
const breakEvenOddsAtFair = probToAmerican(fairWinProb);
return {
maxOverLine: maxOverLine ? maxOverLine.toFixed(1) : (fairLine - (market === 'receptions' ? 1.0 : 6.0)).toFixed(1),
minUnderLine: minUnderLine ? minUnderLine.toFixed(1) : (fairLine + (market === 'receptions' ? 1.0 : 6.0)).toFixed(1),
breakEvenOddsAtFair: breakEvenOddsAtFair > 0 ? `+${breakEvenOddsAtFair}` : `${breakEvenOddsAtFair}`
};
}
// --------------------------------------------------------------------------
// Mathematical & Pricing Evaluation Engine (3 Distinct Quant Metrics)
// --------------------------------------------------------------------------
function evaluateLineAndOdds(muRec, muYpr, market, line, offeredOdds, bias = 0.0) {
const isWhole = Math.abs(line - Math.round(line)) < 1e-4;
let pOver = 0;
let pUnder = 0;
let pPush = 0;
if (market === 'receptions') {
const r = 1.0 / MODEL_ALPHA;
const p = r / (r + muRec);
if (isWhole) {
const k = Math.round(line);
pPush = nbPmf(k, r, p);
pOver = Math.max(0.001, Math.min(0.999, pRecOver(muRec, k) - bias));
pUnder = Math.max(0.001, Math.min(0.999, 1.0 - pOver - pPush));
} else {
pPush = 0.0;
pOver = Math.max(0.001, Math.min(0.999, pRecOver(muRec, line) - bias));
pUnder = Math.max(0.001, Math.min(0.999, 1.0 - pOver));
}
} else {
// Receiving yards
if (isWhole) {
const L = Math.round(line);
// Discrete integer grading: box scores report integer yards; pushes occur on exact integers
const cdfLo = compoundYardsCdf(muRec, muYpr, L - 0.5);
const cdfHi = compoundYardsCdf(muRec, muYpr, L + 0.5);
pPush = Math.max(0.0, cdfHi - cdfLo);
pOver = Math.max(0.001, Math.min(0.999, (1.0 - cdfHi) - bias));
pUnder = Math.max(0.001, Math.min(0.999, cdfLo));
const s = pOver + pUnder + pPush;
if (s > 0) {
pOver /= s;
pUnder /= s;
pPush /= s;
}
} else {
pPush = 0.0;
pOver = Math.max(0.001, Math.min(0.999, pYardsOver(muRec, muYpr, line) - bias));
pUnder = Math.max(0.001, Math.min(0.999, 1.0 - pOver));
}
}
const decOdds = americanToDecimal(offeredOdds);
const breakEvenProb = 1.0 / decOdds;
const deviggedMktProb = 0.50; // Reference 50/50 fair market price
// Expected returns per dollar staked
const evOver = pOver * (decOdds - 1.0) - (1.0 - pOver - pPush);
const evUnder = pUnder * (decOdds - 1.0) - (1.0 - pUnder - pPush);
const bestSide = evOver >= evUnder ? 'OVER' : 'UNDER';
const winProb = bestSide === 'OVER' ? pOver : pUnder;
const lossProb = 1.0 - winProb - pPush;
// Pushes return the stake, so price comparisons must use the probability
// conditional on a graded decision. Using raw win probability makes a
// 50/50 whole-number market appear to require plus money.
const decisionWinProb = (winProb + lossProb) > 0
? winProb / (winProb + lossProb)
: 0.50;
const expectedReturn = winProb * (decOdds - 1.0) - lossProb;
// 1. Probability edge: Model probability minus devigged market probability
const probEdge = decisionWinProb - deviggedMktProb;
// 2. Break-even advantage: Model probability minus offered price's break-even probability
const breakEvenAdvantage = decisionWinProb - breakEvenProb;
return {
line,
pOver,
pUnder,
pPush,
bestSide,
winProb,
lossProb,
decisionWinProb,
breakEvenProb,
deviggedMktProb,
probEdge,
breakEvenAdvantage,
expectedReturn,
decOdds,
offeredOdds
};
}
function isFiniteNumber(value) {
return Number.isFinite(Number(value));
}
function getValidatedBeneficiary(p) {
const beneficiaries = currentInjuriesData && currentInjuriesData.impacted_beneficiaries;
const injuries = currentInjuriesData && currentInjuriesData.injuries;
if (!beneficiaries || !p) return null;
const ben = beneficiaries[p.player_id];
if (!ben) return null;
const injury = Array.isArray(injuries)
? injuries.find(item => item.injury_id === ben.injury_id)
: null;
const conditional = ben.conditional || {};
const identityMatches = ben.player_id === p.player_id
&& ben.player_name === p.player_display_name
&& ben.team === p.team
&& ben.opponent === p.opponent_team
&& ben.game_id === p.game_id;
const catalystMatches = injury
&& injury.team === p.team
&& injury.opponent === p.opponent_team
&& injury.game_id === p.game_id;
const catalystHasEvidence = injury
&& typeof injury.source_url === 'string'
&& /^https:\/\//i.test(injury.source_url);
const numericFieldsValid = [
ben.absorption_share,
ben.added_targets,
ben.added_air_yards,
conditional.mu_rec,
conditional.mu_ypr,
conditional.fair_line_rec,
conditional.fair_line_yards
].every(isFiniteNumber);
return identityMatches && catalystMatches && catalystHasEvidence && numericFieldsValid
? { ...ben, catalyst: injury }
: null;
}