-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp-code-class.js
More file actions
830 lines (727 loc) · 25.2 KB
/
app-code-class.js
File metadata and controls
830 lines (727 loc) · 25.2 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
// app-code-class.js
// Code_Class integration for competitive programming platforms
// NOTE: firebase is initialized via firebase.js on this page.
const ccAuth = firebase.auth();
const CC_SERVER_URL = "http://localhost:4000";
// ----- Local helpers for usernames & logs -----
const CC_USERNAMES_KEY = "devtrackr_code_class_usernames";
const LOGS_KEY = "devtrackr_logs";
function ccGetStoredUsernames() {
try {
const raw = localStorage.getItem(CC_USERNAMES_KEY);
return raw ? JSON.parse(raw) : {};
} catch (e) {
console.error("Failed to read Code_Class usernames", e);
return {};
}
}
function ccSaveStoredUsernames(usernames) {
try {
localStorage.setItem(CC_USERNAMES_KEY, JSON.stringify(usernames));
} catch (e) {
console.error("Failed to save Code_Class usernames", e);
}
}
function ccGetLogs() {
try {
const raw = localStorage.getItem(LOGS_KEY);
return raw ? JSON.parse(raw) : [];
} catch (e) {
console.error("Failed to read logs", e);
return [];
}
}
function ccSaveLogs(allLogs) {
try {
localStorage.setItem(LOGS_KEY, JSON.stringify(allLogs));
} catch (e) {
console.error("Failed to save logs", e);
}
}
function ccAddAutoLogIfNeeded(userId, logPayload) {
const allLogs = ccGetLogs();
const today = new Date().toISOString().slice(0, 10);
const exists = allLogs.some(
(l) =>
l.userId === userId &&
l.date === today &&
l.title === logPayload.title &&
l.tag === "DSA"
);
if (exists) return;
allLogs.push({
userId,
title: logPayload.title,
desc: logPayload.desc,
tag: "DSA",
date: today,
createdAt: new Date().toISOString(),
});
ccSaveLogs(allLogs);
}
// ----- Chart holders -----
let ccDifficultyCharts = {
leetcode: null,
codechef: null,
gfg: null,
hackerearth: null,
};
let ccWeeklyChartInstance = null;
function ccRenderDifficultyChart(platform, canvasId, dist) {
const el = document.getElementById(canvasId);
if (!el) return;
const ctx = el.getContext("2d");
if (ccDifficultyCharts[platform]) {
ccDifficultyCharts[platform].destroy();
}
const total = (dist.easy || 0) + (dist.medium || 0) + (dist.hard || 0);
const toPercent = (v) => (total ? Math.round((v / total) * 100) : 0);
ccDifficultyCharts[platform] = new Chart(ctx, {
type: "doughnut",
data: {
labels: ["Easy", "Medium", "Hard"],
datasets: [
{
data: [
toPercent(dist.easy || 0),
toPercent(dist.medium || 0),
toPercent(dist.hard || 0),
],
backgroundColor: [
"rgba(34, 197, 94, 0.9)",
"rgba(249, 115, 22, 0.9)",
"rgba(239, 68, 68, 0.9)",
],
borderWidth: 0,
},
],
},
options: {
plugins: {
legend: {
display: false,
},
},
cutout: "65%",
},
});
}
function ccRenderWeeklyChart(byDate) {
const canvas = document.getElementById("cc-weekly-chart");
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (ccWeeklyChartInstance) {
ccWeeklyChartInstance.destroy();
}
const days = [];
const today = new Date();
for (let i = 6; i >= 0; i--) {
const d = new Date(today);
d.setDate(d.getDate() - i);
const key = d.toISOString().slice(0, 10);
days.push(key);
}
const labels = days.map((d) => d.slice(5)); // MM-DD
const values = days.map((d) => byDate[d] || 0);
ccWeeklyChartInstance = new Chart(ctx, {
type: "bar",
data: {
labels,
datasets: [
{
label: "Problems per day",
data: values,
backgroundColor: "rgba(56, 189, 248, 0.9)",
borderRadius: 4,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
},
scales: {
x: {
ticks: { color: "#9ca3af" },
grid: { display: false },
},
y: {
ticks: { color: "#9ca3af" },
grid: { color: "rgba(31, 41, 55, 0.7)" },
},
},
},
});
}
// ----- Portfolio derived from local DevTrackr logs (no external APIs) -----
function ccBuildPlatformStatsFromLogs(logs) {
const platforms = ["leetcode", "codechef", "gfg", "hackerearth"];
const base = {};
platforms.forEach((p) => {
base[p] = {
platform:
p === "gfg"
? "GeeksforGeeks"
: p === "hackerearth"
? "HackerEarth"
: p.charAt(0).toUpperCase() + p.slice(1),
key: p,
totalSolved: 0,
difficulties: { easy: 0, medium: 0, hard: 0 },
categories: [],
rankRating: null,
lastProblem: null,
submissionsByDate: {},
};
});
function detectPlatform(text) {
const t = text.toLowerCase();
if (t.includes("leetcode")) return "leetcode";
if (t.includes("codechef")) return "codechef";
if (t.includes("geeksforgeeks") || t.includes("gfg")) return "gfg";
if (t.includes("hackerearth")) return "hackerearth";
return null;
}
function detectDifficulty(text) {
const t = text.toLowerCase();
if (t.includes("easy")) return "easy";
if (t.includes("medium")) return "medium";
if (t.includes("hard")) return "hard";
return null;
}
logs.forEach((log) => {
const combined = `${log.title || ""} ${log.desc || ""}`;
const platformKey = detectPlatform(combined);
if (!platformKey || !base[platformKey]) return;
const entry = base[platformKey];
entry.totalSolved += 1;
const diff = detectDifficulty(combined);
if (diff && entry.difficulties[diff] != null) {
entry.difficulties[diff] += 1;
}
const lower = combined.toLowerCase();
if (lower.includes("array")) entry.categories.push("Arrays");
if (lower.includes("string")) entry.categories.push("Strings");
if (lower.includes("tree")) entry.categories.push("Trees");
if (lower.includes("graph")) entry.categories.push("Graphs");
if (lower.includes("dp") || lower.includes("dynamic programming"))
entry.categories.push("DP");
const dateKey = log.date;
if (dateKey) {
entry.submissionsByDate[dateKey] =
(entry.submissionsByDate[dateKey] || 0) + 1;
}
const currentTs = log.date || log.createdAt || "";
if (!entry.lastProblem || (currentTs && currentTs > entry.lastProblem.timestamp)) {
entry.lastProblem = {
name: log.title || "Solved problem",
difficulty: diff ? diff.charAt(0).toUpperCase() + diff.slice(1) : "Unknown",
category:
entry.categories.length > 0
? entry.categories[entry.categories.length - 1]
: "Unknown",
link: "",
timestamp: currentTs,
};
}
});
Object.values(base).forEach((entry) => {
const seen = new Set();
entry.categories = entry.categories.filter((c) => {
if (seen.has(c)) return false;
seen.add(c);
return true;
});
});
return Object.values(base);
}
// ----- API fetching -----
async function ccFetchExternalStats(usernames) {
const stats = {};
// 1. LeetCode
if (usernames.leetcode) {
try {
const resp = await fetch(`${CC_SERVER_URL}/code-class/leetcode`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: usernames.leetcode }),
});
if (resp.ok) {
const data = await resp.json();
// Map common LeetCode api response
// fields: totalSolved, easySolved, mediumSolved, hardSolved, ranking
stats.leetcode = {
totalSolved: data.totalSolved,
ranking: data.ranking,
difficulties: {
easy: data.easySolved,
medium: data.mediumSolved,
hard: data.hardSolved,
},
};
} else {
console.warn("LeetCode fetch failed", resp.status);
}
} catch (e) {
console.error("LeetCode fetch error", e);
}
}
// 2. CodeChef
if (usernames.codechef) {
try {
const resp = await fetch(
`${CC_SERVER_URL}/code-class/codechef/${encodeURIComponent(usernames.codechef)}`
);
if (resp.ok) {
const data = await resp.json();
// Map CodeChef API response
// fields: success, currentRating, highestRating, globalRank, countryRank
// Does it provide total problems solved? Sometimes in scraping APIs it's tricky.
// Assuming 'data.fullySolved.count' or similar exists, otherwise fallback to 0.
// The endpoint is likely scraping, let's just log what we get or guess.
// Since we don't have exact response structure here, we'll try to extract what we can.
// Mock mapping based on typical CodeChef scraper APIs:
const total = data.total_problems_solved || 0; // naming varies
stats.codechef = {
totalSolved: total,
ranking: data.currentRating,
difficulties: {
easy: 0, // usually not split clearly in simple scrapers
medium: 0,
hard: 0
}
};
}
} catch (e) {
console.error("CodeChef fetch error", e);
}
}
// 3. GFG (HTML proxy)
if (usernames.gfg) {
try {
const resp = await fetch(
`${CC_SERVER_URL}/code-class/gfg/${encodeURIComponent(usernames.gfg)}`
);
if (resp.ok) {
const html = await resp.text();
// Simple regex to find "Problems Solved: X" or similar in GFG profile HTML
// This is fragile but better than nothing.
const solvedMatch = html.match(/problems\s*solved\s*:\s*(\d+)/i) ||
html.match(/total\s*problems\s*solved\s*:\s*(\d+)/i) ||
html.match(/>\s*(\d+)\s*<\/span>\s*problems\s*solved/i);
const scoreMatch = html.match(/coding\s*score\s*:\s*(\d+)/i);
const total = solvedMatch ? parseInt(solvedMatch[1]) : 0;
const score = scoreMatch ? parseInt(scoreMatch[1]) : 0;
stats.gfg = {
totalSolved: total,
ranking: score,
difficulties: { easy: 0, medium: 0, hard: 0 }
};
}
} catch (e) {
console.error("GFG fetch error", e);
}
}
// 4. HackerEarth (HTML proxy)
if (usernames.hackerearth) {
try {
const resp = await fetch(
`${CC_SERVER_URL}/code-class/hackerearth/${encodeURIComponent(usernames.hackerearth)}`
);
if (resp.ok) {
const html = await resp.text();
// Regex for HackerEarth profile
// Often problematic due to dynamic loading, but let's try.
// If unable to parse, we just leave it 0.
const solvedMatch = html.match(/problems\s*solved\s*.*\s*(\d+)/i);
const ratingMatch = html.match(/rating\s*.*\s*(\d+)/i);
stats.hackerearth = {
totalSolved: solvedMatch ? parseInt(solvedMatch[1]) : 0,
ranking: ratingMatch ? parseInt(ratingMatch[1]) : 0,
difficulties: { easy: 0, medium: 0, hard: 0 }
};
}
} catch (e) {
console.error("HackerEarth fetch error", e);
}
}
return stats;
}
async function ccFetchAllPlatforms() {
const user = ccAuth.currentUser;
const usernames = ccGetStoredUsernames(); // Pass this!
if (!user) return [];
// 1. Get local logs stats
const allLogs = ccGetLogs();
const logs = allLogs.filter(
(l) =>
l.userId === user.uid &&
l.tag &&
String(l.tag).toLowerCase() === "dsa"
);
const localStats = ccBuildPlatformStatsFromLogs(logs);
// 2. Fetch external API stats
const apiStats = await ccFetchExternalStats(usernames);
// 3. Merge: prefer API totals over local logs if API calls succeeded
localStats.forEach(stat => {
const key = stat.key;
if (apiStats[key]) {
// Overwrite totals
const api = apiStats[key];
if (api.totalSolved > 0 || (api.totalSolved === 0 && api.ranking)) {
stat.totalSolved = api.totalSolved;
stat.rankRating = api.ranking;
// Merge difficulties if API has them, else keep local logs detailed breakdown?
// Usually API is better for totals.
if (api.difficulties && (api.difficulties.easy || api.difficulties.medium || api.difficulties.hard)) {
stat.difficulties = api.difficulties;
}
stat.source = "api"; // Mark as API sourced
}
}
});
return localStats;
}
function ccSetPlatformError(platformKey, message) {
const labelMap = {
leetcode: "LeetCode",
codechef: "CodeChef",
gfg: "GeeksforGeeks",
hackerearth: "HackerEarth",
};
const prefix = labelMap[platformKey] || platformKey;
const text = `⚠️ ${prefix}: ${message}`;
switch (platformKey) {
case "leetcode":
document.getElementById("cc-lc-total").textContent = "—";
document.getElementById("cc-lc-ranking").textContent = text;
document.getElementById("cc-lc-last-problem").textContent = "—";
break;
case "codechef":
document.getElementById("cc-cc-total").textContent = "—";
document.getElementById("cc-cc-ranking").textContent = text;
document.getElementById("cc-cc-last-problem").textContent = "—";
break;
case "gfg":
document.getElementById("cc-gfg-total").textContent = "—";
document.getElementById("cc-gfg-ranking").textContent = text;
document.getElementById("cc-gfg-last-problem").textContent = "—";
break;
case "hackerearth":
document.getElementById("cc-he-total").textContent = "—";
document.getElementById("cc-he-ranking").textContent = text;
document.getElementById("cc-he-last-problem").textContent = "—";
break;
default:
break;
}
}
function ccUpdatePlatformCards(results) {
results.forEach((r) => {
switch (r.key) {
case "leetcode":
document.getElementById("cc-lc-total").textContent =
r.totalSolved ?? "—";
document.getElementById("cc-lc-ranking").textContent =
r.rankRating
? `Rank: ${r.rankRating}`
: (r.totalSolved > 0 ? "Rank: —" : "From logs: 0 problems");
if (r.lastProblem) {
const lp = r.lastProblem;
document.getElementById(
"cc-lc-last-problem"
).innerHTML = `<a href="${lp.link}" target="_blank" style="color:#38bdf8; text-decoration:none;">${lp.name}</a> · ${lp.difficulty} · ${new Date(
lp.timestamp
).toLocaleString()}`;
} else {
document.getElementById("cc-lc-last-problem").textContent = "—";
}
ccRenderDifficultyChart("leetcode", "cc-lc-difficulty-chart", r.difficulties);
break;
case "codechef":
document.getElementById("cc-cc-total").textContent =
r.totalSolved ?? "—";
document.getElementById("cc-cc-ranking").textContent =
r.rankRating
? `Rating: ${r.rankRating}`
: (r.totalSolved > 0 ? "Rating: —" : "From logs: 0 problems");
if (r.lastProblem) {
const ccLP = r.lastProblem;
document.getElementById(
"cc-cc-last-problem"
).innerHTML = `${ccLP.name} · ${ccLP.difficulty}`;
} else {
document.getElementById("cc-cc-last-problem").textContent = "—";
}
ccRenderDifficultyChart(
"codechef",
"cc-cc-difficulty-chart",
r.difficulties
);
break;
case "gfg":
document.getElementById("cc-gfg-total").textContent =
r.totalSolved ?? "—";
document.getElementById("cc-gfg-ranking").textContent =
r.rankRating
? `Score: ${r.rankRating}`
: (r.totalSolved > 0 ? "Score: —" : "From logs: 0 problems");
if (r.lastProblem) {
document.getElementById("cc-gfg-last-problem").textContent =
r.lastProblem.name;
} else {
document.getElementById("cc-gfg-last-problem").textContent = "—";
}
ccRenderDifficultyChart("gfg", "cc-gfg-difficulty-chart", r.difficulties);
break;
case "hackerearth":
document.getElementById("cc-he-total").textContent =
r.totalSolved ?? "—";
document.getElementById("cc-he-ranking").textContent =
r.rankRating
? `Rating: ${r.rankRating}`
: (r.totalSolved > 0 ? "Rating: —" : "From logs: 0 problems");
if (r.lastProblem) {
document.getElementById("cc-he-last-problem").textContent =
r.lastProblem.name;
} else {
document.getElementById("cc-he-last-problem").textContent = "—";
}
ccRenderDifficultyChart(
"hackerearth",
"cc-he-difficulty-chart",
r.difficulties
);
break;
default:
break;
}
});
}
function ccUpdateWeeklySummary(results) {
const byDate = {};
const byPlatform = {};
results.forEach((r) => {
const key = r.key;
byPlatform[key] = byPlatform[key] || 0;
Object.entries(r.submissionsByDate || {}).forEach(([date, count]) => {
byDate[date] = (byDate[date] || 0) + count;
byPlatform[key] += count; // Using mock history if provided
});
});
ccRenderWeeklyChart(byDate);
const totalWeek = Object.values(byDate).reduce((a, b) => a + b, 0);
const weeklyTotalEl = document.getElementById("cc-weekly-total");
if (weeklyTotalEl) {
weeklyTotalEl.textContent = `Total problems this week: ${totalWeek || "—"
}`;
}
const topPlatformsEl = document.getElementById("cc-weekly-top-platforms");
if (topPlatformsEl) {
const entries = Object.entries(byPlatform).sort((a, b) => b[1] - a[1]);
if (!entries.length) {
topPlatformsEl.textContent = "Most used platforms: —";
} else {
const labelMap = {
leetcode: "LeetCode",
codechef: "CodeChef",
gfg: "GFG",
hackerearth: "HackerEarth",
};
const summary = entries
.slice(0, 3)
.map(([k, v]) => `${labelMap[k] || k} (${v})`)
.join(", ");
topPlatformsEl.textContent = `Most used platforms: ${summary}`;
}
}
const weeklyText = document.getElementById("cc-weekly-summary-text");
if (weeklyText) {
if (totalWeek > 0) {
weeklyText.textContent =
"Your last 7 days of DSA practice across all connected platforms.";
} else {
weeklyText.textContent =
"No problems detected for this week yet, or APIs are limited. Solve something today and refresh.";
}
}
}
async function ccRunAutoLoggingIfNeeded(user, results) {
// Auto-logging based on external platform activity is disabled because
// Code_Class now derives stats purely from local DevTrackr logs.
return;
}
// ----- Page wiring -----
function ccInitCodeClassPage() {
const btnLogout = document.getElementById("btn-logout");
if (btnLogout) {
btnLogout.onclick = () => {
ccAuth.signOut().then(() => {
window.location.href = "index.html";
});
};
}
const inputs = {
leetcode: document.getElementById("cc-username-leetcode"),
codechef: document.getElementById("cc-username-codechef"),
gfg: document.getElementById("cc-username-gfg"),
hackerearth: document.getElementById("cc-username-hackerearth"),
};
const stored = ccGetStoredUsernames();
Object.entries(inputs).forEach(([key, el]) => {
if (el && stored[key]) el.value = stored[key];
});
const btnSave = document.getElementById("cc-btn-save");
const btnFetch = document.getElementById("cc-btn-fetch");
const statusHint = document.getElementById("cc-status-hint");
if (btnSave) {
btnSave.onclick = () => {
const usernames = {};
Object.entries(inputs).forEach(([key, el]) => {
usernames[key] = (el && el.value.trim()) || "";
});
ccSaveStoredUsernames(usernames);
if (statusHint) {
statusHint.textContent = "Usernames saved locally.";
}
};
}
if (btnFetch) {
btnFetch.onclick = async () => {
const usernames = ccGetStoredUsernames();
if (statusHint) {
statusHint.textContent = "Fetching profiles (make sure 'node server.js' is running)...";
}
const results = await ccFetchAllPlatforms();
ccUpdatePlatformCards(results);
ccUpdateWeeklySummary(results);
const user = ccAuth.currentUser;
await ccRunAutoLoggingIfNeeded(user, results);
if (statusHint) {
statusHint.textContent = "Profiles updated.";
}
};
}
const btnDemo = document.getElementById("cc-btn-demo");
if (btnDemo) {
btnDemo.onclick = () => {
// Demo Mode: Mock data with randomization
if (statusHint) statusHint.textContent = "Generating random demo data...";
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const lcTotal = rand(300, 600);
const lcEasy = Math.floor(lcTotal * 0.4);
const lcMed = Math.floor(lcTotal * 0.5);
const lcHard = lcTotal - lcEasy - lcMed;
const ccTotal = rand(100, 300);
const gfgTotal = rand(200, 450);
const heTotal = rand(50, 150);
// Helper to generate mock history for the last 7 days
const getMockHistory = () => {
const h = {};
const today = new Date();
for (let i = 0; i < 7; i++) {
const d = new Date(today);
d.setDate(d.getDate() - i);
const key = d.toISOString().slice(0, 10);
h[key] = rand(0, 5); // 0-5 problems per day random
}
return h;
};
const demoStatsAll = [
{
key: "leetcode",
totalSolved: lcTotal,
rankRating: rand(100000, 500000).toLocaleString(),
difficulties: { easy: lcEasy, medium: lcMed, hard: lcHard },
lastProblem: { name: "Two Sum", link: "#", timestamp: new Date().toISOString() },
submissionsByDate: getMockHistory()
},
{
key: "codechef",
totalSolved: ccTotal,
rankRating: `${rand(1400, 1800)} (${rand(2, 4)}★)`,
difficulties: { easy: Math.floor(ccTotal * 0.6), medium: Math.floor(ccTotal * 0.3), hard: Math.floor(ccTotal * 0.1) },
lastProblem: { name: "Chef and Array", link: "#", timestamp: new Date().toISOString() },
submissionsByDate: getMockHistory()
},
{
key: "gfg",
totalSolved: gfgTotal,
rankRating: rand(800, 1500).toString(),
difficulties: { easy: Math.floor(gfgTotal * 0.4), medium: Math.floor(gfgTotal * 0.4), hard: Math.floor(gfgTotal * 0.2) },
lastProblem: { name: "Detect Cycle in Graph", link: "#", timestamp: new Date().toISOString() },
submissionsByDate: getMockHistory()
},
{
key: "hackerearth",
totalSolved: heTotal,
rankRating: rand(1200, 1600).toString(),
difficulties: { easy: Math.floor(heTotal * 0.5), medium: Math.floor(heTotal * 0.4), hard: Math.floor(heTotal * 0.1) },
lastProblem: { name: "Linear Search", link: "#", timestamp: new Date().toISOString() },
submissionsByDate: getMockHistory()
}
];
// Filter based on inputs
const currentInputs = {
leetcode: document.getElementById("cc-username-leetcode")?.value.trim(),
codechef: document.getElementById("cc-username-codechef")?.value.trim(),
gfg: document.getElementById("cc-username-gfg")?.value.trim(),
hackerearth: document.getElementById("cc-username-hackerearth")?.value.trim(),
};
const hasAnyInput = Object.values(currentInputs).some(v => v);
let demoStats = [];
if (!hasAnyInput) {
// If no inputs, show all (fallback/default demo behavior)
demoStats = demoStatsAll;
} else {
// Only show platforms that have a username typed
demoStats = demoStatsAll.filter(d => currentInputs[d.key]);
}
// If user typed something but we filtered everything out (shouldn't happen if logic is right), fallback to all?
// No, if they typed "leetcode" they want only leetcode.
// Clear all first to ensure hidden ones are reset
// (The update function might not clear old values if we don't pass them, so we might need to handle UI clearing)
// But ccUpdatePlatformCards only updates what is passed.
// We should probably reset the UI for missing keys.
const allKeys = ["leetcode", "codechef", "gfg", "hackerearth"];
allKeys.forEach(k => {
if (!demoStats.find(d => d.key === k)) {
ccSetPlatformError(k, "No username provided (Demo)");
}
});
ccUpdatePlatformCards(demoStats);
ccUpdateWeeklySummary(demoStats);
if (statusHint) statusHint.textContent = "⚡ Demo Mode Active: Random data generated.";
};
}
}
// Auto-logging when dashboard (or any page including this script) loads
async function ccAutoCheckOnLoad(user) {
const usernames = ccGetStoredUsernames();
const hasAny = Object.values(usernames).some((v) => v && v.trim());
if (!hasAny) return;
try {
const results = await ccFetchAllPlatforms();
await ccRunAutoLoggingIfNeeded(user, results);
} catch (e) {
console.error("Auto Code_Class check failed", e);
}
}
document.addEventListener("DOMContentLoaded", () => {
const root = document.getElementById("code-class-root");
ccAuth.onAuthStateChanged((user) => {
if (!user) {
window.location.href = "index.html";
return;
}
// If we are on the Code_Class page, wire UI.
if (root) {
ccInitCodeClassPage();
}
// Auto logging check on any page where this script runs (e.g., dashboard).
ccAutoCheckOnLoad(user);
});
});
// No external API tester needed now that Code_Class uses local logs only.