Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1189 lines (1029 loc) · 39 KB
/
Copy pathscript.js
File metadata and controls
1189 lines (1029 loc) · 39 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
/* global Chart */
const playerSelect = document.getElementById("playerSelect");
const playerDropdownList = document.getElementById("playerDropdownList");
const statusMsg = document.getElementById("statusMsg");
const pageLoader = document.getElementById("pageLoader");
const pageLoaderText = document.getElementById("pageLoaderText");
const impactScoreValue = document.getElementById("impactScoreValue");
const gaugeFill = document.getElementById("gaugeFill");
const gaugeCanvas = document.getElementById("gaugeChart");
const summaryRole = document.getElementById("summaryRole");
const summaryMatches = document.getElementById("summaryMatches");
const summaryAvgImpact = document.getElementById("summaryAvgImpact");
const summaryTeam = document.getElementById("summaryTeam");
const summaryRecentImpact = document.getElementById("summaryRecentImpact");
const summaryHighPressure = document.getElementById("summaryHighPressure");
const summaryPrimaryPhase = document.getElementById("summaryPrimaryPhase");
const impactCategoryTitle = document.getElementById("impactCategoryTitle");
const impactCategorySub = document.getElementById("impactCategorySub");
const mlImpactValue = document.getElementById("mlImpactValue");
const mlDeltaValue = document.getElementById("mlDeltaValue");
const mlImpactBar = document.getElementById("mlImpactBar");
const roleBadge = document.getElementById("roleBadge");
const roleMetric1Label = document.getElementById("roleMetric1Label");
const roleMetric1Value = document.getElementById("roleMetric1Value");
const roleMetric2Label = document.getElementById("roleMetric2Label");
const roleMetric2Value = document.getElementById("roleMetric2Value");
const roleMetric3Label = document.getElementById("roleMetric3Label");
const roleMetric3Value = document.getElementById("roleMetric3Value");
const roleMetric4Label = document.getElementById("roleMetric4Label");
const roleMetric4Value = document.getElementById("roleMetric4Value");
const roleMetric5Label = document.getElementById("roleMetric5Label");
const roleMetric5Value = document.getElementById("roleMetric5Value");
const roleFinal = document.getElementById("roleFinal");
const roleMetricNote = document.getElementById("roleMetricNote");
const trendPlayerLabel = document.getElementById("trendPlayerLabel");
const trendTableBody = document.getElementById("trendTableBody");
const trendModeToggle = document.getElementById("trendModeToggle");
const pressureIndexValue = document.getElementById("pressureIndexValue");
const pressureLevelBadge = document.getElementById("pressureLevelBadge");
const pressureIndexBar = document.getElementById("pressureIndexBar");
const highPressureShare = document.getElementById("highPressureShare");
const clutchScoreValue = document.getElementById("clutchScoreValue");
const clutchTag = document.getElementById("clutchTag");
const clutchScoreBar = document.getElementById("clutchScoreBar");
const clutchSummary = document.getElementById("clutchSummary");
const phasePowerplay = document.getElementById("phasePowerplay");
const phaseMiddle = document.getElementById("phaseMiddle");
const phaseDeath = document.getElementById("phaseDeath");
const phasePowerplayBar = document.getElementById("phasePowerplayBar");
const phaseMiddleBar = document.getElementById("phaseMiddleBar");
const phaseDeathBar = document.getElementById("phaseDeathBar");
const phaseRolePowerplay = document.getElementById("phaseRolePowerplay");
const phaseRoleMiddle = document.getElementById("phaseRoleMiddle");
const phaseRoleDeath = document.getElementById("phaseRoleDeath");
const phaseInsightPrimary = document.getElementById("phaseInsightPrimary");
const phaseInsightText = document.getElementById("phaseInsightText");
const rankingTableBody = document.getElementById("rankingTableBody");
const mlFeatureImportancePanel = document.getElementById("mlFeatureImportancePanel");
const compareASelect = document.getElementById("compareASelect");
const compareBSelect = document.getElementById("compareBSelect");
const compareADropdownList = document.getElementById("compareADropdownList");
const compareBDropdownList = document.getElementById("compareBDropdownList");
const compareAScore = document.getElementById("compareAScore");
const compareBScore = document.getElementById("compareBScore");
let playerScores = [];
let impactDataset = [];
let mlScores = [];
let mlFeatureImportance = [];
let allPlayers = [];
let visiblePlayers = [];
let trendChart = null;
let compareTrendChart = null;
let distributionChart = null;
let gaugeChart = null;
let rankingRows = [];
function escapeHtml(text) {
return text
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function setDropdownItems(players) {
visiblePlayers = players;
if (players.length === 0) {
playerDropdownList.innerHTML = '<li class="px-3 py-2 text-slate-500">No players found</li>';
playerDropdownList.classList.remove("hidden");
return;
}
playerDropdownList.innerHTML = players
.map(
(p) =>
`<li><button type="button" class="w-full text-left px-3 py-2 hover:bg-slate-100" data-player="${escapeHtml(p)}">${escapeHtml(p)}</button></li>`
)
.join("");
playerDropdownList.classList.remove("hidden");
}
function closePlayerDropdown() {
playerDropdownList.classList.add("hidden");
}
function filterPlayers(query) {
const q = query.trim().toLowerCase();
if (!q) return allPlayers;
return allPlayers.filter((p) => p.toLowerCase().includes(q));
}
function setupComboInput(inputEl, listEl, onSelect) {
let visible = [];
function close() {
listEl.classList.add("hidden");
}
function setItems(players) {
visible = players;
if (players.length === 0) {
listEl.innerHTML = '<li class="px-3 py-2 text-slate-500">No players found</li>';
listEl.classList.remove("hidden");
return;
}
listEl.innerHTML = players
.map(
(p) =>
`<li><button type="button" class="w-full text-left px-3 py-2 hover:bg-slate-100" data-player="${escapeHtml(p)}">${escapeHtml(p)}</button></li>`
)
.join("");
listEl.classList.remove("hidden");
}
function selectFromInput() {
const typed = inputEl.value.trim().toLowerCase();
if (!typed) return;
const exact = allPlayers.find((p) => p.toLowerCase() === typed);
const partial = allPlayers.find((p) => p.toLowerCase().includes(typed));
const selected = exact || partial;
if (!selected) return;
inputEl.value = selected;
close();
onSelect(selected);
}
inputEl.addEventListener("focus", () => {
setItems(filterPlayers(inputEl.value));
});
inputEl.addEventListener("input", () => {
setItems(filterPlayers(inputEl.value));
});
inputEl.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
if (visible.length > 0) {
inputEl.value = visible[0];
}
selectFromInput();
}
if (e.key === "Escape") {
close();
}
});
listEl.addEventListener("click", (e) => {
const target = e.target.closest("button[data-player]");
if (!target) return;
inputEl.value = target.dataset.player;
close();
onSelect(target.dataset.player);
});
document.addEventListener("click", (e) => {
const withinPicker = e.target === inputEl || listEl.contains(e.target);
if (!withinPicker) {
close();
}
});
return {
close,
selectFromInput
};
}
function pickPlayerFromInput() {
const typed = playerSelect.value.trim().toLowerCase();
if (!typed) return;
const exact = allPlayers.find((p) => p.toLowerCase() === typed);
const partial = allPlayers.find((p) => p.toLowerCase().includes(typed));
const selected = exact || partial;
if (!selected) {
statusMsg.textContent = `No player found for "${playerSelect.value.trim()}".`;
return;
}
playerSelect.value = selected;
renderPlayer(selected);
closePlayerDropdown();
statusMsg.textContent = `Loaded ${allPlayers.length} players.`;
}
function populatePlayerSelect(players, selectedPlayer) {
if (players.length === 0) {
playerSelect.value = "";
return "";
}
visiblePlayers = players;
const nextSelected = players.includes(selectedPlayer) ? selectedPlayer : players[0];
playerSelect.value = nextSelected;
return nextSelected;
}
function toNumber(value, fallback = 0) {
const n = Number(value);
return Number.isFinite(n) ? n : fallback;
}
function setPageLoading(isLoading, message = "Loading dashboard data...") {
if (!pageLoader) return;
if (pageLoaderText) {
pageLoaderText.textContent = message;
}
pageLoader.classList.toggle("hidden", !isLoading);
}
function parseCSV(text) {
const rows = [];
let cur = "";
let row = [];
let inQuotes = false;
for (let i = 0; i < text.length; i += 1) {
const c = text[i];
const next = text[i + 1];
if (c === '"') {
if (inQuotes && next === '"') {
cur += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
continue;
}
if (c === "," && !inQuotes) {
row.push(cur);
cur = "";
continue;
}
if ((c === "\n" || c === "\r") && !inQuotes) {
if (c === "\r" && next === "\n") {
i += 1;
}
row.push(cur);
cur = "";
if (row.length > 1 || (row.length === 1 && row[0] !== "")) {
rows.push(row);
}
row = [];
continue;
}
cur += c;
}
if (cur.length > 0 || row.length > 0) {
row.push(cur);
rows.push(row);
}
if (rows.length === 0) return [];
const headers = rows[0].map((h) => h.trim());
return rows.slice(1).map((r) => {
const obj = {};
headers.forEach((h, idx) => {
obj[h] = (r[idx] || "").trim();
});
return obj;
});
}
async function fetchCsvFromPaths(paths) {
for (const path of paths) {
try {
const res = await fetch(path);
if (res.ok) {
const text = await res.text();
return parseCSV(text);
}
} catch (_err) {
// Try next path.
}
}
return [];
}
function groupMeanByPlayer(rows) {
const map = new Map();
rows.forEach((r) => {
const player = r.player;
const score = toNumber(r.IM_score ?? r.impact_score, 0);
if (!map.has(player)) {
map.set(player, { sum: 0, count: 0 });
}
const item = map.get(player);
item.sum += score;
item.count += 1;
});
return [...map.entries()]
.map(([player, v]) => ({
player,
impact: v.count > 0 ? v.sum / v.count : 0
}))
.sort((a, b) => b.impact - a.impact);
}
function latestPlayerScore(playerRows) {
const sorted = [...playerRows].sort((a, b) => {
const da = new Date(a.match_date || "1970-01-01").getTime();
const db = new Date(b.match_date || "1970-01-01").getTime();
if (da !== db) return da - db;
return toNumber(a.match_id) - toNumber(b.match_id);
});
return sorted[sorted.length - 1] || null;
}
function latestMlPlayerScore(playerRows) {
const sorted = [...playerRows].sort((a, b) => {
const da = new Date(a.match_date || "1970-01-01").getTime();
const db = new Date(b.match_date || "1970-01-01").getTime();
if (da !== db) return da - db;
return toNumber(a.match_id) - toNumber(b.match_id);
});
return sorted[sorted.length - 1] || null;
}
function updateGauge(score) {
const clamped = Math.max(0, Math.min(100, score));
impactScoreValue.textContent = clamped.toFixed(1);
gaugeFill.style.width = `${clamped}%`;
if (!gaugeChart) {
gaugeChart = new Chart(gaugeCanvas, {
type: "doughnut",
data: {
labels: ["Score", "Remaining"],
datasets: [
{
data: [clamped, 100 - clamped],
backgroundColor: ["#0B6E4F", "#E5E7EB"],
borderWidth: 0,
cutout: "75%"
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
rotation: -90,
circumference: 180,
plugins: {
legend: { display: false },
tooltip: { enabled: false }
}
}
});
} else {
gaugeChart.data.datasets[0].data = [clamped, 100 - clamped];
gaugeChart.update();
}
}
function updateMlImpact(player, ruleScore) {
const rows = mlScores.filter((r) => r.player === player);
if (rows.length === 0) {
mlImpactValue.textContent = "-";
mlDeltaValue.textContent = "N/A";
mlImpactBar.style.width = "0%";
return;
}
const latest = latestMlPlayerScore(rows);
const mlScore = Math.max(0, Math.min(100, toNumber(latest.ml_impact_score, 0)));
const delta = mlScore - ruleScore;
mlImpactValue.textContent = mlScore.toFixed(1);
mlDeltaValue.textContent = `${delta >= 0 ? "+" : ""}${delta.toFixed(1)}`;
mlDeltaValue.className = delta >= 0 ? "font-semibold text-emerald-700" : "font-semibold text-rose-700";
mlImpactBar.style.width = `${mlScore}%`;
}
function extractTrendScore(point, useMlTrend) {
if (useMlTrend) {
return toNumber(point.ml_impact_score, 0);
}
return toNumber(point.IM_score ?? point.impact_score, 0);
}
function renderTrendTable(points, useMlTrend) {
trendTableBody.innerHTML = points
.map((point, idx) => {
const score = extractTrendScore(point, useMlTrend);
return `
<tr class="border-b border-slate-100">
<td class="py-2 px-3">Match${idx + 1}</td>
<td class="py-2 px-3 text-right font-semibold">${score.toFixed(1)}</td>
</tr>`;
})
.join("");
}
function buildTrend(points, useMlTrend) {
const labels = points.map((_, idx) => `Match${idx + 1}`);
const data = points.map((p) => extractTrendScore(p, useMlTrend));
if (trendChart) {
trendChart.destroy();
}
const ctx = document.getElementById("trendChart");
trendChart = new Chart(ctx, {
type: "line",
data: {
labels,
datasets: [
{
label: useMlTrend ? "ML Impact Score" : "Impact Score",
data,
borderColor: useMlTrend ? "#0369A1" : "#0B6E4F",
backgroundColor: useMlTrend ? "rgba(3, 105, 161, 0.15)" : "rgba(11, 110, 79, 0.15)",
pointBackgroundColor: useMlTrend ? "#38BDF8" : "#F39C12",
pointRadius: 3,
borderWidth: 2,
tension: 0.3,
fill: true
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false }
},
scales: {
y: {
min: 0,
max: 100
}
}
}
});
}
function inferPlayerRole(rows) {
const totalRuns = rows.reduce((acc, r) => acc + toNumber(r.runs_scored, 0), 0);
const totalWickets = rows.reduce((acc, r) => acc + toNumber(r.wickets_taken, 0), 0);
const battingEvents = rows.filter(
(r) => toNumber(r.balls_faced, 0) > 0 || toNumber(r.strike_rate, 0) > 0 || toNumber(r.runs_scored, 0) > 0
).length;
const bowlingEvents = rows.filter(
(r) => toNumber(r.economy, 0) > 0 || toNumber(r.bowler_impact_score, 0) > 0 || toNumber(r.wickets_taken, 0) > 0
).length;
// Rule-of-thumb thresholds for role assignment.
if (totalRuns > 300 && totalWickets < 5) return "batter";
if (totalWickets > 10 && totalRuns < 200) return "bowler";
if (battingEvents > 0 && bowlingEvents > 0) return "allrounder";
if (bowlingEvents > 0) return "bowler";
return "batter";
}
function formatRoleLabel(role) {
if (role === "allrounder") return "All-rounder";
if (role === "bowler") return "Bowler";
return "Batter";
}
function getImpactCategory(rankPct) {
if (rankPct <= 15) {
return {
title: "High Impact Player",
subtitle: `Top ${rankPct.toFixed(0)}%`
};
}
if (rankPct <= 40) {
return {
title: "Strong Impact Player",
subtitle: `Top ${rankPct.toFixed(0)}%`
};
}
if (rankPct <= 70) {
return {
title: "Emerging Impact Player",
subtitle: `Top ${rankPct.toFixed(0)}%`
};
}
return {
title: "Developing Impact Player",
subtitle: `Top ${rankPct.toFixed(0)}%`
};
}
function updatePlayerSummaryCards(player) {
const scoreRows = playerScores.filter((r) => r.player === player);
const featureRows = impactDataset.filter((r) => r.player === player);
if (scoreRows.length === 0) {
summaryTeam.textContent = "-";
summaryRole.textContent = "-";
summaryMatches.textContent = "-";
summaryAvgImpact.textContent = "-";
summaryRecentImpact.textContent = "-";
summaryHighPressure.textContent = "-";
summaryPrimaryPhase.textContent = "-";
impactCategoryTitle.textContent = "-";
impactCategorySub.textContent = "-";
return;
}
const role = inferPlayerRole(featureRows);
const avgImpact = mean(scoreRows.map((r) => toNumber(r.IM_score ?? r.impact_score, 0)));
const recentRows = [...scoreRows]
.sort((a, b) => {
const da = new Date(a.match_date || "1970-01-01").getTime();
const db = new Date(b.match_date || "1970-01-01").getTime();
if (da !== db) return da - db;
return toNumber(a.match_id) - toNumber(b.match_id);
})
.slice(-10);
const recentImpact = mean(recentRows.map((r) => toNumber(r.IM_score ?? r.impact_score, 0)));
const highPressureCount = featureRows.filter((r) => toNumber(r.pressure_index, 0) >= 0.6).length;
const highPressureSharePct = featureRows.length > 0 ? (highPressureCount / featureRows.length) * 100 : 0;
const teamFreq = new Map();
featureRows.forEach((r) => {
const t = String(r.team || "").trim();
if (!t) return;
teamFreq.set(t, (teamFreq.get(t) || 0) + 1);
});
const primaryTeam = [...teamFreq.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] || "-";
const phaseFreq = new Map();
featureRows.forEach((r) => {
const p = String(r.phase || "").toLowerCase();
if (!p) return;
phaseFreq.set(p, (phaseFreq.get(p) || 0) + 1);
});
const phaseRaw = [...phaseFreq.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] || "middle";
const phaseLabel = phaseRaw === "powerplay" ? "Powerplay" : phaseRaw === "death" ? "Death" : "Middle";
const rankIndex = rankingRows.findIndex((r) => r.player === player);
const rankPct = rankIndex >= 0 && rankingRows.length > 0
? ((rankIndex + 1) / rankingRows.length) * 100
: 100;
const category = getImpactCategory(rankPct);
summaryTeam.textContent = primaryTeam;
summaryRole.textContent = formatRoleLabel(role);
summaryMatches.textContent = String(scoreRows.length);
summaryAvgImpact.textContent = avgImpact.toFixed(1);
summaryRecentImpact.textContent = recentImpact.toFixed(1);
summaryHighPressure.textContent = `${highPressureSharePct.toFixed(1)}%`;
summaryPrimaryPhase.textContent = phaseLabel;
impactCategoryTitle.textContent = category.title;
impactCategorySub.textContent = category.subtitle;
}
function computeRoleSnapshot(player, finalImpact) {
const rows = impactDataset.filter((r) => r.player === player);
if (rows.length === 0) {
roleBadge.textContent = "Unknown";
roleBadge.className = "px-3 py-1 rounded-full text-xs font-semibold bg-slate-100 text-slate-700";
roleMetric1Value.textContent = "-";
roleMetric2Value.textContent = "-";
roleMetric3Value.textContent = "-";
roleMetric4Value.textContent = "-";
roleMetric5Value.textContent = "-";
roleFinal.textContent = finalImpact.toFixed(1);
return;
}
const role = inferPlayerRole(rows);
const highPressureRows = rows.filter((r) => toNumber(r.pressure_index, 0) >= 0.6);
const totalRuns = rows.reduce((acc, r) => acc + toNumber(r.runs_scored, 0), 0);
const totalBalls = rows.reduce((acc, r) => acc + toNumber(r.balls_faced, 0), 0);
const strikeRate = totalBalls > 0 ? (totalRuns * 100) / totalBalls : 0;
const totalWickets = rows.reduce((acc, r) => acc + toNumber(r.wickets_taken, 0), 0);
const economyRows = rows.filter((r) => toNumber(r.economy, 0) > 0);
const avgEconomy = economyRows.length > 0 ? mean(economyRows.map((r) => toNumber(r.economy, 0))) : 0;
const battingImpact = mean(rows.map((r) => toNumber(r.batter_impact_score, 0)));
const bowlingImpact = mean(rows.map((r) => toNumber(r.bowler_impact_score, 0)));
if (role === "bowler") {
const dotBallPct = Math.max(10, Math.min(75, 65 - avgEconomy * 5));
const deathRows = rows.filter((r) => (r.phase || "").toLowerCase() === "death");
const deathPerformance =
deathRows.length > 0
? mean(deathRows.map((r) => toNumber(r.bowler_impact_score, 0)))
: 0;
roleBadge.textContent = "Bowler";
roleBadge.className = "px-3 py-1 rounded-full text-xs font-semibold bg-sky-100 text-sky-700";
roleMetric1Label.textContent = "Wickets";
roleMetric1Value.textContent = totalWickets.toFixed(0);
roleMetric2Label.textContent = "Economy Rate";
roleMetric2Value.textContent = avgEconomy.toFixed(2);
roleMetric3Label.textContent = "Dot Ball %";
roleMetric3Value.textContent = `${dotBallPct.toFixed(1)}%`;
roleMetric4Label.textContent = "Death Overs Performance";
roleMetric4Value.textContent = deathPerformance.toFixed(1);
roleMetric5Label.textContent = "Bowling Impact";
roleMetric5Value.textContent = bowlingImpact.toFixed(1);
roleMetricNote.textContent = "Dot Ball % is estimated from economy due to aggregate feature granularity.";
} else if (role === "allrounder") {
const allrounderImpact = (0.55 * battingImpact) + (0.45 * bowlingImpact);
roleBadge.textContent = "All-rounder";
roleBadge.className = "px-3 py-1 rounded-full text-xs font-semibold bg-violet-100 text-violet-700";
roleMetric1Label.textContent = "Runs";
roleMetric1Value.textContent = totalRuns.toFixed(0);
roleMetric2Label.textContent = "Strike Rate";
roleMetric2Value.textContent = strikeRate.toFixed(1);
roleMetric3Label.textContent = "Wickets";
roleMetric3Value.textContent = totalWickets.toFixed(0);
roleMetric4Label.textContent = "Economy Rate";
roleMetric4Value.textContent = avgEconomy.toFixed(2);
roleMetric5Label.textContent = "All-rounder Impact";
roleMetric5Value.textContent = allrounderImpact.toFixed(1);
roleMetricNote.textContent = "All-rounder impact blends batting and bowling contribution.";
} else {
const estimatedBoundaries = Math.round(totalRuns / 9);
const clutchRuns = highPressureRows.reduce((acc, r) => acc + toNumber(r.runs_scored, 0), 0);
roleBadge.textContent = "Batter";
roleBadge.className = "px-3 py-1 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-700";
roleMetric1Label.textContent = "Runs";
roleMetric1Value.textContent = totalRuns.toFixed(0);
roleMetric2Label.textContent = "Strike Rate";
roleMetric2Value.textContent = strikeRate.toFixed(1);
roleMetric3Label.textContent = "Boundaries";
roleMetric3Value.textContent = estimatedBoundaries.toFixed(0);
roleMetric4Label.textContent = "Clutch Runs";
roleMetric4Value.textContent = clutchRuns.toFixed(0);
roleMetric5Label.textContent = "Batting Impact";
roleMetric5Value.textContent = battingImpact.toFixed(1);
roleMetricNote.textContent = "Boundaries are estimated from aggregate innings features.";
}
roleFinal.textContent = finalImpact.toFixed(1);
}
function computePhaseContribution(player) {
const rows = impactDataset.filter((r) => r.player === player);
function phaseRoleText(phaseKey, pct) {
const contribution = pct >= 45
? "Primary contribution"
: pct >= 20
? "Supporting contribution"
: "Limited contribution";
if (phaseKey === "powerplay") return `${contribution} as an aggressive starter`;
if (phaseKey === "middle") return `${contribution} as stabilizer`;
return `${contribution} as finisher`;
}
if (rows.length === 0) {
phasePowerplay.textContent = "0%";
phaseMiddle.textContent = "0%";
phaseDeath.textContent = "0%";
phasePowerplayBar.style.width = "0%";
phaseMiddleBar.style.width = "0%";
phaseDeathBar.style.width = "0%";
phaseRolePowerplay.textContent = "-";
phaseRoleMiddle.textContent = "-";
phaseRoleDeath.textContent = "-";
phaseInsightPrimary.textContent = "-";
phaseInsightText.textContent = "No phase insight available yet.";
return;
}
const phaseWeight = { powerplay: 1.1, middle: 1.0, death: 1.4 };
const totals = { powerplay: 0, middle: 0, death: 0 };
rows.forEach((r) => {
const runs = toNumber(r.runs_scored, 0);
const strikeRate = toNumber(r.strike_rate, 0);
const batterImpact = toNumber(r.batter_impact_score, 0);
const bowlerImpact = toNumber(r.bowler_impact_score, 0);
const wickets = toNumber(r.wickets_taken, 0);
const pressure = toNumber(r.pressure_index, 0.5);
const phase = (r.phase || "middle").toLowerCase();
const perfBat = runs * 0.6 + strikeRate * 0.2 + batterImpact * 0.2;
const perfBowl = bowlerImpact * 0.7 + wickets * 10;
const combined = 0.6 * perfBat + 0.4 * perfBowl;
const ctx = (phaseWeight[phase] || 1.0) * (1 + pressure);
const raw = combined * ctx;
if (!totals[phase]) totals[phase] = 0;
totals[phase] += raw;
});
const sum = Object.values(totals).reduce((a, b) => a + b, 0) || 1;
const p = ((totals.powerplay || 0) / sum) * 100;
const m = ((totals.middle || 0) / sum) * 100;
const d = ((totals.death || 0) / sum) * 100;
phasePowerplay.textContent = `${p.toFixed(1)}%`;
phaseMiddle.textContent = `${m.toFixed(1)}%`;
phaseDeath.textContent = `${d.toFixed(1)}%`;
phasePowerplayBar.style.width = `${p}%`;
phaseMiddleBar.style.width = `${m}%`;
phaseDeathBar.style.width = `${d}%`;
phaseRolePowerplay.textContent = phaseRoleText("powerplay", p);
phaseRoleMiddle.textContent = phaseRoleText("middle", m);
phaseRoleDeath.textContent = phaseRoleText("death", d);
const phaseStats = [
{ key: "powerplay", label: "Powerplay", pct: p },
{ key: "middle", label: "Middle Overs", pct: m },
{ key: "death", label: "Death Overs", pct: d }
];
phaseStats.sort((a, b) => b.pct - a.pct);
const primary = phaseStats[0];
let insight = "This phase profile suggests balanced contribution across innings situations.";
if (primary.key === "powerplay") {
insight = "This player contributes most in the powerplay, indicating an aggressive start that creates early momentum.";
} else if (primary.key === "middle") {
insight = "This player contributes most during the middle overs, indicating strong ability to stabilize and build innings momentum.";
} else if (primary.key === "death") {
insight = "This player contributes most in the death overs, showing strong finishing ability under end-phase pressure.";
}
phaseInsightPrimary.textContent = `${primary.label} (${primary.pct.toFixed(1)}%)`;
phaseInsightText.textContent = insight;
}
function getPressureLevel(score) {
if (score >= 60) {
return {
label: "High",
classes: "bg-red-100 text-red-700"
};
}
if (score >= 30) {
return {
label: "Medium",
classes: "bg-amber-100 text-amber-700"
};
}
return {
label: "Low",
classes: "bg-emerald-100 text-emerald-700"
};
}
function getClutchTag(score) {
if (score >= 75) {
return {
label: "Elite",
classes: "bg-emerald-100 text-emerald-700"
};
}
if (score >= 55) {
return {
label: "Reliable",
classes: "bg-sky-100 text-sky-700"
};
}
if (score >= 35) {
return {
label: "Developing",
classes: "bg-amber-100 text-amber-700"
};
}
return {
label: "Low Sample",
classes: "bg-slate-100 text-slate-700"
};
}
function computePressureAndClutch(player) {
const rows = impactDataset.filter((r) => r.player === player);
if (rows.length === 0) {
pressureIndexValue.textContent = "0.0";
pressureLevelBadge.textContent = "Low";
pressureLevelBadge.className = "px-3 py-1 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-700";
pressureIndexBar.style.width = "0%";
highPressureShare.textContent = "0.0%";
clutchScoreValue.textContent = "0.0";
clutchTag.textContent = "Low Sample";
clutchTag.className = "px-3 py-1 rounded-full text-xs font-semibold bg-slate-100 text-slate-700";
clutchScoreBar.style.width = "0%";
clutchSummary.textContent = "No high-pressure summary available yet.";
return;
}
const pressureScores = rows.map((r) => Math.max(0, Math.min(100, toNumber(r.pressure_index, 0) * 100)));
const avgPressure = mean(pressureScores);
const highPressureRows = rows.filter((r) => toNumber(r.pressure_index, 0) * 100 >= 60);
const highShare = (highPressureRows.length / rows.length) * 100;
const pressureLevel = getPressureLevel(avgPressure);
pressureIndexValue.textContent = avgPressure.toFixed(1);
pressureLevelBadge.textContent = pressureLevel.label;
pressureLevelBadge.className = `px-3 py-1 rounded-full text-xs font-semibold ${pressureLevel.classes}`;
pressureIndexBar.style.width = `${avgPressure}%`;
highPressureShare.textContent = `${highShare.toFixed(1)}%`;
const highRuns = highPressureRows.reduce((acc, r) => acc + toNumber(r.runs_scored, 0), 0);
const highBalls = highPressureRows.reduce((acc, r) => acc + toNumber(r.balls_faced, 0), 0);
const highWickets = highPressureRows.reduce((acc, r) => acc + toNumber(r.wickets_taken, 0), 0);
const highStrikeRate = highBalls > 0 ? (highRuns * 100) / highBalls : 0;
const highImpact = mean(
highPressureRows.map(
(r) => 0.6 * toNumber(r.batter_impact_score, 0) + 0.4 * toNumber(r.bowler_impact_score, 0)
)
);
const srComponent = Math.min(100, highStrikeRate / 1.5);
const runsComponent = Math.min(100, highRuns * 2);
const wicketsComponent = Math.min(100, highWickets * 25);
const impactComponent = Math.max(0, Math.min(100, highImpact));
const clutchScore =
0.35 * srComponent +
0.25 * runsComponent +
0.2 * wicketsComponent +
0.2 * impactComponent;
const clutch = Math.max(0, Math.min(100, clutchScore));
const clutchMeta = getClutchTag(clutch);
clutchScoreValue.textContent = clutch.toFixed(1);
clutchTag.textContent = clutchMeta.label;
clutchTag.className = `px-3 py-1 rounded-full text-xs font-semibold ${clutchMeta.classes}`;
clutchScoreBar.style.width = `${clutch}%`;
clutchSummary.textContent =
`High-pressure runs: ${highRuns.toFixed(0)}, SR: ${highStrikeRate.toFixed(1)}, wickets: ${highWickets.toFixed(0)}`;
}
function renderRankingTable(rows) {
const top = rows.slice(0, 10);
rankingTableBody.innerHTML = top
.map(
(r, idx) => `
<tr class="border-b border-slate-100">
<td class="py-2 pr-2">${idx + 1}</td>
<td class="py-2 pr-2">${r.player}</td>
<td class="py-2 text-right font-semibold">${r.impact.toFixed(1)}</td>
</tr>`
)
.join("");
}
function renderMlFeatureImportance() {
if (!mlFeatureImportancePanel) return;
const cleaned = mlFeatureImportance
.map((r) => ({
feature: String(r.feature || "").replaceAll("_", " "),
importancePct: toNumber(r.importance_pct, 0)
}))
.filter((r) => r.feature)
.slice(0, 5);
if (cleaned.length === 0) {
mlFeatureImportancePanel.innerHTML = '<p class="text-xs text-slate-500">Feature importance file not available.</p>';
return;
}
mlFeatureImportancePanel.innerHTML = cleaned
.map((item) => `
<div>
<div class="flex justify-between"><span>${escapeHtml(item.feature)}</span><span>${item.importancePct.toFixed(2)}%</span></div>
<div class="h-2 bg-slate-200 rounded"><div class="h-full bg-sky-500 rounded" style="width:${Math.max(0, Math.min(100, item.importancePct))}%"></div></div>
</div>
`)
.join("");
}
function renderPlayer(player) {
const rows = playerScores
.filter((r) => r.player === player)
.sort((a, b) => {
const da = new Date(a.match_date || "1970-01-01").getTime();
const db = new Date(b.match_date || "1970-01-01").getTime();
if (da !== db) return da - db;
return toNumber(a.match_id) - toNumber(b.match_id);
});
if (rows.length === 0) return;
const latest = latestPlayerScore(rows);
const latestImpact = toNumber(latest.IM_score ?? latest.impact_score, 0);
const useMlTrend = Boolean(trendModeToggle?.checked);
const mlRows = mlScores
.filter((r) => r.player === player)
.sort((a, b) => {
const da = new Date(a.match_date || "1970-01-01").getTime();
const db = new Date(b.match_date || "1970-01-01").getTime();
if (da !== db) return da - db;
return toNumber(a.match_id) - toNumber(b.match_id);
});
const trendRows = useMlTrend && mlRows.length > 0 ? mlRows : rows;
const lastTen = trendRows.slice(-10);
trendPlayerLabel.textContent = `Player: ${player} | Trend: ${useMlTrend && mlRows.length > 0 ? "ML-Assisted" : "Rule-Based"}`;
updateGauge(latestImpact);
updatePlayerSummaryCards(player);
updateMlImpact(player, latestImpact);
buildTrend(lastTen, useMlTrend && mlRows.length > 0);
renderTrendTable(lastTen, useMlTrend && mlRows.length > 0);
computeRoleSnapshot(player, latestImpact);
computePhaseContribution(player);
computePressureAndClutch(player);
}
function getPlayerRecentSeries(player, n = 10) {
return playerScores
.filter((r) => r.player === player)
.sort((a, b) => {
const da = new Date(a.match_date || "1970-01-01").getTime();
const db = new Date(b.match_date || "1970-01-01").getTime();
if (da !== db) return da - db;
return toNumber(a.match_id) - toNumber(b.match_id);
})
.slice(-n)
.map((r) => toNumber(r.IM_score ?? r.impact_score, 0));
}
function mean(values) {
if (!values.length) return 0;
return values.reduce((a, b) => a + b, 0) / values.length;
}
function renderComparison() {
const a = compareASelect.value;
const b = compareBSelect.value;
const aSeries = getPlayerRecentSeries(a, 10);
const bSeries = getPlayerRecentSeries(b, 10);
compareAScore.textContent = mean(aSeries).toFixed(1);
compareBScore.textContent = mean(bSeries).toFixed(1);
const maxLen = Math.max(aSeries.length, bSeries.length, 10);
const labels = Array.from({ length: maxLen }, (_, i) => `${i + 1}`);
if (compareTrendChart) compareTrendChart.destroy();
compareTrendChart = new Chart(document.getElementById("compareTrendChart"), {
type: "line",
data: {
labels,