Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1596 lines (1436 loc) · 71.6 KB
/
Copy pathapp.js
File metadata and controls
1596 lines (1436 loc) · 71.6 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
import './firebase.js';
// ── STATE ─────────────────────────────────────────────────────────────────────
let teams = [], scores = {}, rankings = [], sponsorAwards = [], judges = [];
// rankings = [{ judge, ranks: { teamId: rankNumber 1–5 }, rubric: { teamId: score } }]
// sponsorAwards = [{ sponsor, award, project }]
// judges = [{ id, name, email, tableIds: [] }] tableIds = team ids assigned
const TRACKS = [
// Main Theme Tracks
{ id: 'Social Impact', label: 'Alchemy of the Earth (Social Impact)', icon: '🌿', cls: 'badge-social', main: true },
{ id: 'Health', label: 'Elixirs of Vitality (Health)', icon: '🧪', cls: 'badge-health', main: true },
{ id: 'Education', label: "The Scholar's Spellbook (Education)", icon: '📜', cls: 'badge-edu', main: true },
{ id: 'Commerce', label: 'Enchanted Commerce (Commerce)', icon: '🪙', cls: 'badge-commerce', main: true },
{ id: 'Wildcard', label: "The Rogue's Ritual (Wildcard)", icon: '✨', cls: 'badge-uiux', main: true },
// Side Tracks
{ id: 'Best Solo Hack', label: 'Best Solo Hack', icon: '🦸', cls: 'badge-solo', main: false },
{ id: 'Best Duo Hack', label: 'Best Duo Hack', icon: '👯', cls: 'badge-duo', main: false },
{ id: 'Best Beginner Hack',label: 'Best Beginner Hack',icon: '🌱', cls: 'badge-social', main: false },
{ id: 'Best AI/ML', label: 'Best AI/ML Hack', icon: '🧠', cls: 'badge-aiml', main: false },
{ id: 'Best UI/UX', label: 'Best UI/UX Hack', icon: '🎨', cls: 'badge-uiux', main: false },
{ id: 'Best Mobile App', label: 'Best Mobile Hack', icon: '📱', cls: 'badge-mobile', main: false },
];
const TMAP = {}; TRACKS.forEach(t => TMAP[t.id] = t);
const CORNER_CSE_ROOM_LABEL = 'Corner CSE Room';
function isMCACornerTeamByProject(t) {
return !!(t && (t.project || '').trim().toUpperCase() === 'MCA');
}
function isMCACornerTeam(t) {
if (!t) return false;
if (t.specialRoom === CORNER_CSE_ROOM_LABEL) return true;
return isMCACornerTeamByProject(t);
}
function getRowLabel(tableNum) {
const n = Number(tableNum);
if (!Number.isFinite(n) || n < 1) return '';
const start = Math.floor((n - 1) / 10) * 10 + 1;
return `<span style="font-size:0.68rem;color:var(--muted);margin-left:6px;white-space:nowrap">(${start}–${start + 9})</span>`;
}
// ── FIREBASE SYNC ─────────────────────────────────────────────────────────────
let _fbConnected = false;
// Bumped on every persist(); embedded in RTDB payload. Listener ignores snapshots with
// a lower _persistGen than local (out-of-order / stale echoes, e.g. empty DB after CSV import).
let _persistGen = 0;
// Firebase set() rejects undefined anywhere in the tree (e.g. team.conflict omitted as undefined).
function stripUndefinedDeep(val) {
if (val === null || typeof val !== 'object') return val;
if (Array.isArray(val)) return val.map(stripUndefinedDeep);
const out = {};
for (const k of Object.keys(val)) {
const v = val[k];
if (v === undefined) continue;
out[k] = stripUndefinedDeep(v);
}
return out;
}
function judgingPayload() {
return stripUndefinedDeep({ teams, scores, rankings, sponsorAwards, judges, _persistGen });
}
function persist() {
if (!window._fbSet) {
// Firebase not ready — save to localStorage as fallback
try {
localStorage.setItem('dh26_teams', JSON.stringify(teams));
localStorage.setItem('dh26_scores', JSON.stringify(scores));
localStorage.setItem('dh26_rankings', JSON.stringify(rankings));
localStorage.setItem('dh26_sponsors', JSON.stringify(sponsorAwards));
localStorage.setItem('dh26_judges', JSON.stringify(judges));
} catch(e) {}
const el = document.getElementById('autosave-msg');
if (el) el.textContent = '💾 saved locally';
renderTeamsTable(); updateStats();
return;
}
_persistGen++;
window._fbSet('judging', judgingPayload())
.catch(e => {
console.error('Firebase write error:', e);
_persistGen = Math.max(0, _persistGen - 1);
});
const el = document.getElementById('autosave-msg');
if (el) el.textContent = '🔄 syncing...';
}
function startFirebaseSync() {
window._fbOn('judging', val => {
const toArray = v => {
if (!v) return [];
if (Array.isArray(v)) return v.filter(Boolean);
return Object.values(v).filter(Boolean);
};
if (!val) {
// Empty database — first time setup
// Only seed judges if we don't already have local data
if (!judges.length) {
judges = DEFAULT_JUDGES.map((name, i) => ({ id: Date.now() + i, name, email: '', tableIds: [] }));
}
// Write whatever local state we have (could have just been set by CSV parse)
if (teams.length || judges.length) {
window._fbSet('judging', judgingPayload())
.catch(e => console.error(e));
}
_fbConnected = true;
const el = document.getElementById('autosave-msg');
if (el) el.textContent = '✅ connected';
renderTeamsTable(); updateStats(); refreshJudgesTab();
return;
}
// Firebase has data — only overwrite local state if this is the initial load
// (not a response to our own persist() call)
if (!_fbConnected) {
// First load — take Firebase data
teams = toArray(val.teams).map(t => ({ ...t, tracks: toArray(t.tracks) }));
scores = val.scores || {};
rankings = toArray(val.rankings).map(r => ({ ...r, ranks: r.ranks || {}, rubric: r.rubric || {} }));
sponsorAwards = toArray(val.sponsorAwards);
judges = toArray(val.judges).map(j => ({ ...j, tableIds: toArray(j.tableIds) }));
if (typeof val._persistGen === 'number') {
_persistGen = Math.max(_persistGen, val._persistGen);
}
if (!judges.length) {
judges = DEFAULT_JUDGES.map((name, i) => ({ id: Date.now() + i, name, email: '', tableIds: [] }));
window._fbSet('judging', judgingPayload()).catch(e => console.error(e));
}
_fbConnected = true;
} else {
const remoteGen = val._persistGen;
const stale = typeof remoteGen === 'number' && remoteGen < _persistGen;
if (!stale) {
teams = toArray(val.teams).map(t => ({ ...t, tracks: toArray(t.tracks) }));
scores = val.scores || {};
rankings = toArray(val.rankings).map(r => ({ ...r, ranks: r.ranks || {}, rubric: r.rubric || {} }));
sponsorAwards = toArray(val.sponsorAwards);
judges = toArray(val.judges).map(j => ({ ...j, tableIds: toArray(j.tableIds) }));
if (typeof remoteGen === 'number') {
_persistGen = Math.max(_persistGen, remoteGen);
}
}
}
setTimeout(() => {
renderTeamsTable();
updateProjectSelect();
updateStats();
refreshJudgesTab();
const activePanel = document.querySelector('.panel.active');
if (activePanel) {
const id = activePanel.id.replace('panel-', '');
if (id === 'leaderboard') refreshLeaderboard();
if (id === 'tracks') refreshTracks();
if (id === 'rankings') refreshRankingsTab();
if (id === 'judges') refreshJudgesTab();
}
}, 100);
const el = document.getElementById('autosave-msg');
if (el) el.textContent = '✅ synced ' + new Date().toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});
});
}
// ── TABS ──────────────────────────────────────────────────────────────────────
function switchTab(id, btn) {
document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.getElementById('panel-' + id).classList.add('active');
btn.classList.add('active');
if (id === 'rankings') refreshRankingsTab();
if (id === 'leaderboard') refreshLeaderboard();
if (id === 'tracks') refreshTracks();
if (id === 'judges') refreshJudgesTab();
}
// ── JUDGES & TABLE ASSIGNMENTS ────────────────────────────────────────────────
function autoAssignTableNumbers() {
if (!teams.length) return alert('Import teams first.');
const mcaTeams = teams.filter(isMCACornerTeamByProject);
const nNum = teams.length - mcaTeams.length;
const msg = mcaTeams.length
? `${teams.length} teams: ${mcaTeams.length} MCA (Hardware) → Corner CSE Room (no table #); the other ${nNum} get numbers 1–${nNum}. Continue?`
: `Auto-number all ${teams.length} teams with table numbers 1–${teams.length}?`;
if (!confirm(msg)) return;
let tableCounter = 1;
teams = teams.map(t => {
if (isMCACornerTeamByProject(t))
return { ...t, tableNum: null, specialRoom: CORNER_CSE_ROOM_LABEL };
return { ...t, tableNum: tableCounter++, specialRoom: null };
});
persist(); renderTeamsTable(); refreshJudgesTab();
}
function clearTableNumbers() {
if (!confirm('Clear all table numbers?')) return;
teams = teams.map(t => {
const o = { ...t, tableNum: null };
delete o.specialRoom;
return o;
});
persist(); renderTeamsTable(); refreshJudgesTab();
}
function clearAllJudges() {
if (!confirm('Clear ALL judges and their assignments? Cannot be undone.')) return;
judges = [];
persist(); refreshJudgesTab();
}
function loadDefaultJudges() {
if (judges.length > 0 && !confirm(`This will add the 31 DiamondHacks judges to your existing list of ${judges.length}. Continue?`)) return;
let added = 0;
DEFAULT_JUDGES.forEach(name => {
if (!judges.find(j => j.name.toLowerCase() === name.toLowerCase())) {
judges.push({ id: Date.now() + Math.random(), name, email: '', tableIds: [] });
added++;
}
});
persist(); refreshJudgesTab();
alert(`✅ Added ${added} judges (${DEFAULT_JUDGES.length - added} already existed).`);
}
function addJudge() {
const name = document.getElementById('judge-add-name').value.trim();
const email = document.getElementById('judge-add-email').value.trim();
if (!name) return alert('Please enter a judge name.');
if (judges.find(j => j.name.toLowerCase() === name.toLowerCase())) return alert(`${name} is already in the list.`);
judges.push({ id: Date.now(), name, email, tableIds: [] });
document.getElementById('judge-add-name').value = '';
document.getElementById('judge-add-email').value = '';
persist(); refreshJudgesTab();
}
function importJudgeList() {
const area = document.getElementById('judge-paste-area');
const btn = document.getElementById('judge-paste-btn');
area.style.display = area.style.display === 'none' ? 'block' : 'none';
btn.style.display = btn.style.display === 'none' ? 'block' : 'none';
}
function confirmJudgePaste() {
const lines = document.getElementById('judge-paste-area').value.split('\n').map(l => l.trim()).filter(Boolean);
if (!lines.length) return alert('No names found.');
let added = 0;
lines.forEach(name => {
if (!judges.find(j => j.name.toLowerCase() === name.toLowerCase())) {
judges.push({ id: Date.now() + Math.random(), name, email: '', tableIds: [] });
added++;
}
});
document.getElementById('judge-paste-area').value = '';
document.getElementById('judge-paste-area').style.display = 'none';
document.getElementById('judge-paste-btn').style.display = 'none';
persist(); refreshJudgesTab();
alert(`✅ Added ${added} judges (${lines.length - added} duplicates skipped).`);
}
function removeJudge(idx) {
idx = parseInt(idx);
if (isNaN(idx) || idx < 0 || idx >= judges.length) return;
const j = judges[idx];
if (!confirm('Remove ' + j.name + ' from the judge roster?')) return;
judges.splice(idx, 1);
persist(); refreshJudgesTab();
}
window.removeJudge = removeJudge;
window.doRemoveJudge = function(idx) {
idx = parseInt(idx);
if (isNaN(idx) || idx < 0 || idx >= judges.length) return;
const j = judges[idx];
if (!confirm('Remove ' + j.name + ' from the judge roster?')) return;
judges.splice(idx, 1);
persist(); refreshJudgesTab();
};
window.doAbsent = function(idx) {
idx = parseInt(idx);
if (isNaN(idx) || idx < 0 || idx >= judges.length) return;
markAbsent(idx);
};
window.doReinstate = function(idx) {
idx = parseInt(idx);
if (isNaN(idx) || idx < 0 || idx >= judges.length) return;
judges[idx].absent = false;
persist(); refreshJudgesTab();
};
function fisherYatesShuffle(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function judgeWithFewestAssignments() {
const active = judges.filter(j => !j.absent);
if (!active.length) return null;
let best = active[0];
let minL = best.tableIds.length;
active.forEach(j => {
if (j.tableIds.length < minL) {
minL = j.tableIds.length;
best = j;
}
});
return best;
}
function autoAssignJudges() {
if (!judges.length) return alert('Add judges first.');
const assignable = teams.filter(t =>
(t.tableNum != null && t.tableNum !== '') || isMCACornerTeam(t)
);
if (!assignable.length) {
return alert('Assign table numbers first (Step 1 — Auto-Number All Teams). MCA uses Corner CSE Room without a number.');
}
if (!confirm(`Auto-assign ${assignable.length} project(s) to ${judges.length} judges using a random shuffle.\nMCA (Corner CSE Room) goes to the judge with the fewest tables.\n\nThis clears existing assignments. Continue?`)) return;
judges = judges.map(j => ({ ...j, tableIds: [] }));
const mcaList = assignable.filter(isMCACornerTeam);
const numbered = assignable.filter(t => !isMCACornerTeam(t));
const shuffled = fisherYatesShuffle(numbered);
shuffled.forEach((team, i) => {
judges[i % judges.length].tableIds.push(team.id);
});
const mcaNotifyNames = [];
mcaList.forEach(team => {
const j = judgeWithFewestAssignments();
if (j) {
j.tableIds.push(team.id);
mcaNotifyNames.push(j.name);
}
});
persist(); refreshJudgesTab();
const lo = Math.floor(assignable.length / judges.length);
const hi = Math.ceil(assignable.length / judges.length);
let msg = `✅ Tables assigned randomly! Each judge has about ${lo}–${hi} assignment(s).`;
if (mcaList.length && mcaNotifyNames.length) {
const who = [...new Set(mcaNotifyNames)].join(', ');
msg += `\n\n📍 Corner CSE Room (MCA Hardware) → ${who}\nPlease notify them — they cover the hardware hack.`;
} else if (mcaList.length && !mcaNotifyNames.length) {
msg += '\n\n⚠️ MCA could not be assigned (no active judges).';
}
alert(msg);
}
function markAbsent(judgeIdx) {
judgeIdx = parseInt(judgeIdx);
if (isNaN(judgeIdx) || judgeIdx < 0 || judgeIdx >= judges.length) return;
const absent = judges[judgeIdx];
if (!absent.tableIds.length) return alert(absent.name + ' has no tables assigned.');
const available = judges.filter((j, i) => i !== judgeIdx && !j.absent);
if (!available.length) return alert('No other judges available to redistribute to.');
if (!confirm('Mark ' + absent.name + ' as absent and redistribute their ' + absent.tableIds.length + ' tables to other judges?')) return;
absent.absent = true;
const reassigned = [];
absent.tableIds.forEach((tid, i) => {
const target = available[i % available.length];
target.tableIds.push(tid);
const team = teams.find(t => String(t.id) === String(tid));
reassigned.push({ table: team ? assignmentTableLabelForTeam(team) : '?', project: team?.project || '?', to: target.name });
});
absent.tableIds = [];
persist(); refreshJudgesTab();
const summary = reassigned.map(r => ' ' + r.table + ' (' + r.project + ') → ' + r.to).join('\n');
alert('✅ Redistributed ' + reassigned.length + ' tables from ' + absent.name + ':\n\n' + summary + '\n\nPlease notify affected judges of their updated assignments.');
}
window.markAbsent = markAbsent;
function reinstateJudge(judgeIdx) {
judgeIdx = parseInt(judgeIdx);
if (isNaN(judgeIdx) || judgeIdx < 0 || judgeIdx >= judges.length) return;
judges[judgeIdx].absent = false;
persist(); refreshJudgesTab();
}
window.reinstateJudge = reinstateJudge;
function assignmentTableLabelForTeam(team) {
if (!team) return '?';
if (team.specialRoom) return team.specialRoom;
if (isMCACornerTeamByProject(team)) return CORNER_CSE_ROOM_LABEL;
const tn = team.tableNum;
if (tn != null && String(tn).trim().toUpperCase() === 'MCA') return CORNER_CSE_ROOM_LABEL;
if (tn != null && tn !== '') return String(tn);
return '?';
}
function compareAssignmentTableLabels(a, b) {
const rank = (l) => {
if (l === CORNER_CSE_ROOM_LABEL) return { g: 3, n: 0 };
if (l === '?') return { g: 2, n: 0 };
const num = Number(l);
if (!Number.isNaN(num) && String(num) === String(l).trim()) return { g: 0, n: num };
return { g: 1, s: String(l) };
};
const ra = rank(a), rb = rank(b);
if (ra.g !== rb.g) return ra.g - rb.g;
if (ra.g === 0) return ra.n - rb.n;
if (ra.g === 1) return ra.s.localeCompare(rb.s);
return 0;
}
/** Labels for CSV/print/judges tab: comma-separated, sorted (numeric table #s ascending; Corner MCA after numbers). */
function judgeAssignedTableLabels(judge) {
const labels = judge.tableIds.map(tid => {
const t = teams.find(tm => String(tm.id) === String(tid));
if (!t) return '?';
// Prefer human-readable label (table # or Corner CSE Room for MCA); plain tableNum||'?' would hide Corner.
return assignmentTableLabelForTeam(t);
});
labels.sort(compareAssignmentTableLabels);
return labels;
}
function csvEscapeCell(val) {
const s = String(val ?? '');
if (/[",\r\n]/.test(s)) return '"' + s.replace(/"/g, '""') + '"';
return s;
}
function exportJudgeAssignments() {
if (!judges.length) return alert('No judges to export.');
const rows = [['Judge Name', 'Assigned Tables']];
judges.forEach(j => {
rows.push([j.name, judgeAssignedTableLabels(j).join(', ')]);
});
const csv = rows.map(r => r.map(csvEscapeCell).join(',')).join('\n');
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([csv], {type:'text/csv'}));
a.download = 'judge-assignments.csv'; a.click();
}
function escapePrintDoc(s) {
return String(s ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
function printJudgeAssignmentSheet() {
if (!judges.length) return alert('No judges to print.');
const when = new Date().toLocaleString(undefined, { dateStyle: 'long', timeStyle: 'short' });
const bodyRows = judges.map(j => {
const tables = escapePrintDoc(judgeAssignedTableLabels(j).join(', '));
return `<tr><td>${escapePrintDoc(j.name)}</td><td>${tables}</td></tr>`;
}).join('');
const html = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Judge Assignments — Print</title>
<style>
* { box-sizing: border-box; }
body { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; margin: 0; padding: 24px; color: #000; background: #fff; }
.no-print { font-size: 10pt; color: #444; margin-bottom: 16px; }
.doc-title { font-size: 14pt; font-weight: bold; margin: 0 0 6px 0; }
.doc-meta { font-size: 10pt; margin: 0 0 20px 0; color: #222; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; }
th, td { border: 1px solid #000; padding: 10px 12px; text-align: left; vertical-align: top; word-wrap: break-word; }
th { background: #f0f0f0; font-weight: bold; }
tr { page-break-inside: avoid; }
@media print {
.no-print { display: none !important; }
body { padding: 12pt; margin: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
table { font-size: 12pt; }
}
</style></head><body>
<p class="no-print">If the print dialog does not open, use <strong>File → Print</strong>. You can close this tab after printing.</p>
<h1 class="doc-title">DiamondHacks 2026 — Judge Assignments</h1>
<p class="doc-meta">${escapePrintDoc(when)}</p>
<table>
<thead><tr><th style="width:32%">Judge Name</th><th>Assigned Tables</th></tr></thead>
<tbody>${bodyRows}</tbody>
</table>
<script>
(function(){
function doPrint() {
window.focus();
window.print();
}
if (document.readyState === 'complete') setTimeout(doPrint, 120);
else window.addEventListener('load', function() { setTimeout(doPrint, 120); });
})();
<\/script>
</body></html>`;
const w = window.open('', '_blank');
if (!w) return alert('Pop-up blocked — allow pop-ups for this site to print.');
w.document.write(html);
w.document.close();
}
window.printJudgeAssignmentSheet = printJudgeAssignmentSheet;
function refreshJudgesTab() {
document.getElementById('judge-count').textContent = `(${judges.length})`;
// Update assign stats
const assigned = judges.filter(j => j.tableIds.length > 0).length;
const totalAssigned = judges.reduce((s, j) => s + j.tableIds.length, 0);
document.getElementById('assign-stats').textContent =
judges.length ? `${assigned}/${judges.length} judges assigned · ${totalAssigned} table assignments` : '';
// Render judge list
const el = document.getElementById('judges-list');
if (!judges.length) {
el.innerHTML = '<div class="empty-state"><div class="empty-icon">👤</div><p>No judges added yet.</p></div>';
} else {
el.innerHTML = `<div class="table-wrap"><table>
<thead><tr><th>Judge</th><th>Email</th><th>Status</th><th>Tables</th><th>Projects Assigned</th><th></th></tr></thead>
<tbody>${judges.map((j, i) => {
const tableNums = judgeAssignedTableLabels(j).join(', ');
const statusBadge = j.absent
? `<span class="badge badge-health">ABSENT</span>`
: `<span class="badge badge-scored">Active</span>`;
return `<tr style="${j.absent ? 'opacity:0.5' : ''}">
<td style="font-weight:500">${j.name}</td>
<td style="color:var(--muted);font-size:0.82rem">${j.email||'—'}</td>
<td>${statusBadge}</td>
<td style="font-family:'DM Mono',monospace;font-size:0.8rem">${tableNums || '—'}</td>
<td style="color:var(--muted);font-size:0.82rem">${j.tableIds.length} projects</td>
<td style="display:flex;gap:6px;flex-wrap:wrap">
${j.absent
? `<button class="btn btn-secondary" style="padding:4px 10px;font-size:0.72rem" onclick="doReinstate(${i})">↩ Reinstate</button>`
: `<button class="btn btn-danger" style="padding:4px 10px;font-size:0.72rem" onclick="doAbsent(${i})">⚠️ Absent</button>`}
<button class="btn btn-danger" style="padding:4px 10px;font-size:0.72rem" onclick="doRemoveJudge(${i})">✕</button>
</td>
</tr>`;
}).join('')}</tbody>
</table></div>`;
}
// Render table assignments
const tbody = document.getElementById('table-assignments-tbody');
if (!tbody) return;
const numbered = teams.filter(t => (t.tableNum != null && t.tableNum !== '') || t.specialRoom)
.sort((a, b) => {
const am = isMCACornerTeam(a) ? 1 : 0, bm = isMCACornerTeam(b) ? 1 : 0;
if (am !== bm) return am - bm;
return (Number(a.tableNum) || 0) - (Number(b.tableNum) || 0);
});
if (!numbered.length) {
tbody.innerHTML = '<tr><td colspan="5"><div class="empty-state"><div class="empty-icon">🗂️</div><p>No table numbers assigned yet.</p></div></td></tr>';
return;
}
tbody.innerHTML = numbered.map(t => {
const assignedJudges = judges.filter(j => j.tableIds.some(tid => String(tid) === String(t.id)));
const judgeNames = assignedJudges.length
? assignedJudges.map(j => `<span class="badge ${j.absent ? 'badge-health' : 'badge-scored'}">${j.name}${j.absent ? ' (absent)' : ''}</span>`).join(' ')
: '<span style="color:var(--muted);font-size:0.8rem">Unassigned</span>';
const badges = t.tracks.map(trackBadge).join('') || '—';
return `<tr>
<td style="font-family:'DM Mono',monospace;font-weight:600;color:var(--accent)">${assignmentTableLabelForTeam(t)}</td>
<td style="font-weight:500">${t.project}</td>
<td style="color:var(--muted);font-size:0.85rem">${t.submitter}</td>
<td>${badges}</td>
<td>${judgeNames}</td>
</tr>`;
}).join('');
}
// ── RANKINGS ──────────────────────────────────────────────────────────────────
function refreshRankingsTab() {
renderRankInputs();
renderRankingsList();
renderGlobalScores();
}
function renderRankInputs() {
const container = document.getElementById('rank-inputs');
if (!teams.length) {
container.innerHTML = '<div style="color:var(--muted);font-size:0.85rem;font-style:italic">Import teams first to see the ranking inputs.</div>';
return;
}
const judgeName = document.getElementById('rank-judge-name').value.trim();
const existing = judgeName ? rankings.find(r => r.judge === judgeName) : null;
container.innerHTML = teams.map(t => {
const rankVal = existing ? (existing.ranks[t.id] ?? '') : '';
const rubricVal = existing ? (existing.rubric?.[t.id] ?? '') : '';
return `<div style="display:grid;grid-template-columns:1fr 70px 70px;align-items:center;gap:8px;padding:7px 10px;background:var(--surface2);border:1px solid var(--border);border-radius:8px">
<span style="font-size:0.82rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${t.project}">${t.project}</span>
<div style="display:flex;flex-direction:column;gap:2px;align-items:center">
<span style="font-size:0.62rem;color:var(--muted);text-transform:uppercase;letter-spacing:0.05em">Rank</span>
<input type="number" min="1" max="5" placeholder="1–5" data-teamid="${t.id}" data-type="rank"
value="${rankVal}"
style="width:60px;font-family:'DM Mono',monospace;text-align:center;padding:5px 4px;font-size:0.85rem"
oninput="highlightDuplicateRanks()">
</div>
<div style="display:flex;flex-direction:column;gap:2px;align-items:center">
<span style="font-size:0.62rem;color:var(--muted);text-transform:uppercase;letter-spacing:0.05em">Score</span>
<input type="number" min="0" max="40" placeholder="/40" data-teamid="${t.id}" data-type="rubric"
value="${rubricVal}"
style="width:60px;font-family:'DM Mono',monospace;text-align:center;padding:5px 4px;font-size:0.85rem;border-color:rgba(108,99,255,0.3)">
</div>
</div>`;
}).join('');
}
function highlightDuplicateRanks() {
const inputs = document.querySelectorAll('#rank-inputs input[data-type="rank"]');
const seen = {}, dupes = new Set();
inputs.forEach(inp => {
const v = inp.value.trim();
if (!v) return;
if (seen[v]) dupes.add(v);
seen[v] = true;
});
inputs.forEach(inp => {
inp.style.borderColor = (inp.value && dupes.has(inp.value)) ? 'var(--accent2)' : '';
});
}
function saveRankings() {
const judgeName = document.getElementById('rank-judge-name').value.trim();
if (!judgeName) return alert('Please enter the judge name.');
const rankInputs = document.querySelectorAll('#rank-inputs input[data-type="rank"]');
const rubricInputs = document.querySelectorAll('#rank-inputs input[data-type="rubric"]');
const ranks = {};
const rubric = {};
const usedRanks = new Set();
let hasAny = false;
// Partial rankings OK: ≥1 project with a rank; each rank integer 1–5; no duplicate rank numbers for this judge.
for (const inp of rankInputs) {
const v = inp.value.trim();
if (!v) continue;
const rank = Number(v);
if (!Number.isInteger(rank) || rank < 1 || rank > 5) {
return alert(`Rank "${v}" must be a whole number between 1 and 5.`);
}
if (usedRanks.has(rank)) return alert(`Rank ${rank} is used more than once. Each rank number can only be used once.`);
usedRanks.add(rank);
ranks[inp.getAttribute('data-teamid')] = rank;
hasAny = true;
}
for (const inp of rubricInputs) {
const v = inp.value.trim();
if (!v) continue;
const score = parseFloat(v);
if (!isNaN(score)) rubric[inp.getAttribute('data-teamid')] = score;
}
if (!hasAny) return alert('Please enter at least one rank.');
const existingIdx = rankings.findIndex(r => r.judge === judgeName);
const entry = { judge: judgeName, ranks, rubric, _savedAt: Date.now() };
if (existingIdx >= 0) rankings[existingIdx] = entry;
else rankings.push(entry);
persist();
renderTeamsTable();
renderRankingsList();
renderGlobalScores();
refreshTracks();
document.getElementById('rank-judge-name').value = '';
renderRankInputs();
alert('✅ Rankings saved for ' + judgeName + '!');
}
function deleteRanking(idx) {
if (!confirm('Remove rankings for ' + rankings[idx].judge + '?')) return;
rankings.splice(idx, 1);
persist();
renderRankingsList();
renderGlobalScores();
refreshTracks();
}
window.deleteRanking = deleteRanking;
function loadJudgeRankings() {
// Called when judge name field changes — pre-fills rank inputs if judge already has data
renderRankInputs();
}
function renderRankingsList() {
const el = document.getElementById('rankings-list');
if (!rankings.length) {
el.innerHTML = '<div class="empty-state"><div class="empty-icon">🏅</div><p>No rankings entered yet.</p></div>';
return;
}
el.innerHTML = `<div class="table-wrap"><table>
<thead><tr><th>Judge</th><th>Projects Ranked</th><th>Rankings</th><th></th></tr></thead>
<tbody>${rankings.map((r, i) => {
const ranked = Object.entries(r.ranks).sort((a,b) => a[1]-b[1]);
const summary = ranked.map(([tid, rank]) => {
const team = teams.find(t => String(t.id) === String(tid));
return `<span style="font-size:0.75rem;color:var(--muted)">#${rank} <span style="color:var(--text)">${team ? team.project : '?'}</span></span>`;
}).join(' · ');
return `<tr>
<td style="font-weight:500">${r.judge}</td>
<td style="font-family:'DM Mono',monospace;color:var(--muted)">${ranked.length}</td>
<td style="font-size:0.82rem;line-height:1.8">${summary}</td>
<td><button class="btn btn-secondary" style="padding:5px 10px;font-size:0.75rem" onclick="editRanking(${i})">✏️ Edit</button>
<button class="btn btn-danger" style="padding:5px 10px;font-size:0.75rem" onclick="deleteRanking(${i})">✕</button></td>
</tr>`;
}).join('')}</tbody>
</table></div>`;
}
function sumRubricPointsForTeam(teamId) {
let s = 0;
const want = String(teamId);
rankings.forEach(r => {
const rub = r.rubric || {};
for (const k of Object.keys(rub)) {
if (String(k) !== want) continue;
const v = rub[k];
if (typeof v === 'number' && !Number.isNaN(v)) s += v;
}
});
return s;
}
function calcGlobalScores() {
const POINTS = { 1: 5, 2: 4, 3: 3, 4: 2, 5: 1 };
const teamPoints = {};
const teamCounts = {};
rankings.forEach(r => {
Object.entries(r.ranks || {}).forEach(([tid, rank]) => {
const rk = parseInt(rank, 10);
const pts = POINTS[rk] || 0;
teamPoints[tid] = (teamPoints[tid] || 0) + pts;
teamCounts[tid] = (teamCounts[tid] || 0) + 1;
});
});
return Object.entries(teamPoints).map(([tid, pts]) => {
const team = teams.find(t => String(t.id) === String(tid));
return { tid, team, avg: pts, count: teamCounts[tid] || 0 };
}).sort((a, b) => {
if (b.avg !== a.avg) return b.avg - a.avg;
return sumRubricPointsForTeam(b.tid) - sumRubricPointsForTeam(a.tid);
});
}
function renderGlobalScores() {
const el = document.getElementById('global-scores-content');
const results = calcGlobalScores();
if (!results.length) {
el.innerHTML = '<div class="empty-state"><div class="empty-icon">📊</div><p>Enter rankings above to see total points.</p></div>';
return;
}
const rc = i => i===0?'rank-1':i===1?'rank-2':i===2?'rank-3':'';
el.innerHTML = `<div class="table-wrap"><table>
<thead><tr><th>Rank</th><th>Project</th><th>Submitter</th><th>Points</th><th>Judges who ranked</th></tr></thead>
<tbody>${results.map((r, i) => `<tr>
<td><span class="rank-num ${rc(i)}">${i+1}</span></td>
<td style="font-weight:500">${r.team ? r.team.project : '(unknown)'}</td>
<td style="color:var(--muted)">${r.team ? r.team.submitter : '—'}</td>
<td><span class="score-pill">${Math.round(r.avg)} pts</span></td>
<td style="font-family:'DM Mono',monospace;color:var(--muted)">${r.count}</td>
</tr>`).join('')}</tbody>
</table></div>`;
}
// ── CSV PARSER (proper RFC 4180 — handles quoted multiline fields) ─────────────
function parseCSVFull(text) {
const rows = [];
let row = [], field = '', inQ = false;
for (let i = 0; i < text.length; i++) {
const c = text[i], nx = text[i+1];
if (inQ) {
if (c==='"' && nx==='"') { field+='"'; i++; }
else if (c==='"') { inQ=false; }
else { field+=c; }
} else {
if (c==='"') { inQ=true; }
else if (c===',') { row.push(field); field=''; }
else if (c==='\n' || (c==='\r' && nx==='\n')) {
if (c==='\r') i++;
row.push(field); field='';
if (row.some(x => x.trim())) rows.push(row);
row=[];
} else { field+=c; }
}
}
if (field || row.length) { row.push(field); if (row.some(x=>x.trim())) rows.push(row); }
return rows;
}
function mapTrack(raw) {
const cleaned = raw.replace(/^Track\s*\d+[:\-]\s*/i, '').trim();
if (/social|sustain|environ|alchemy|earth/i.test(cleaned)) return 'Social Impact';
if (/health|medical|patient|hospital|elixir|vital/i.test(cleaned)) return 'Health';
if (/educ|learn|school|study|scholar|spellbook/i.test(cleaned)) return 'Education';
if (/commerc|financ|business|enchanted|shop|ecomm/i.test(cleaned)) return 'Commerce';
if (/wildcard|wild.card|rogue|ritual|anomal/i.test(cleaned)) return 'Wildcard';
if (/beginner|first.time|starter/i.test(cleaned)) return 'Best Beginner Hack';
if (/solo/i.test(cleaned)) return 'Best Solo Hack';
if (/duo/i.test(cleaned)) return 'Best Duo Hack';
if (/ui.?ux|design|interface/i.test(cleaned)) return 'Best UI/UX';
if (/\bai\b|\bml\b|machine.?learn|gemini|gpt|llm/i.test(cleaned)) return 'Best AI/ML';
if (/mobile|ios|android/i.test(cleaned)) return 'Best Mobile App';
return null;
}
function setCsvParseDebug(lines) {
const text = Array.isArray(lines) ? lines.join('\n') : String(lines);
const el = document.getElementById('csv-parse-debug');
const wrap = document.getElementById('csv-parse-debug-wrap');
if (el) el.textContent = text;
if (wrap) wrap.open = true;
console.warn('[CSV parse diagnostics]\n' + text);
}
function parseDevpostCSV() {
const lines = [];
const log = (s) => { lines.push(s); };
try {
log('— ' + new Date().toISOString() + ' —');
log('1) parseDevpostCSV() was called (button / upload handler ran).');
const ta = document.getElementById('csv-input');
if (!ta) {
log('FAIL: #csv-input not found in the DOM.');
setCsvParseDebug(lines);
alert('Internal error: CSV textarea missing. Check the diagnostics box below.');
return;
}
const raw = ta.value.trim();
log('2) Textarea length (trimmed): ' + raw.length + ' chars.');
if (!raw) {
log('STOP: Empty textarea — paste CSV text or use file upload.');
setCsvParseDebug(lines);
alert('Please paste or upload a CSV file first.');
return;
}
const preview = raw.slice(0, 200).replace(/\n/g, '\\n');
log('3) First ~200 chars: ' + preview + (raw.length > 200 ? '…' : ''));
const rows = parseCSVFull(raw);
log('4) parseCSVFull → ' + rows.length + ' row(s).');
if (rows.length < 2) {
log('STOP: Need a header row + at least one data row.');
setCsvParseDebug(lines);
alert('Could not parse CSV — only ' + rows.length + ' row(s) found. Make sure you uploaded the full file.');
return;
}
const headers = rows[0].map(h => h.trim().toLowerCase());
log('5) Header count: ' + headers.length + '. Columns (first 25):');
log(' ' + headers.slice(0, 25).map((h, i) => '[' + i + '] ' + JSON.stringify(h)).join(' | '));
if (headers.length > 25) log(' … +' + (headers.length - 25) + ' more');
const col = (...names) => names.reduce((f,n) => f!==-1 ? f : headers.findIndex(h => h.includes(n)), -1);
const titleIdx = col('project title', 'submission title', 'project name', 'title');
const tableIdx = col('table number', 'table #', 'table num');
const mainTrackIdx = col('please select a main track', 'select a main track', 'please select a track', 'select a track');
const sponsorTrackIdx = col('select a sponsor track', 'sponsor track', 'sponsor / special prizes', 'sponsor/special');
const sideTrackIdx = col('select a side track', 'side track');
const prizesIdx = col('opt-in prizes', 'prizes');
const firstIdx = col('submitter first name', 'first name');
const lastIdx = col('submitter last name', 'last name');
const sizeIdx = col('how many people', 'team size', 'members');
log('6) Column indices → title:' + titleIdx + ' table:' + tableIdx + ' mainTrack:' + mainTrackIdx +
' sponsor:' + sponsorTrackIdx + ' side:' + sideTrackIdx + ' prizes:' + prizesIdx +
' first:' + firstIdx + ' last:' + lastIdx + ' size:' + sizeIdx);
if (titleIdx === -1) {
log('STOP: No column matched "project title" / "title". Your export may use a different header name.');
log(' Tip: Devpost sometimes uses "Submission Title" or similar — we can add that match if you confirm the exact header.');
setCsvParseDebug(lines);
alert('Could not find "Project Title" column. Is this a Devpost CSV? Open Parse diagnostics below for headers.');
return;
}
const SKIP = new Set(['']);
const added = [];
const conflicts = [];
let skippedRows = 0;
for (let i = 1; i < rows.length; i++) {
const r = rows[i];
const title = (r[titleIdx] || '').trim();
if (!title || SKIP.has(title.toLowerCase())) {
skippedRows++;
continue;
}
const rawMain = (r[mainTrackIdx] || '').trim();
const rawSponsor = sponsorTrackIdx !== -1 ? (r[sponsorTrackIdx] || '').trim() : '';
const rawSide = sideTrackIdx !== -1 ? (r[sideTrackIdx] || '').trim() : '';
const rawPrizes = (r[prizesIdx] || '').trim();
const first = (r[firstIdx] || '').trim();
const last = (r[lastIdx] || '').trim();
const size = parseInt(r[sizeIdx] || '0') || 0;
const tableNum = tableIdx !== -1 ? (parseInt(r[tableIdx]) || null) : null;
const tset = new Set();
const m1 = mapTrack(rawMain); if (m1) tset.add(m1);
if (rawSponsor) rawSponsor.split(',').forEach(p => {
const m = mapTrack(p.trim()); if (m) tset.add(m);
});
if (rawSide) rawSide.split(',').forEach(p => {
const m = mapTrack(p.trim()); if (m) tset.add(m);
});
if (rawPrizes && !rawSponsor && !rawSide) {
rawPrizes.split(',').forEach(p => {
p = p.trim();
if (p.toUpperCase().startsWith('MLH')) return;
const m = mapTrack(p); if (m) tset.add(m);
});
}
if (size === 1 && !tset.has('Best Solo Hack')) tset.add('Best Solo Hack');
else if (size === 2 && !tset.has('Best Duo Hack')) tset.add('Best Duo Hack');
const hasSolo = tset.has('Best Solo Hack');
const hasDuo = tset.has('Best Duo Hack');
const conflict = hasSolo && hasDuo;
if (conflict) conflicts.push(title);
const isMCA = title.trim().toUpperCase() === 'MCA';
const row = {
id: Date.now() + i,
project: title,
submitter: [first, last].filter(Boolean).join(' ') || 'Unknown',
tracks: [...tset],
tableNum: isMCA ? null : tableNum,
};
if (isMCA) row.specialRoom = CORNER_CSE_ROOM_LABEL;
if (conflict) row.conflict = true;
added.push(row);
}
log('7) Data rows skipped (empty title): ' + skippedRows + '. Projects parsed: ' + added.length + '.');
if (!added.length) {
log('STOP: No rows produced a project title. Check title column and that rows are not all blank.');
if (rows[1]) log('8) Sample row 1 cells (first 8): ' + rows[1].slice(0, 8).map(c => JSON.stringify((c||'').slice(0, 40))).join(' | '));
setCsvParseDebug(lines);
alert('No valid projects found. Open Parse diagnostics below for details.');
return;
}
teams = added;
scores = {};
rankings = [];
const hasTableNums = added.some(t => t.tableNum != null || t.specialRoom);
log('9) Assigned teams.length = ' + teams.length + ' (in memory).');
log('10) Firebase: _fbSet ' + (typeof window._fbSet === 'function' ? 'available' : 'NOT READY (will use localStorage only in persist)') + '.');
log(' _persistGen before persist: ' + (typeof _persistGen !== 'undefined' ? _persistGen : '(n/a)'));
persist();
log(' _persistGen after persist: ' + (typeof _persistGen !== 'undefined' ? _persistGen : '(n/a)'));
const tbody = document.getElementById('teams-tbody');
log('11) #teams-tbody exists: ' + !!tbody + '. Calling renderTeamsTable()…');
renderTeamsTable();
updateProjectSelect();
updateStats();
log('12) After render, stat-teams text: "' + (document.getElementById('stat-teams') && document.getElementById('stat-teams').textContent) + '".');
log('DONE: Success — if the table is still empty, check the Teams tab / scroll; or a script error after this line in console.');
setCsvParseDebug(lines);
let msg = '✅ Imported ' + added.length + ' projects!';
if (hasTableNums) msg += '\n📋 Table numbers / room info imported from CSV.';
if (conflicts.length) msg += '\n\n⚠️ Solo+Duo conflict detected on ' + conflicts.length + ' project(s):\n' + conflicts.join('\n') + '\n\nThese teams are flagged in red — remove them from one track manually.';
alert(msg);
} catch (err) {
log('EXCEPTION: ' + (err && err.message));
log((err && err.stack) || '');
setCsvParseDebug(lines);
alert('CSV parse crashed — see "Parse diagnostics" below and browser console (F12). Error: ' + (err && err.message));
}
}
window.parseDevpostCSV = parseDevpostCSV;
// ── MANUAL ADD ────────────────────────────────────────────────────────────────
function addManualTeam() {
const project = document.getElementById('manual-project').value.trim();