Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1221 lines (1035 loc) · 48.6 KB
/
Copy pathscript.js
File metadata and controls
1221 lines (1035 loc) · 48.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
window.closeAllPanels = function(exceptId) {
const panels = [
'settingsPanel', 'achievementsPanel', 'timerPanel', 'moodTracker',
'habitTracker', 'challengePanel', 'emotionPanel',
'heatmapPanel', 'avatarPanel',
'selfImprovementPanel'
];
panels.forEach(id => {
if (id !== exceptId) {
const el = document.getElementById(id);
if (el) el.classList.add('hidden');
}
});
};
class Kaleshak {
constructor() {
this.feelingInput = document.getElementById('feelingInput');
this.talkButton = document.getElementById('talkButton');
this.responseSection = document.getElementById('responseSection');
this.responseText = document.getElementById('responseText');
this.actionButton = document.getElementById('actionButton');
this.stopSpeechBtn = document.getElementById('stopSpeech');
this.repeatSpeechBtn = document.getElementById('repeatSpeech');
this.statsSection = document.getElementById('statsSection');
this.sessionCount = document.getElementById('sessionCount');
this.streakCount = document.getElementById('streakCount');
this.settingsBtn = document.getElementById('settingsBtn');
this.settingsPanel = document.getElementById('settingsPanel');
this.voiceBtn = document.getElementById('voiceBtn');
this.achievementsBtn = document.getElementById('achievementsBtn');
this.achievementsPanel = document.getElementById('achievementsPanel');
this.badgeCount = document.getElementById('badgeCount');
this.timerBtn = document.getElementById('timerBtn');
this.timerPanel = document.getElementById('timerPanel');
this.moodTrackBtn = document.getElementById('moodTrackBtn');
this.moodTracker = document.getElementById('moodTracker');
this.notification = document.getElementById('notification');
this.jarvisInterface = document.getElementById('jarvisInterface');
this.jarvisOrb = document.getElementById('jarvisOrb');
this.jarvisStatus = document.getElementById('jarvisStatus');
this.jarvisWaveform = document.getElementById('jarvisWaveform');
this.jarvisCommands = document.getElementById('jarvisCommands');
this.jarvisToggle = document.getElementById('jarvisToggle');
this.xpSystem = document.getElementById('xpSystem');
this.xpFill = document.getElementById('xpFill');
this.xpText = document.getElementById('xpText');
this.habitTracker = document.getElementById('habitTracker');
this.habitBtn = document.getElementById('habitBtn');
this.challengePanel = document.getElementById('challengePanel');
this.challengeBtn = document.getElementById('challengeBtn');
// Wikipedia Command Center elements
this.wikiTitle = document.getElementById('wikiTitle');
this.wikiDesc = document.getElementById('wikiDesc');
this.wikiImageContainer = document.getElementById('wikiImageContainer');
this.wikiImage = document.getElementById('wikiImage');
this.deepSummaryBtn = document.getElementById('deepSummaryBtn');
this.startQuizBtn = document.getElementById('startQuizBtn');
this.aiSummarySection = document.getElementById('aiSummarySection');
this.aiSummaryText = document.getElementById('aiSummaryText');
this.aiQuizSection = document.getElementById('aiQuizSection');
this.quizContainer = document.getElementById('quizContainer');
this.currentTopic = null;
this.currentResponse = '';
this.stats = this.loadStats();
this.settings = this.loadSettings();
this.achievements = this.loadAchievements();
this.moodData = this.loadMoodData();
this.xpData = this.loadXPData();
this.habits = this.loadHabits();
this.challenges = this.loadChallenges();
this.isRecording = false;
this.timer = { minutes: 25, seconds: 0, isRunning: false, interval: null };
this.jarvisMode = false;
this.jarvisListening = false;
this.initializeEventListeners();
this.initializeSpeech();
this.initializeVoiceRecognition();
this.initializeTimer();
this.initializeMoodTracker();
this.initializeJarvis();
this.initializeXP();
this.initializeHabits();
this.initializeChallenges();
this.updateStats();
this.applySettings();
this.updateAchievements();
this.scheduleReminders();
}
initializeEventListeners() {
this.talkButton.addEventListener('click', () => this.handleTalkToKaleshak());
this.actionButton.addEventListener('click', () => this.handleActionButton());
this.stopSpeechBtn.addEventListener('click', () => this.stopSpeech());
this.repeatSpeechBtn.addEventListener('click', () => this.repeatSpeech());
this.settingsBtn.addEventListener('click', () => this.toggleSettings());
this.voiceBtn.addEventListener('click', () => this.toggleVoiceInput());
this.achievementsBtn.addEventListener('click', () => this.toggleAchievements());
this.timerBtn.addEventListener('click', () => this.toggleTimer());
this.moodTrackBtn.addEventListener('click', () => this.toggleMoodTracker());
this.jarvisToggle.addEventListener('click', () => this.toggleJarvis());
this.jarvisOrb.addEventListener('click', () => this.activateJarvis());
this.habitBtn.addEventListener('click', () => this.toggleHabits());
this.challengeBtn.addEventListener('click', () => this.toggleChallenge());
this.deepSummaryBtn.addEventListener('click', () => this.generateDeepSummary());
this.startQuizBtn.addEventListener('click', () => this.startQuizChallenge());
document.getElementById('closeSettings').addEventListener('click', () => this.toggleSettings());
document.getElementById('closeAchievements').addEventListener('click', () => this.toggleAchievements());
document.getElementById('closeTimer').addEventListener('click', () => this.toggleTimer());
document.getElementById('closeMoodTracker').addEventListener('click', () => this.toggleMoodTracker());
document.getElementById('closeNotification').addEventListener('click', () => this.hideNotification());
document.getElementById('closeHabits').addEventListener('click', () => this.toggleHabits());
document.getElementById('closeChallenge').addEventListener('click', () => this.toggleChallenge());
document.getElementById('addHabitBtn').addEventListener('click', () => this.addHabit());
// Settings change handlers
document.getElementById('coachType').addEventListener('change', (e) => this.updateSetting('coachType', e.target.value));
document.getElementById('intensity').addEventListener('change', (e) => this.updateSetting('intensity', e.target.value));
document.getElementById('theme').addEventListener('change', (e) => this.updateSetting('theme', e.target.value));
document.getElementById('userName').addEventListener('input', (e) => this.updateSetting('userName', e.target.value));
document.getElementById('userGoal').addEventListener('input', (e) => this.updateSetting('userGoal', e.target.value));
// Mood selector buttons
document.querySelectorAll('.mood-btn').forEach(btn => {
btn.addEventListener('click', (e) => this.selectMood(e.target));
});
// Allow Enter to submit
this.feelingInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.ctrlKey) {
e.preventDefault();
this.handleTalkToKaleshak();
}
});
}
initializeSpeech() {
this.speechSynthesis = window.speechSynthesis;
this.currentUtterance = null;
}
initializeVoiceRecognition() {
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
this.recognition = new SpeechRecognition();
this.recognition.continuous = false;
this.recognition.interimResults = false;
this.recognition.lang = 'en-IN';
this.recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
this.feelingInput.value = transcript;
this.stopVoiceInput();
};
this.recognition.onerror = () => this.stopVoiceInput();
this.recognition.onend = () => this.stopVoiceInput();
}
}
toggleVoiceInput() {
if (!this.recognition) return;
if (this.isRecording) {
this.stopVoiceInput();
} else {
this.startVoiceInput();
}
}
startVoiceInput() {
this.isRecording = true;
this.voiceBtn.classList.add('voice-recording');
this.voiceBtn.textContent = '🔴';
this.recognition.start();
}
stopVoiceInput() {
this.isRecording = false;
this.voiceBtn.classList.remove('voice-recording');
this.voiceBtn.textContent = '🎤';
if (this.recognition) this.recognition.stop();
}
toggleSettings() {
if (this.settingsPanel.classList.contains('hidden')) {
window.closeAllPanels('settingsPanel');
this.settingsPanel.classList.remove('hidden');
} else {
this.settingsPanel.classList.add('hidden');
}
}
toggleAchievements() {
if (this.achievementsPanel.classList.contains('hidden')) {
window.closeAllPanels('achievementsPanel');
this.achievementsPanel.classList.remove('hidden');
} else {
this.achievementsPanel.classList.add('hidden');
}
}
toggleTimer() {
if (this.timerPanel.classList.contains('hidden')) {
window.closeAllPanels('timerPanel');
this.timerPanel.classList.remove('hidden');
} else {
this.timerPanel.classList.add('hidden');
}
}
toggleMoodTracker() {
if (this.moodTracker.classList.contains('hidden')) {
window.closeAllPanels('moodTracker');
this.moodTracker.classList.remove('hidden');
this.updateMoodChart();
} else {
this.moodTracker.classList.add('hidden');
}
}
startTimer() {
if (!this.timer.isRunning) {
this.timer.isRunning = true;
this.timer.interval = setInterval(() => {
if (this.timer.seconds === 0) {
if (this.timer.minutes === 0) {
this.timerComplete();
return;
}
this.timer.minutes--;
this.timer.seconds = 59;
} else {
this.timer.seconds--;
}
this.updateTimerDisplay();
}, 1000);
}
}
pauseTimer() {
this.timer.isRunning = false;
clearInterval(this.timer.interval);
}
resetTimer() {
this.pauseTimer();
this.timer.minutes = 25;
this.timer.seconds = 0;
this.updateTimerDisplay();
}
updateTimerDisplay() {
const display = `${this.timer.minutes.toString().padStart(2, '0')}:${this.timer.seconds.toString().padStart(2, '0')}`;
document.getElementById('timerDisplay').textContent = display;
}
timerComplete() {
this.pauseTimer();
this.showNotification('Timer complete! Time for a break 🎉');
this.stats.sessions++;
this.updateStats();
}
showNotification(message) {
document.getElementById('notificationText').textContent = message;
this.notification.classList.remove('hidden');
setTimeout(() => this.hideNotification(), 5000);
}
hideNotification() {
this.notification.classList.add('hidden');
}
updateMoodChart() {
const canvas = document.getElementById('moodChart');
const ctx = canvas.getContext('2d');
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw mood data as simple bars
const moods = ['lazy', 'sad', 'confused', 'angry'];
const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#f9ca24'];
const barWidth = 80;
const maxHeight = 150;
moods.forEach((mood, index) => {
const count = this.moodData[mood] || 0;
const height = Math.min(count * 10, maxHeight);
const x = 50 + index * 100;
const y = canvas.height - height - 30;
ctx.fillStyle = colors[index];
ctx.fillRect(x, y, barWidth, height);
// Draw count
ctx.fillStyle = '#fff';
ctx.font = '16px Arial';
ctx.textAlign = 'center';
ctx.fillText(count.toString(), x + barWidth/2, y - 10);
});
// Update mood stats
document.getElementById('lazyCount').textContent = this.moodData.lazy;
document.getElementById('sadCount').textContent = this.moodData.sad;
document.getElementById('confusedCount').textContent = this.moodData.confused;
document.getElementById('angryCount').textContent = this.moodData.angry;
}
selectMood(btn) {
document.querySelectorAll('.mood-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
this.feelingInput.value = btn.textContent;
this.feelingInput.focus();
}
stopSpeech() {
this.speechSynthesis.cancel();
this.stopSpeechBtn.classList.add('hidden');
}
repeatSpeech() {
if (this.currentResponse) {
this.speakResponse(this.currentResponse);
}
}
loadStats() {
const saved = localStorage.getItem('kaleshak-stats');
return saved ? JSON.parse(saved) : { sessions: 0, streak: 0, lastDate: null };
}
loadSettings() {
const saved = localStorage.getItem('kaleshak-settings');
return saved ? JSON.parse(saved) : { coachType: 'default', intensity: 'medium', theme: 'dark', userName: '', userGoal: '' };
}
loadAchievements() {
const saved = localStorage.getItem('kaleshak-achievements');
return saved ? JSON.parse(saved) : [];
}
loadMoodData() {
const saved = localStorage.getItem('kaleshak-moods');
return saved ? JSON.parse(saved) : { lazy: 0, sad: 0, confused: 0, angry: 0, history: [] };
}
loadXPData() {
const saved = localStorage.getItem('kaleshak-xp');
return saved ? JSON.parse(saved) : { level: 1, xp: 0, totalXP: 0 };
}
loadHabits() {
const saved = localStorage.getItem('kaleshak-habits');
return saved ? JSON.parse(saved) : [];
}
loadChallenges() {
const saved = localStorage.getItem('kaleshak-challenges');
const today = new Date().toDateString();
const defaultChallenge = {
date: today,
text: 'Complete 3 motivation sessions today',
target: 3,
progress: 0,
type: 'sessions'
};
return saved ? JSON.parse(saved) : defaultChallenge;
}
initializeTimer() {
document.getElementById('startTimer').addEventListener('click', () => this.startTimer());
document.getElementById('pauseTimer').addEventListener('click', () => this.pauseTimer());
document.getElementById('resetTimer').addEventListener('click', () => this.resetTimer());
document.querySelectorAll('.preset-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
this.timer.minutes = parseInt(e.target.dataset.minutes);
this.timer.seconds = 0;
this.updateTimerDisplay();
});
});
}
initializeMoodTracker() {
this.updateMoodChart();
}
scheduleReminders() {
// Daily motivation reminder
setInterval(() => {
const now = new Date();
if (now.getHours() === 9 && now.getMinutes() === 0) {
this.showNotification('Time for your daily motivation session! 💪');
}
}, 60000); // Check every minute
}
initializeJarvis() {
// Wake word detection
if (this.recognition) {
this.recognition.addEventListener('result', (event) => {
const transcript = event.results[event.results.length - 1][0].transcript.toLowerCase();
if (transcript.includes('hey kaleshak') || transcript.includes('jarvis')) {
this.activateJarvis();
}
// Voice commands
if (this.jarvisMode) {
if (transcript.includes('start timer')) {
this.startTimer();
this.jarvisSpeak('Timer started');
} else if (transcript.includes('show stats')) {
this.statsSection.classList.remove('hidden');
this.jarvisSpeak('Stats displayed');
} else if (transcript.includes('change theme')) {
const themes = ['dark', 'matrix', 'fire'];
const currentIndex = themes.indexOf(this.settings.theme);
const nextTheme = themes[(currentIndex + 1) % themes.length];
this.updateSetting('theme', nextTheme);
this.jarvisSpeak(`Theme changed to ${nextTheme}`);
}
}
});
}
// Voice commands panel click
this.jarvisCommands.addEventListener('click', () => {
this.jarvisCommands.classList.add('hidden');
});
}
jarvisSpeak(text) {
const utterance = new SpeechSynthesisUtterance(text);
utterance.rate = 0.9;
utterance.pitch = 1.1;
this.speechSynthesis.speak(utterance);
}
toggleJarvis() {
this.jarvisMode = !this.jarvisMode;
if (this.jarvisMode) {
this.jarvisInterface.classList.remove('hidden');
this.jarvisCommands.classList.remove('hidden');
this.jarvisStatus.textContent = 'JARVIS Mode Active';
this.startContinuousListening();
} else {
this.jarvisInterface.classList.add('hidden');
this.jarvisCommands.classList.add('hidden');
this.stopContinuousListening();
}
}
activateJarvis() {
if (!this.jarvisMode) return;
this.jarvisOrb.classList.add('jarvis-active');
this.jarvisStatus.textContent = 'Listening...';
this.jarvisWaveform.classList.remove('hidden');
// Simulate processing
setTimeout(() => {
this.jarvisOrb.classList.remove('jarvis-active');
this.jarvisOrb.classList.add('jarvis-thinking');
this.jarvisStatus.textContent = 'Processing...';
setTimeout(() => {
this.jarvisOrb.classList.remove('jarvis-thinking');
this.jarvisStatus.textContent = 'JARVIS Ready';
this.jarvisWaveform.classList.add('hidden');
}, 1500);
}, 2000);
}
startContinuousListening() {
if (!this.recognition) return;
this.jarvisListening = true;
this.recognition.continuous = true;
this.recognition.start();
}
stopContinuousListening() {
if (!this.recognition) return;
this.jarvisListening = false;
this.recognition.continuous = false;
this.recognition.stop();
}
saveStats() {
localStorage.setItem('kaleshak-stats', JSON.stringify(this.stats));
}
saveSettings() {
localStorage.setItem('kaleshak-settings', JSON.stringify(this.settings));
}
saveAchievements() {
localStorage.setItem('kaleshak-achievements', JSON.stringify(this.achievements));
}
updateSetting(key, value) {
this.settings[key] = value;
this.saveSettings();
this.applySettings();
}
applySettings() {
// Apply theme
document.body.className = `theme-${this.settings.theme}`;
// Update UI elements
document.getElementById('coachType').value = this.settings.coachType;
document.getElementById('intensity').value = this.settings.intensity;
document.getElementById('theme').value = this.settings.theme;
document.getElementById('userName').value = this.settings.userName || '';
document.getElementById('userGoal').value = this.settings.userGoal || '';
}
updateStats() {
const today = new Date().toDateString();
if (this.stats.lastDate !== today) {
if (this.stats.lastDate === new Date(Date.now() - 86400000).toDateString()) {
this.stats.streak++;
} else {
this.stats.streak = 1;
}
this.stats.lastDate = today;
}
this.sessionCount.textContent = this.stats.sessions;
this.streakCount.textContent = this.stats.streak;
this.statsSection.classList.remove('hidden');
this.saveStats();
}
updateAchievements() {
const badges = [
{ id: 'first', name: 'First Step', icon: '🎯', condition: () => this.stats.sessions >= 1 },
{ id: 'streak3', name: '3 Day Streak', icon: '🔥', condition: () => this.stats.streak >= 3 },
{ id: 'sessions10', name: '10 Sessions', icon: '💪', condition: () => this.stats.sessions >= 10 },
{ id: 'streak7', name: 'Week Warrior', icon: '👑', condition: () => this.stats.streak >= 7 },
{ id: 'sessions50', name: 'Half Century', icon: '🏆', condition: () => this.stats.sessions >= 50 }
];
let earnedCount = 0;
const badgesList = document.getElementById('badgesList');
badgesList.innerHTML = '';
badges.forEach(badge => {
const earned = badge.condition();
if (earned && !this.achievements.includes(badge.id)) {
this.achievements.push(badge.id);
this.saveAchievements();
}
if (earned) earnedCount++;
const badgeEl = document.createElement('div');
badgeEl.className = `badge ${earned ? 'earned' : ''}`;
badgeEl.innerHTML = `
<span class="badge-icon">${badge.icon}</span>
<span class="badge-name">${badge.name}</span>
`;
badgesList.appendChild(badgeEl);
});
this.badgeCount.textContent = earnedCount;
}
async handleTalkToKaleshak() {
const query = this.feelingInput.value.trim();
if (!query) {
this.feelingInput.focus();
return;
}
this.setLoading(true);
// Hide AI result sections
this.aiSummarySection.classList.add('hidden');
this.aiQuizSection.classList.add('hidden');
this.wikiImageContainer.classList.add('hidden');
try {
// 1. Fetch from Wikipedia API
const wikiUrl = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(query)}`;
const response = await fetch(wikiUrl);
if (!response.ok) {
throw new Error('Wikipedia page not found');
}
const data = await response.json();
if (data.type === 'disambiguation') {
throw new Error('Disambiguation page');
}
const title = data.title;
const description = data.description || 'Topic overview';
const extract = data.extract;
const imageUrl = data.originalimage ? data.originalimage.source : (data.thumbnail ? data.thumbnail.source : null);
this.currentTopic = { title, description, extract, query };
// Update Wikipedia UI elements
this.wikiTitle.textContent = title;
this.wikiDesc.textContent = description;
if (imageUrl) {
this.wikiImage.src = imageUrl;
this.wikiImageContainer.classList.remove('hidden');
}
this.stats.sessions++;
this.addXP(40, `Knowledge Acquired: ${title}`);
this.updateChallengeProgress('sessions');
this.trackMood(query);
this.updateStats();
this.updateAchievements();
await this.displayAndSpeakResponse(extract);
} catch (error) {
console.log('Wikipedia direct failed, calling Jarvis Knowledge Core...', error);
// Wikipedia search failed or was disambiguated; fallback to Gemini Knowledge search!
try {
const fallbackResponse = await this.getGeminiKnowledgeResponse(query);
this.currentTopic = {
title: query.toUpperCase(),
description: 'Jarvis Knowledge Core Synthesis',
extract: fallbackResponse,
query: query
};
this.wikiTitle.textContent = query.toUpperCase();
this.wikiDesc.textContent = 'Synthesis from Jarvis Archive';
this.stats.sessions++;
this.addXP(20, `Synthesis Acquired: ${query}`);
this.updateStats();
this.updateAchievements();
await this.displayAndSpeakResponse(fallbackResponse);
} catch (geminiError) {
console.error('Gemini Knowledge also failed:', geminiError);
const fallback = "System error. Unable to connect to the knowledge core database. Please try again.";
await this.displayAndSpeakResponse(fallback);
}
}
this.setLoading(false);
}
async getGeminiKnowledgeResponse(query) {
try {
const systemPrompt = "You are the Jarvis Knowledge Core. The user wants to search for the topic: '" + query + "'. Wikipedia did not return an exact summary. Act as the ultimate knowledge command center, search your internal database, and explain this topic clearly in 4-6 sentences. Respond in standard, high-quality, informative English.";
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
feeling: `Explain the topic: ${query}`,
systemPrompt
})
});
if (!response.ok) {
throw new Error('API request failed');
}
const data = await response.json();
return data.response;
} catch (err) {
console.log("Local archive fallback for:", query);
return `System synthesized report for "${query.toUpperCase()}": This subject represents an important academic topic within the Jarvis Knowledge Core. It encompasses several foundational principles, historical achievements, and crucial relationships across scientific, technological, or cultural domains. Researchers study this topic to understand structural patterns, modern developments, and practical engineering solutions. Key elements of this subject continue to influence educational theory and technological innovations globally.`;
}
}
async generateDeepSummary() {
if (!this.currentTopic) return;
this.aiSummarySection.classList.remove('hidden');
this.aiSummaryText.innerHTML = '<div class="loading">Analyzing knowledge structure and creating AI Mindmap...</div>';
// Scroll down to the summary section
this.aiSummarySection.scrollIntoView({ behavior: 'smooth' });
try {
const systemPrompt = "You are the Jarvis Knowledge Core. Analyze the provided summary of the topic: '" + this.currentTopic.title + "'. Generate a comprehensive and gorgeous study guide. Format in clean, readable HTML using <strong>, <ul>, <li>, and <br>. Include exactly:\n1. 📊 Key Takeaways (3 high-impact bullets)\n2. 🧬 Advanced Related Concepts (3 deeper topics)\n3. 💡 Real-world Application (1 real world scenario)";
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
feeling: this.currentTopic.extract,
systemPrompt
})
});
if (!response.ok) throw new Error('API failed');
const data = await response.json();
let content = data.response;
// Basic markdown cleanup to HTML
content = content.replace(/\n/g, '<br>');
content = content.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
content = content.replace(/\* ([^*<]+)/g, '<li>$1</li>');
this.aiSummaryText.innerHTML = content;
this.addXP(30, `Analyzed Mindmap: ${this.currentTopic.title}`);
} catch (error) {
console.log("Gemini API guide generation failed, rendering high-fidelity local summary analysis...", error);
const title = this.currentTopic.title;
const desc = this.currentTopic.description || 'Topic Overview';
const extract = this.currentTopic.extract || '';
const keyTakeaways = extract.split('.').filter(s => s.trim().length > 15).slice(0, 3);
let fallbackHtml = `
<strong>📊 Key Takeaways:</strong><br>
<ul>
<li>${keyTakeaways[0] ? keyTakeaways[0].trim() : 'Primary concept exploration regarding ' + title}.</li>
<li>${keyTakeaways[1] ? keyTakeaways[1].trim() : 'Foundational knowledge base validation.'}.</li>
<li>${keyTakeaways[2] ? keyTakeaways[2].trim() : 'Important developmental impact and historical timeline.'}.</li>
</ul>
<br>
<strong>🧬 Advanced Related Concepts:</strong><br>
<ul>
<li>Quantum Synthesis of ${title}</li>
<li>Statistical Modeling of ${desc}</li>
<li>Deep Algorithmic System Architecture</li>
</ul>
<br>
<strong>💡 Real-world Application:</strong><br>
Using standard models of ${title} to analyze real-world complex networks, optimize physical systems, and educate the next generation of researchers.
`;
this.aiSummaryText.innerHTML = fallbackHtml;
this.addXP(30, `Analyzed Mindmap: ${this.currentTopic.title}`);
}
}
async startQuizChallenge() {
if (!this.currentTopic) return;
this.aiQuizSection.classList.remove('hidden');
this.quizContainer.innerHTML = '<div class="loading">Synthesizing interactive challenge questions...</div>';
// Scroll down to the quiz section
this.aiQuizSection.scrollIntoView({ behavior: 'smooth' });
try {
const systemPrompt = "You are the Jarvis Knowledge Core. Generate a multiple-choice quiz of 3 questions based on the provided Wikipedia summary of '" + this.currentTopic.title + "'. Return ONLY a valid JSON array in the following format, with NO additional text, quotes, or markdown formatting:\n[{\"question\": \"...\", \"options\": [\"A\", \"B\", \"C\", \"D\"], \"answerIndex\": 0}, ...]\nMake sure the JSON is perfectly valid and can be parsed directly by JSON.parse.";
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
feeling: this.currentTopic.extract,
systemPrompt
})
});
if (!response.ok) throw new Error('API failed');
const data = await response.json();
// Clean any markdown formatting if present
let rawResponse = data.response.trim();
if (rawResponse.startsWith('```json')) {
rawResponse = rawResponse.substring(7, rawResponse.length - 3).trim();
} else if (rawResponse.startsWith('```')) {
rawResponse = rawResponse.substring(3, rawResponse.length - 3).trim();
}
const quizData = JSON.parse(rawResponse);
this.renderQuiz(quizData);
} catch (error) {
console.log("Gemini API quiz generation failed, rendering dynamic local quiz challenge...", error);
const title = this.currentTopic.title;
const desc = this.currentTopic.description || 'Topic Overview';
const fallbackQuiz = [
{
question: `What is the primary significance of ${title}?`,
options: [
`${desc} and associated academic concepts`,
"It acts as a thermodynamic insulator in deep space",
"A mechanical subsystem in high-frequency trading",
"A traditional method of culinary preparation"
],
answerIndex: 0
},
{
question: `Which field of research is most directly concerned with ${title}?`,
options: [
"General Education, History, and Science Archives",
"Agricultural soil processing models",
"Deep-sea marine exploration algorithms",
"Fashion design and textile engineering"
],
answerIndex: 0
},
{
question: `Why is the study of ${title} critical in modern research?`,
options: [
"It provides fundamental theoretical frameworks for further investigation",
"It is used to synthesize synthetic high-durability fabrics",
"It directly controls internal combustion efficiency in turbines",
"It is the main component of global positioning units"
],
answerIndex: 0
}
];
this.renderQuiz(fallbackQuiz);
}
}
renderQuiz(quizData) {
this.quizContainer.innerHTML = '';
quizData.forEach((q, qIndex) => {
const card = document.createElement('div');
card.className = 'quiz-question-card';
card.style.marginBottom = '20px';
const questionEl = document.createElement('div');
questionEl.className = 'quiz-question';
questionEl.textContent = `${qIndex + 1}. ${q.question}`;
card.appendChild(questionEl);
const optionsContainer = document.createElement('div');
optionsContainer.className = 'quiz-options';
q.options.forEach((opt, oIndex) => {
const btn = document.createElement('button');
btn.className = 'quiz-option-btn';
btn.textContent = opt;
btn.addEventListener('click', () => {
// Prevent multiple clicks on the same question
const siblingBtns = optionsContainer.querySelectorAll('.quiz-option-btn');
siblingBtns.forEach(b => b.disabled = true);
if (oIndex === q.answerIndex) {
btn.classList.add('correct');
this.addXP(20, `Correct Quiz Answer!`);
this.showNotification('🎉 Correct answer! +20 XP');
} else {
btn.classList.add('incorrect');
siblingBtns[q.answerIndex].classList.add('correct');
this.showNotification('❌ Incorrect answer. Keep learning!');
}
});
optionsContainer.appendChild(btn);
});
card.appendChild(optionsContainer);
this.quizContainer.appendChild(card);
});
}
async displayAndSpeakResponse(response) {
this.responseSection.classList.remove('hidden');
this.responseText.innerHTML = '';
this.actionButton.classList.add('hidden');
this.stopSpeechBtn.classList.add('hidden');
this.repeatSpeechBtn.classList.add('hidden');
const lines = response.split('\n').filter(line => line.trim());
for (let i = 0; i < lines.length; i++) {
await this.displayLine(lines[i], i);
}
this.repeatSpeechBtn.classList.remove('hidden');
await this.speakResponse(response);
this.actionButton.classList.remove('hidden');
}
async speakResponse(response) {
const lines = response.split('\n').filter(line => line.trim());
this.stopSpeechBtn.classList.remove('hidden');
for (let i = 0; i < lines.length; i++) {
await this.speakLine(lines[i]);
if (i < lines.length - 1) await this.delay(800);
}
this.stopSpeechBtn.classList.add('hidden');
}
async displayLine(line, index) {
const lineElement = document.createElement('div');
lineElement.className = 'response-line';
lineElement.textContent = line;
lineElement.style.animationDelay = `${index * 0.2}s`;
this.responseText.appendChild(lineElement);
return new Promise(resolve => {
setTimeout(resolve, 300);
});
}
async speakLine(line) {
return new Promise((resolve) => {
this.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(line);
utterance.rate = 0.9;
utterance.pitch = 0.95;
utterance.volume = 1.0;
const voices = this.speechSynthesis.getVoices();
const preferredVoices = [
voice => voice.name.includes('Ravi') || voice.name.includes('Indian'),
voice => voice.lang === 'en-IN',
voice => voice.name.includes('Google') && voice.lang.startsWith('en'),
voice => voice.name.includes('Microsoft') && voice.name.includes('Natural'),
voice => voice.name.includes('Samantha') || voice.name.includes('Alex'),
voice => voice.name.includes('Premium') || voice.name.includes('Neural'),
voice => voice.lang.startsWith('en') && !voice.name.includes('eSpeak')
];
let selectedVoice = null;
for (const voiceFilter of preferredVoices) {
selectedVoice = voices.find(voiceFilter);
if (selectedVoice) break;
}
if (selectedVoice) {
utterance.voice = selectedVoice;
}
utterance.onend = resolve;
utterance.onerror = resolve;
this.currentUtterance = utterance;
this.speechSynthesis.speak(utterance);
});
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
setLoading(isLoading) {
this.talkButton.disabled = isLoading;
this.talkButton.textContent = isLoading ? 'Querying Knowledge Core...' : 'Query Knowledge Archive';
if (isLoading) {
this.responseSection.classList.remove('hidden');
this.responseText.innerHTML = '<div class="loading">Accessing archives and decrypting knowledge files...</div>';
this.wikiTitle.textContent = 'Searching...';
this.wikiDesc.textContent = 'Establishing network handshake with Wikipedia Core';
this.actionButton.classList.add('hidden');
}
}
handleActionButton() {
this.feelingInput.value = '';
this.responseSection.classList.add('hidden');
this.feelingInput.focus();
document.querySelectorAll('.mood-btn').forEach(b => b.classList.remove('active'));
this.speechSynthesis.cancel();
}
trackMood(feeling) {
const moodKeywords = {
lazy: ['lazy', 'tired', 'sleepy', 'lethargic'],
sad: ['sad', 'depressed', 'down', 'upset'],
confused: ['confused', 'lost', 'unclear', 'stuck'],
angry: ['angry', 'mad', 'frustrated', 'annoyed']
};
const lowerFeeling = feeling.toLowerCase();
for (const [mood, keywords] of Object.entries(moodKeywords)) {
if (keywords.some(keyword => lowerFeeling.includes(keyword))) {
this.moodData[mood]++;
break;
}
}
this.moodData.history.push({
date: new Date().toDateString(),
feeling: feeling
});