-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprofilescript.js
More file actions
1558 lines (1376 loc) · 53.2 KB
/
profilescript.js
File metadata and controls
1558 lines (1376 loc) · 53.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
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
// Auth0 configuration and client
let auth0Client = null;
let currentUser = null;
const configureClient = async () => {
try {
const response = await fetch("./auth_config.json");
if (!response.ok) {
throw new Error(`Failed to load config: ${response.status}`);
}
const config = await response.json();
auth0Client = await auth0.createAuth0Client({
domain: config.domain,
clientId: config.clientId,
authorizationParams: {
redirect_uri: window.location.origin + "/frontend/profile.html",
},
});
console.log("Auth0 client configured successfully");
} catch (error) {
console.error("Error configuring Auth0 client:", error);
throw error;
}
};
const handleRedirectCallback = async () => {
const isAuthenticated = await auth0Client.isAuthenticated();
if (
window.location.search.includes("code=") &&
window.location.search.includes("state=")
) {
await auth0Client.handleRedirectCallback();
window.history.replaceState(
{},
document.title,
window.location.pathname
);
}
if (await auth0Client.isAuthenticated()) {
currentUser = await auth0Client.getUser();
loadUserData();
} else {
// Redirect to login if not authenticated
window.location.href = "index.html";
}
};
const logout = async () => {
try {
if (auth0Client) {
await auth0Client.logout({
logoutParams: {
returnTo: window.location.origin + "/frontend/index.html",
},
});
} else {
// Fallback if Auth0 client is not available
console.warn("Auth0 client not available, performing simple logout");
window.location.href = "index.html";
}
} catch (error) {
console.error("Error during logout:", error);
// Fallback to simple redirect
window.location.href = "index.html";
}
};
const userData = {
name: "Sahas",
fullName: "Sahas sharma",
grade: "Grade 3",
avatar: "ss",
totalWords: 248,
totalTime: 12.5,
accuracy: 87,
level: "🏆 Gold",
stars: 156,
streakDays: 0, // Will be calculated dynamically
todayProgress: 75, // percentage
wordsRemaining: 15,
};
// Streak tracking system
const streakData = {
lastPracticeDate: null,
practiceHistory: [], // Array of date strings in YYYY-MM-DD format
currentStreak: 0,
// Initialize from localStorage or create new
init() {
const savedData = localStorage.getItem('dyslexicjit_streak_data');
if (savedData) {
const parsed = JSON.parse(savedData);
this.lastPracticeDate = parsed.lastPracticeDate;
this.practiceHistory = parsed.practiceHistory || [];
this.currentStreak = parsed.currentStreak || 0;
} else {
// Initialize with some sample data for demo purposes
const today = new Date();
this.practiceHistory = [];
// Add practice days for the last 6 days (not including today)
for (let i = 6; i >= 1; i--) {
const date = new Date(today);
date.setDate(today.getDate() - i);
this.practiceHistory.push(this.formatDate(date));
}
this.lastPracticeDate = this.formatDate(new Date(today.getTime() - 24 * 60 * 60 * 1000)); // Yesterday
this.calculateStreak();
this.save();
}
// Always recalculate streak on init to handle date changes
this.calculateStreak();
},
// Save to localStorage
save() {
localStorage.setItem('dyslexicjit_streak_data', JSON.stringify({
lastPracticeDate: this.lastPracticeDate,
practiceHistory: this.practiceHistory,
currentStreak: this.currentStreak
}));
},
// Format date as YYYY-MM-DD
formatDate(date) {
return date.getFullYear() + '-' +
String(date.getMonth() + 1).padStart(2, '0') + '-' +
String(date.getDate()).padStart(2, '0');
},
// Add a practice session for today
addPracticeToday() {
const today = this.formatDate(new Date());
if (!this.practiceHistory.includes(today)) {
this.practiceHistory.push(today);
this.practiceHistory.sort(); // Keep dates sorted
this.lastPracticeDate = today;
this.calculateStreak();
this.save();
}
},
// Calculate current streak
calculateStreak() {
if (this.practiceHistory.length === 0) {
this.currentStreak = 0;
return;
}
const today = new Date();
const todayStr = this.formatDate(today);
const yesterdayStr = this.formatDate(new Date(today.getTime() - 24 * 60 * 60 * 1000));
// Sort practice history in ascending order
const sortedHistory = [...this.practiceHistory].sort();
let streak = 0;
// Check if streak is still alive (practiced today or yesterday)
const hasToday = sortedHistory.includes(todayStr);
const hasYesterday = sortedHistory.includes(yesterdayStr);
if (!hasToday && !hasYesterday) {
// Streak is broken
this.currentStreak = 0;
return;
}
// Start from the most recent practice day and count backwards
let currentDate = new Date(today);
// If they haven't practiced today, start from yesterday
if (!hasToday) {
currentDate.setDate(currentDate.getDate() - 1);
}
// Count consecutive days backwards
while (true) {
const currentDateStr = this.formatDate(currentDate);
if (sortedHistory.includes(currentDateStr)) {
streak++;
currentDate.setDate(currentDate.getDate() - 1);
} else {
break;
}
}
this.currentStreak = streak;
},
// Check if user practiced on a specific date
hasPracticedOn(date) {
const dateStr = this.formatDate(date);
return this.practiceHistory.includes(dateStr);
},
// Get streak for display
getStreak() {
this.calculateStreak();
return this.currentStreak;
}
};
document.addEventListener("DOMContentLoaded", async function () {
try {
// Initialize systems
settingsData.init();
streakData.init();
await configureClient();
await handleRedirectCallback();
generateCalendar();
animateStats();
initializeEventListeners();
animateProgressBar();
} catch (error) {
console.error("Error initializing Auth0:", error);
window.location.href = "index.html";
}
});
function loadUserData() {
// Use Auth0 user data if available, otherwise use default userData
const displayName = currentUser
? currentUser.name || currentUser.nickname || currentUser.email
: userData.name;
const fullName = currentUser ? currentUser.name : userData.fullName;
const avatar = currentUser
? currentUser.picture
? `<img src="${currentUser.picture}" alt="Profile" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;">`
: userData.avatar
: userData.avatar;
// Load user information
document.getElementById("userName").textContent = displayName;
document.getElementById("profileName").textContent = fullName;
document.getElementById("userAvatar").innerHTML =
typeof avatar === "string" && avatar.includes("<img")
? avatar
: `<span>${avatar}</span>`;
// Load stats
document.getElementById("totalWords").textContent = userData.totalWords;
document.getElementById("totalTime").textContent = userData.totalTime;
document.getElementById("accuracy").textContent = userData.accuracy + "%";
// Update streak with dynamic data
const currentStreak = streakData.getStreak();
document.getElementById("streakDays").textContent = currentStreak;
userData.streakDays = currentStreak; // Update userData for other functions
// Load progress
const progressPercent = userData.todayProgress + "%";
document.getElementById("progressPercent").textContent = progressPercent;
document.getElementById("progressFill").style.width = "0%"; // Start at 0 for animation
// Update progress text
const progressText = document.querySelector(".progress-text");
if (userData.todayProgress >= 100) {
progressText.textContent = "🎉 Daily goal completed! Great job!";
progressText.style.color = "var(--accent-coral)";
progressText.style.fontWeight = "700";
} else {
progressText.textContent = `${userData.wordsRemaining} more words to complete today!`;
}
}
function animateStats() {
const currentStreak = streakData.getStreak();
const stats = [
{
element: document.getElementById("totalWords"),
target: userData.totalWords,
},
{
element: document.getElementById("totalTime"),
target: userData.totalTime,
decimal: true,
},
{
element: document.getElementById("streakDays"),
target: currentStreak,
},
];
stats.forEach((stat) => {
animateCounter(stat.element, stat.target, stat.decimal);
});
}
function animateCounter(element, target, isDecimal = false) {
const duration = 1500;
const start = 0;
const increment = target / (duration / 16);
let current = start;
const timer = setInterval(() => {
current += increment;
if (current >= target) {
element.textContent = isDecimal ? target.toFixed(1) : target;
clearInterval(timer);
} else {
element.textContent = isDecimal
? current.toFixed(1)
: Math.floor(current);
}
}, 16);
}
function animateProgressBar() {
setTimeout(() => {
const progressFill = document.getElementById("progressFill");
progressFill.style.width = userData.todayProgress + "%";
}, 500);
}
function generateCalendar() {
const calendarGrid = document.getElementById("calendarGrid");
calendarGrid.innerHTML = ""; // Clear existing content
const today = new Date();
const daysOfWeek = ["S", "M", "T", "W", "T", "F", "S"];
// Show 4 weeks (28 days) - 3 weeks in the past + current week
const totalDays = 28;
const startDate = new Date(today);
startDate.setDate(today.getDate() - 21); // Start 3 weeks ago
// Find the start of the week for the start date (Sunday)
const startOfCalendar = new Date(startDate);
startOfCalendar.setDate(startDate.getDate() - startDate.getDay());
// Generate calendar days for 4 weeks
for (let i = 0; i < totalDays; i++) {
const dayElement = document.createElement("div");
dayElement.className = "calendar-day";
const dayLabel = document.createElement("div");
dayLabel.className = "calendar-day-label";
dayLabel.textContent = daysOfWeek[i % 7];
const dayNumber = document.createElement("div");
dayNumber.className = "calendar-day-number";
// Calculate date for this day
const date = new Date(startOfCalendar);
date.setDate(startOfCalendar.getDate() + i);
dayNumber.textContent = date.getDate();
// Add month indicator for first day of month or if different from previous day
if (i > 0) {
const prevDate = new Date(startOfCalendar);
prevDate.setDate(startOfCalendar.getDate() + i - 1);
if (date.getMonth() !== prevDate.getMonth() || date.getDate() === 1) {
const monthLabel = document.createElement("div");
monthLabel.className = "calendar-month-label";
monthLabel.textContent = date.toLocaleDateString('en-US', { month: 'short' });
dayElement.appendChild(monthLabel);
}
} else if (date.getDate() === 1 || i === 0) {
const monthLabel = document.createElement("div");
monthLabel.className = "calendar-month-label";
monthLabel.textContent = date.toLocaleDateString('en-US', { month: 'short' });
dayElement.appendChild(monthLabel);
}
// Determine status based on real practice data
const hasPracticed = streakData.hasPracticedOn(date);
const isToday = date.toDateString() === today.toDateString();
const isPast = date < today && !isToday;
const isFuture = date > today;
if (isToday) {
dayElement.classList.add("today");
// If user has completed today's goal, mark as completed
if (userData.todayProgress >= 100 || hasPracticed) {
dayElement.classList.add("completed");
}
// Scroll to today on initial load
setTimeout(() => {
dayElement.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'center'
});
}, 100);
} else if (isPast) {
if (hasPracticed) {
dayElement.classList.add("completed");
} else {
dayElement.classList.add("inactive");
}
} else {
// Future days
dayElement.classList.add("inactive");
}
dayElement.appendChild(dayLabel);
dayElement.appendChild(dayNumber);
calendarGrid.appendChild(dayElement);
}
}
function initializeEventListeners() {
const homeBtn = document.getElementById("homeBtn");
const settingsBtn = document.getElementById("settingsBtn");
const logoutBtn = document.getElementById("logoutBtn");
const editProfileBtn = document.getElementById("editProfileBtn");
homeBtn.addEventListener("click", () => {
window.location.href = "index.html";
});
settingsBtn.addEventListener("click", () => {
showSettingsModal();
});
logoutBtn.addEventListener("click", async () => {
if (confirm("Are you sure you want to logout?")) {
try {
await logout();
} catch (error) {
console.error("Error during logout:", error);
// Force redirect as fallback
window.location.href = "index.html";
}
}
});
editProfileBtn.addEventListener("click", () => {
alert("✏️ Profile editing coming soon!");
});
const badges = document.querySelectorAll(".badge");
badges.forEach((badge) => {
badge.addEventListener("click", function () {
const title = this.getAttribute("title");
showNotification(`🎉 ${title} badge earned!`);
});
});
const logo = document.querySelector(".nav-logo");
logo.addEventListener("click", () => {
window.location.href = "foxmode.html";
});
// Initialize goals functionality
initializeGoals();
}
function showNotification(message) {
const notification = document.createElement("div");
notification.style.cssText = `
position: fixed;
top: 100px;
right: 30px;
background: white;
padding: 1.5rem 2rem;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
border: 2px solid var(--primary-orange);
z-index: 10000;
font-weight: 600;
color: var(--text-primary);
animation: slideIn 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = "slideOut 0.3s ease";
setTimeout(() => {
notification.remove();
}, 300);
}, 3000);
}
const notificationStyles = document.createElement("style");
notificationStyles.textContent = `
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
`;
document.head.appendChild(notificationStyles);
const actionButtons = document.querySelectorAll(".action-btn");
actionButtons.forEach((btn) => {
btn.addEventListener("mouseenter", function () {
this.style.transform = "translateY(-5px)";
});
btn.addEventListener("mouseleave", function () {
this.style.transform = "translateY(0)";
});
});
const avatar = document.getElementById("userAvatar");
avatar.addEventListener("click", function () {
this.style.animation = "none";
setTimeout(() => {
this.style.animation = "spin 0.6s ease";
}, 10);
});
const avatarStyles = document.createElement("style");
avatarStyles.textContent = `
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
`;
document.head.appendChild(avatarStyles);
// Function to complete today's practice
function completeTodaysPractice() {
// Mark today as completed
streakData.addPracticeToday();
userData.todayProgress = 100;
userData.wordsRemaining = 0;
// Update UI
document.getElementById("progressPercent").textContent = "100%";
document.getElementById("progressFill").style.width = "100%";
const progressText = document.querySelector(".progress-text");
progressText.textContent = "🎉 Daily goal completed! Great job!";
progressText.style.color = "var(--accent-coral)";
progressText.style.fontWeight = "700";
// Recalculate and update streak display
streakData.calculateStreak();
const newStreak = streakData.getStreak();
document.getElementById("streakDays").textContent = newStreak;
userData.streakDays = newStreak;
// Regenerate calendar to show today as completed
generateCalendar();
// Show celebration notification
showNotification("🎉 Daily goal completed! Your streak is now " + newStreak + " days!");
// Add fire animation if streak is 7 or more
if (newStreak >= 7) {
setTimeout(() => {
const streakIcon = document.querySelector(".streak-icon");
if (streakIcon) {
streakIcon.style.animation = "fire 0.5s ease infinite";
}
}, 500);
}
}
// Debug function to add practice for previous days (for testing)
function addPracticeForDate(daysAgo) {
const date = new Date();
date.setDate(date.getDate() - daysAgo);
const dateStr = streakData.formatDate(date);
if (!streakData.practiceHistory.includes(dateStr)) {
streakData.practiceHistory.push(dateStr);
streakData.practiceHistory.sort();
streakData.calculateStreak(); // Recalculate streak
streakData.save();
generateCalendar(); // Refresh calendar
const newStreak = streakData.getStreak();
document.getElementById("streakDays").textContent = newStreak;
userData.streakDays = newStreak;
showNotification(`✅ Added practice for ${daysAgo} days ago. Streak: ${newStreak}`);
} else {
showNotification(`⚠️ Practice already recorded for ${daysAgo} days ago`);
}
}
// Check if streak should have fire animation
if (streakData.getStreak() >= 7) {
setTimeout(() => {
const streakIcon = document.querySelector(".streak-icon");
if (streakIcon) {
streakIcon.style.animation = "fire 0.5s ease infinite";
}
}, 1000);
}
const fireAnimation = document.createElement("style");
fireAnimation.textContent = `
@keyframes fire {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.2); }
}
`;
document.head.appendChild(fireAnimation);
// ==================== CALENDAR DAY CLICK ====================
document.addEventListener("click", function (e) {
if (
e.target.closest(".calendar-day") &&
!e.target.closest(".calendar-day.empty")
) {
const day = e.target.closest(".calendar-day");
const dayNumber = day.querySelector(".calendar-day-number").textContent;
if (day.classList.contains("completed")) {
if (day.classList.contains("today")) {
showNotification(`🎉 Today (${dayNumber}) - Practice completed!`);
} else {
showNotification(`✅ Day ${dayNumber} - Practice completed!`);
}
} else if (day.classList.contains("today")) {
const remaining = userData.todayProgress < 100 ? userData.wordsRemaining : 0;
if (remaining > 0) {
showNotification(
`📅 Today (${dayNumber}): ${userData.todayProgress}% complete! ${remaining} words remaining.`
);
} else {
showNotification(`🎯 Today (${dayNumber}): Ready to practice!`);
}
} else if (day.classList.contains("inactive")) {
const today = new Date();
const currentDay = today.getDay();
const dayIndex = Array.from(day.parentNode.children).indexOf(day);
if (dayIndex < currentDay) {
showNotification(`📅 Day ${dayNumber} - No practice recorded`);
} else {
showNotification(`📆 Day ${dayNumber} - Future date`);
}
} else {
showNotification(
`📆 Day ${dayNumber} - Keep building your streak!`
);
}
}
});
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
anchor.addEventListener("click", function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute("href"));
if (target) {
target.scrollIntoView({
behavior: "smooth",
block: "start",
});
}
});
});
const motivationalMessages = [
"🌟 You're doing great! Keep practicing!",
"🚀 Every word you learn is progress!",
"💪 Your hard work is paying off!",
"🎯 Focus and patience - you've got this!",
"⭐ Reading champion in the making!",
];
setTimeout(() => {
const randomMessage =
motivationalMessages[
Math.floor(Math.random() * motivationalMessages.length)
];
showNotification(randomMessage);
}, 2000);
document.addEventListener("keydown", function (e) {
// Press 'P' for practice
if (e.key === "p" || e.key === "P") {
if (e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") {
window.location.href = "practice.html";
}
}
// Press 'S' for struggle words
if (e.key === "s" || e.key === "S") {
if (e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") {
window.location.href = "struggle.html";
}
}
// Press 'C' to complete today's practice (for testing)
if (e.key === "c" || e.key === "C") {
if (e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") {
if (userData.todayProgress < 100) {
completeTodaysPractice();
} else {
showNotification("📅 Today's practice already completed!");
}
}
}
// Press 'R' to reset streak data (for testing)
if (e.key === "r" || e.key === "R") {
if (e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA" && e.shiftKey) {
if (confirm("Are you sure you want to reset all streak data? This cannot be undone.")) {
localStorage.removeItem('dyslexicjit_streak_data');
streakData.init();
location.reload();
}
}
}
});
window.addEventListener("load", () => {
const cards = document.querySelectorAll(
".welcome-card, .profile-card, .streak-card"
);
cards.forEach((card, index) => {
card.style.opacity = "0";
card.style.transform = "translateY(30px)";
setTimeout(() => {
card.style.transition = "all 0.6s ease";
card.style.opacity = "1";
card.style.transform = "translateY(0)";
}, index * 150);
});
});
// Debug functions available in console
window.debugStreak = {
complete: completeTodaysPractice,
addPractice: addPracticeForDate,
reset: () => {
localStorage.removeItem('dyslexicjit_streak_data');
location.reload();
},
show: () => {
console.log('Current streak:', streakData.getStreak());
console.log('Practice history:', streakData.practiceHistory);
console.log('Last practice:', streakData.lastPracticeDate);
}
};
// Settings System
const settingsData = {
settings: {
theme: 'light',
notifications: true,
soundEffects: true,
dailyGoal: 20,
difficulty: 'medium',
fontSize: 'medium',
autoSave: true,
practiceReminder: true,
streakNotifications: true,
celebrationAnimations: true
},
init() {
const savedSettings = localStorage.getItem('dyslexicjit_settings');
if (savedSettings) {
this.settings = { ...this.settings, ...JSON.parse(savedSettings) };
}
this.applySettings();
},
save() {
localStorage.setItem('dyslexicjit_settings', JSON.stringify(this.settings));
this.applySettings();
},
updateSetting(key, value) {
this.settings[key] = value;
this.save();
},
resetToDefaults() {
this.settings = {
theme: 'light',
notifications: true,
soundEffects: true,
dailyGoal: 20,
difficulty: 'medium',
fontSize: 'medium',
autoSave: true,
practiceReminder: true,
streakNotifications: true,
celebrationAnimations: true
};
this.save();
},
applySettings() {
// Apply theme
document.body.setAttribute('data-theme', this.settings.theme);
// Apply font size
document.body.setAttribute('data-font-size', this.settings.fontSize);
// Update progress goal if needed
if (userData.todayProgress !== undefined) {
const progressText = document.querySelector('.progress-text');
if (progressText && this.settings.dailyGoal) {
const remaining = Math.max(0, this.settings.dailyGoal - (userData.totalWords || 0));
if (remaining > 0) {
progressText.textContent = `${remaining} more words to complete today's goal!`;
} else {
progressText.textContent = "🎉 Daily goal completed! Great job!";
}
}
}
}
};
function showSettingsModal() {
const modal = document.createElement('div');
modal.className = 'settings-modal';
modal.innerHTML = `
<div class="settings-modal-content">
<div class="settings-modal-header">
<h3><i class="fas fa-cog"></i> Settings</h3>
<button class="close-modal" onclick="this.closest('.settings-modal').remove()">
<i class="fas fa-times"></i>
</button>
</div>
<div class="settings-modal-body">
<div class="settings-tabs">
<button class="settings-tab active" data-tab="general">General</button>
<button class="settings-tab" data-tab="practice">Practice</button>
<button class="settings-tab" data-tab="notifications">Notifications</button>
<button class="settings-tab" data-tab="accessibility">Accessibility</button>
</div>
<div class="settings-content">
<div class="settings-panel active" data-panel="general">
<div class="setting-group">
<div class="setting-item">
<div class="setting-info">
<label>Theme</label>
<span class="setting-description">Choose your preferred color theme</span>
</div>
<select class="setting-control" data-setting="theme">
<option value="light" ${settingsData.settings.theme === 'light' ? 'selected' : ''}>Light</option>
<option value="dark" ${settingsData.settings.theme === 'dark' ? 'selected' : ''}>Dark</option>
<option value="auto" ${settingsData.settings.theme === 'auto' ? 'selected' : ''}>Auto</option>
</select>
</div>
<div class="setting-item">
<div class="setting-info">
<label>Sound Effects</label>
<span class="setting-description">Play sounds for interactions and achievements</span>
</div>
<label class="toggle-switch">
<input type="checkbox" data-setting="soundEffects" ${settingsData.settings.soundEffects ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
</div>
<div class="setting-item">
<div class="setting-info">
<label>Auto Save Progress</label>
<span class="setting-description">Automatically save your reading progress</span>
</div>
<label class="toggle-switch">
<input type="checkbox" data-setting="autoSave" ${settingsData.settings.autoSave ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div>
<div class="settings-panel" data-panel="practice">
<div class="setting-group">
<div class="setting-item">
<div class="setting-info">
<label>Daily Words Goal</label>
<span class="setting-description">Number of words to practice each day</span>
</div>
<input type="number" class="setting-control" data-setting="dailyGoal"
value="${settingsData.settings.dailyGoal}" min="5" max="100" step="5">
</div>
<div class="setting-item">
<div class="setting-info">
<label>Reading Difficulty</label>
<span class="setting-description">Adjust the complexity of reading materials</span>
</div>
<select class="setting-control" data-setting="difficulty">
<option value="easy" ${settingsData.settings.difficulty === 'easy' ? 'selected' : ''}>Easy</option>
<option value="medium" ${settingsData.settings.difficulty === 'medium' ? 'selected' : ''}>Medium</option>
<option value="hard" ${settingsData.settings.difficulty === 'hard' ? 'selected' : ''}>Hard</option>
</select>
</div>
<div class="setting-item">
<div class="setting-info">
<label>Practice Reminders</label>
<span class="setting-description">Get reminded when it's time to practice</span>
</div>
<label class="toggle-switch">
<input type="checkbox" data-setting="practiceReminder" ${settingsData.settings.practiceReminder ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div>
<div class="settings-panel" data-panel="notifications">
<div class="setting-group">
<div class="setting-item">
<div class="setting-info">
<label>Enable Notifications</label>
<span class="setting-description">Receive notifications for achievements and reminders</span>
</div>
<label class="toggle-switch">
<input type="checkbox" data-setting="notifications" ${settingsData.settings.notifications ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
</div>
<div class="setting-item">
<div class="setting-info">
<label>Streak Notifications</label>
<span class="setting-description">Get notified about your reading streaks</span>
</div>
<label class="toggle-switch">
<input type="checkbox" data-setting="streakNotifications" ${settingsData.settings.streakNotifications ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
</div>
<div class="setting-item">
<div class="setting-info">
<label>Celebration Animations</label>
<span class="setting-description">Show animations when completing goals</span>
</div>
<label class="toggle-switch">
<input type="checkbox" data-setting="celebrationAnimations" ${settingsData.settings.celebrationAnimations ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div>
<div class="settings-panel" data-panel="accessibility">
<div class="setting-group">
<div class="setting-item">
<div class="setting-info">
<label>Font Size</label>
<span class="setting-description">Adjust text size for better readability</span>
</div>
<select class="setting-control" data-setting="fontSize">
<option value="small" ${settingsData.settings.fontSize === 'small' ? 'selected' : ''}>Small</option>
<option value="medium" ${settingsData.settings.fontSize === 'medium' ? 'selected' : ''}>Medium</option>
<option value="large" ${settingsData.settings.fontSize === 'large' ? 'selected' : ''}>Large</option>
<option value="extra-large" ${settingsData.settings.fontSize === 'extra-large' ? 'selected' : ''}>Extra Large</option>
</select>
</div>
<div class="setting-item">
<div class="setting-info">
<label>High Contrast Mode</label>
<span class="setting-description">Improve visibility with higher contrast</span>
</div>
<label class="toggle-switch">
<input type="checkbox" data-setting="highContrast" ${settingsData.settings.highContrast ? 'checked' : ''}>
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="settings-modal-actions">
<button class="btn-secondary" onclick="resetSettings()">Reset to Defaults</button>
<button class="btn-primary" onclick="this.closest('.settings-modal').remove()">Done</button>
</div>
</div>
`;
document.body.appendChild(modal);