-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
993 lines (877 loc) · 52.3 KB
/
script.js
File metadata and controls
993 lines (877 loc) · 52.3 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
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-analytics.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut, GoogleAuthProvider, signInWithPopup, sendPasswordResetEmail } from "https://www.gstatic.com/firebasejs/10.8.1/firebase-auth.js";
const firebaseConfig = {
apiKey: "AIzaSyDhgX9WcAEQ_kgGiFFpxWVaDSDPo7-gDIQ",
authDomain: "iq-test-web-ff0cd.firebaseapp.com",
projectId: "iq-test-web-ff0cd",
storageBucket: "iq-test-web-ff0cd.firebasestorage.app",
messagingSenderId: "814260349055",
appId: "1:814260349055:web:de102a540551aa7950b74a",
measurementId: "G-5N03TMBFRD"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth(app);
// --- 1. Audio & Haptic Engine ---
const AudioContext = window.AudioContext || window.webkitAudioContext;
let audioCtx;
const SoundEngine = {
init: function() {
if (!audioCtx) audioCtx = new AudioContext();
if (audioCtx.state === 'suspended') audioCtx.resume();
},
playTone: function(freq, type, duration, vol=0.1) {
if (!audioCtx) return;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
gain.gain.setValueAtTime(vol, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + duration);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start();
osc.stop(audioCtx.currentTime + duration);
},
pop: function() { this.playTone(400, 'sine', 0.1, 0.15); },
chime: function() {
this.playTone(800, 'triangle', 0.3, 0.1);
setTimeout(() => this.playTone(1200, 'triangle', 0.4, 0.1), 100);
},
buzz: function() { this.playTone(150, 'sawtooth', 0.3, 0.2); },
victory: function() {
[523.25, 659.25, 783.99, 1046.50].forEach((freq, i) => { // C Major Arpeggio
setTimeout(() => this.playTone(freq, 'sine', 0.4, 0.15), i * 150);
});
},
vibrate: function(pattern) {
if (navigator.vibrate) navigator.vibrate(pattern);
}
};
// --- 2. Localization Dictionary ---
const uiTranslations = {
en: {
welcomeBack: "Welcome Back", loginToContinue: "Log in to continue your IQ journey",
loginBtn: "Log In", or: "OR", continueGoogle: "Continue with Google",
noAccount: "Don't have an account?", signUpLink: "Sign up", acceptBtn: "Accept & Continue",
endTest: "End Test", logout: "Logout", yourHighScore: "Your High Score:",
chooseChallenge: "Choose your challenge level and the number of questions.",
difficulty: "Difficulty Level:", beginner: "Beginner", intermediate: "Intermediate", advanced: "Advanced",
category: "Category:", allCategories: "All Categories", numQuestions: "Number of Questions:",
gameMode: "Game Mode:", modeStandard: "Standard (20s / question)", modeZen: "Zen (No timer)", modeSprint: "Sprint (5 min, unlimited)",
startTest: "Start Test", testComplete: "Test Complete!",
simulatedScore: "Your Simulated IQ Score", restartTest: "Restart Test",
wait: "Please wait...", createAccount: "Create Account", signupText: "Sign up to start tracking your IQ scores",
alreadyAccount: "Already have an account?", loginLink: "Log in",
adaptive: "Adaptive", reviewAnswers: "Review Incorrect Answers",
cat_math: "Math", cat_logic: "Logic", cat_general: "General", cat_science: "Science", cat_history: "History", cat_geography: "Geography", cat_arts: "Arts", cat_sociology: "Sociology", cat_philosophy: "Philosophy", cat_economics: "Economics",
alert_pwdMatch: "Passwords do not match.", alert_regSuccess: "Registration successful!", alert_enterEmail: "Please enter your email address first to reset your password.", alert_resetSent: "Password reset email sent! Check your inbox.", alert_logoutSuccess: "Thank you for using IQ Master! You have been successfully logged out.", alert_acceptTnc: "You must accept the Terms & Conditions to use IQ Master.",
confirm_langChange: "Language changed. Do you want to restart the test to apply the new language to the questions?", confirm_endTest: "Are you sure you want to end the test? Your progress will be lost.",
feedback_perfect: "Perfect! You're a logical genius!", feedback_great: "Great job! You have very strong cognitive skills.", feedback_good: "Good effort, but there's room for improvement.", feedback_keepPracticing: "Keep practicing! Logic puzzles take time and repetition.",
score_earned: "You earned <strong>{0}</strong> points out of a possible {1} ({2}%).", score_simulated: "*This is a simulated score for entertainment purposes.", ans_timeout: "No answer (Timeout)", exp_default: "The correct logical deduction leads to {0}. Review this specific concept to improve your accuracy in future tests.", prog_points: "Points: ", prog_question: "Question {0} of {1}", q_label: "Q:", your_ans: "Your Answer:", correct_ans: "Correct Answer:"
},
es: {
welcomeBack: "Bienvenido", loginToContinue: "Inicia sesión para continuar",
loginBtn: "Iniciar sesión", or: "O", continueGoogle: "Continuar con Google",
noAccount: "¿No tienes cuenta?", signUpLink: "Regístrate", acceptBtn: "Aceptar y continuar",
endTest: "Terminar prueba", logout: "Cerrar sesión", yourHighScore: "Tu puntuación más alta:",
chooseChallenge: "Elige tu nivel de desafío y el número de preguntas.",
difficulty: "Nivel de dificultad:", beginner: "Principiante", intermediate: "Intermedio", advanced: "Avanzado",
category: "Categoría:", allCategories: "Todas las categorías", numQuestions: "Número de preguntas:",
gameMode: "Modo de juego:", modeStandard: "Estándar", modeZen: "Modo Zen", modeSprint: "Sprint (5 min)",
startTest: "Empezar prueba", testComplete: "¡Prueba completada!",
simulatedScore: "Tu coeficiente intelectual simulado", restartTest: "Reiniciar prueba",
wait: "Por favor espera...", createAccount: "Crear cuenta", signupText: "Regístrate para rastrear tus puntajes",
alreadyAccount: "¿Ya tienes cuenta?", loginLink: "Inicia sesión",
adaptive: "Adaptativo", reviewAnswers: "Revisar respuestas incorrectas",
cat_math: "Matemáticas", cat_logic: "Lógica", cat_general: "General", cat_science: "Ciencia", cat_history: "Historia", cat_geography: "Geografía", cat_arts: "Artes", cat_sociology: "Sociología", cat_philosophy: "Filosofía", cat_economics: "Economía",
alert_pwdMatch: "Las contraseñas no coinciden.", alert_regSuccess: "¡Registro exitoso!", alert_enterEmail: "Ingrese su correo electrónico para restablecer su contraseña.", alert_resetSent: "¡Correo de restablecimiento enviado! Revise su bandeja de entrada.", alert_logoutSuccess: "¡Gracias por usar IQ Master! Has cerrado sesión exitosamente.", alert_acceptTnc: "Debes aceptar los Términos y Condiciones para usar IQ Master.",
confirm_langChange: "Idioma cambiado. ¿Deseas reiniciar la prueba para aplicar el nuevo idioma a las preguntas?", confirm_endTest: "¿Estás seguro de que quieres terminar la prueba? Perderás tu progreso.",
feedback_perfect: "¡Perfecto! ¡Eres un genio lógico!", feedback_great: "¡Gran trabajo! Tienes habilidades cognitivas muy fuertes.", feedback_good: "Buen esfuerzo, pero hay margen de mejora.", feedback_keepPracticing: "¡Sigue practicando! Los acertijos lógicos requieren tiempo.",
score_earned: "Ganaste <strong>{0}</strong> puntos de {1} posibles ({2}%).", score_simulated: "*Esta es una puntuación simulada con fines de entretenimiento.", ans_timeout: "Sin respuesta (Tiempo agotado)", exp_default: "La deducción lógica correcta lleva a {0}. Revisa este concepto para mejorar en futuras pruebas.", prog_points: "Puntos: ", prog_question: "Pregunta {0} de {1}", q_label: "P:", your_ans: "Tu respuesta:", correct_ans: "Respuesta correcta:"
},
fr: {
welcomeBack: "Bon retour", loginToContinue: "Connectez-vous pour continuer",
loginBtn: "Connexion", or: "OU", continueGoogle: "Continuer avec Google",
noAccount: "Pas de compte ?", signUpLink: "S'inscrire", acceptBtn: "Accepter et continuer",
endTest: "Terminer le test", logout: "Déconnexion", yourHighScore: "Votre meilleur score :",
chooseChallenge: "Choisissez votre niveau et le nombre de questions.",
difficulty: "Niveau de difficulté :", beginner: "Débutant", intermediate: "Intermédiaire", advanced: "Avancé",
category: "Catégorie :", allCategories: "Toutes les catégories", numQuestions: "Nombre de questions :",
gameMode: "Mode de jeu :", modeStandard: "Standard", modeZen: "Zen", modeSprint: "Sprint (5 min)",
startTest: "Commencer le test", testComplete: "Test terminé !",
simulatedScore: "Votre QI simulé", restartTest: "Recommencer",
wait: "Veuillez patienter...", createAccount: "Créer un compte", signupText: "Inscrivez-vous pour suivre vos scores",
alreadyAccount: "Déjà un compte ?", loginLink: "Connexion",
adaptive: "Adaptatif", reviewAnswers: "Revoir les mauvaises réponses",
cat_math: "Mathématiques", cat_logic: "Logique", cat_general: "Général", cat_science: "Science", cat_history: "Histoire", cat_geography: "Géographie", cat_arts: "Arts", cat_sociology: "Sociologie", cat_philosophy: "Philosophie", cat_economics: "Économie",
alert_pwdMatch: "Les mots de passe ne correspondent pas.", alert_regSuccess: "Inscription réussie !", alert_enterEmail: "Veuillez entrer votre e-mail pour réinitialiser votre mot de passe.", alert_resetSent: "E-mail de réinitialisation envoyé ! Vérifiez votre boîte de réception.", alert_logoutSuccess: "Merci d'utiliser IQ Master ! Vous avez été déconnecté avec succès.", alert_acceptTnc: "Vous devez accepter les conditions générales pour utiliser IQ Master.",
confirm_langChange: "Langue modifiée. Voulez-vous recommencer le test pour appliquer la nouvelle langue aux questions ?", confirm_endTest: "Êtes-vous sûr de vouloir terminer le test ? Votre progression sera perdue.",
feedback_perfect: "Parfait ! Vous êtes un génie de la logique !", feedback_great: "Bon travail ! Vous avez de très fortes compétences cognitives.", feedback_good: "Bel effort, mais il y a place à l'amélioration.", feedback_keepPracticing: "Continuez à vous entraîner ! Les énigmes logiques demandent du temps.",
score_earned: "Vous avez obtenu <strong>{0}</strong> points sur un possible de {1} ({2}%).", score_simulated: "*Il s'agit d'un score simulé à des fins de divertissement.", ans_timeout: "Pas de réponse (Délai écoulé)", exp_default: "La déduction logique correcte mène à {0}. Révisez ce concept pour améliorer votre précision.", prog_points: "Points : ", prog_question: "Question {0} sur {1}", q_label: "Q :", your_ans: "Votre réponse :", correct_ans: "Bonne réponse :"
},
hi: {
welcomeBack: "वापसी पर स्वागत है", loginToContinue: "जारी रखने के लिए लॉगिन करें",
loginBtn: "लॉग इन करें", or: "या", continueGoogle: "Google के साथ जारी रखें",
noAccount: "खाता नहीं है?", signUpLink: "साइन अप करें", acceptBtn: "स्वीकार करें",
endTest: "टेस्ट समाप्त करें", logout: "लॉग आउट", yourHighScore: "आपका उच्चतम स्कोर:",
chooseChallenge: "अपना चुनौती स्तर और प्रश्नों की संख्या चुनें।",
difficulty: "कठिनाई स्तर:", beginner: "शुरुआती", intermediate: "माध्यमिक", advanced: "उन्नत",
category: "श्रेणी:", allCategories: "सभी श्रेणियाँ", numQuestions: "प्रश्नों की संख्या:",
gameMode: "गेम मोड:", modeStandard: "मानक", modeZen: "ज़ेन", modeSprint: "स्प्रिंट (5 मिनट)",
startTest: "टेस्ट शुरू करें", testComplete: "टेस्ट पूरा हुआ!",
simulatedScore: "आपका अनुमानित IQ", restartTest: "फिर से शुरू करें",
wait: "कृपया प्रतीक्षा करें...", createAccount: "खाता बनाएं", signupText: "स्कोर ट्रैक करने के लिए साइन अप करें",
alreadyAccount: "क्या आपके पास पहले से खाता है?", loginLink: "लॉग इन करें",
adaptive: "अनुकूली", reviewAnswers: "गलत उत्तरों की समीक्षा करें",
cat_math: "गणित", cat_logic: "तर्क", cat_general: "सामान्य", cat_science: "विज्ञान", cat_history: "इतिहास", cat_geography: "भूगोल", cat_arts: "कला", cat_sociology: "समाजशास्त्र", cat_philosophy: "दर्शनशास्त्र", cat_economics: "अर्थशास्त्र",
alert_pwdMatch: "पासवर्ड मेल नहीं खाते।", alert_regSuccess: "पंजीकरण सफल!", alert_enterEmail: "पासवर्ड रीसेट करने के लिए कृपया पहले अपना ईमेल पता दर्ज करें।", alert_resetSent: "पासवर्ड रीसेट ईमेल भेज दिया गया! अपना इनबॉक्स जांचें।", alert_logoutSuccess: "IQ Master का उपयोग करने के लिए धन्यवाद! आप सफलतापूर्वक लॉग आउट हो गए हैं।", alert_acceptTnc: "IQ Master का उपयोग करने के लिए आपको नियम और शर्तें स्वीकार करनी होंगी।",
confirm_langChange: "भाषा बदल गई। क्या आप प्रश्नों पर नई भाषा लागू करने के लिए परीक्षण को फिर से शुरू करना चाहते हैं?", confirm_endTest: "क्या आप वाकई परीक्षण समाप्त करना चाहते हैं? आपकी प्रगति नष्ट हो जाएगी।",
feedback_perfect: "बिल्कुल सही! आप एक तार्किक प्रतिभाशाली हैं!", feedback_great: "बहुत बढ़िया! आपके पास बहुत मजबूत संज्ञानात्मक कौशल हैं।", feedback_good: "अच्छा प्रयास, लेकिन सुधार की गुंजाइश है।", feedback_keepPracticing: "अभ्यास करते रहें! तर्क पहेली में समय और दोहराव लगता है।",
score_earned: "आपने संभावित {1} में से <strong>{0}</strong> अंक अर्जित किए ({2}%)।", score_simulated: "*यह मनोरंजन के उद्देश्य से एक सिम्युलेटेड स्कोर है।", ans_timeout: "कोई उत्तर नहीं (समय समाप्त)", exp_default: "सही तार्किक निष्कर्ष {0} की ओर ले जाता है। भविष्य में अपनी सटीकता में सुधार के लिए इसकी समीक्षा करें।", prog_points: "अंक: ", prog_question: "प्रश्न {0} / {1}", q_label: "प्रश्न:", your_ans: "आपका उत्तर:", correct_ans: "सही उत्तर:"
},
mr: {
welcomeBack: "पुन्हा स्वागत आहे", loginToContinue: "सुरू ठेवण्यासाठी लॉग इन करा",
loginBtn: "लॉग इन करा", or: "किंवा", continueGoogle: "Google सह सुरू ठेवा",
noAccount: "खाते नाही?", signUpLink: "साइन अप करा", acceptBtn: "स्वीकारा आणि पुढे जा",
endTest: "चाचणी समाप्त करा", logout: "लॉग आउट", yourHighScore: "तुमचा सर्वोच्च स्कोअर:",
chooseChallenge: "तुमची आव्हान पातळी आणि प्रश्नांची संख्या निवडा.",
difficulty: "कठिण पातळी:", beginner: "नवशिक्या", intermediate: "मध्यम", advanced: "प्रगत",
category: "श्रेणी:", allCategories: "सर्व श्रेणी", numQuestions: "प्रश्नांची संख्या:",
gameMode: "गेम मोड:", modeStandard: "प्रमाणित", modeZen: "झेन", modeSprint: "स्प्रिंट (५ मि)",
startTest: "चाचणी सुरू करा", testComplete: "चाचणी पूर्ण झाली!",
simulatedScore: "तुमचा अंदाजित IQ", restartTest: "पुन्हा सुरू करा",
wait: "कृपया प्रतीक्षा करा...", createAccount: "खाते तयार करा", signupText: "स्कोअर ट्रॅक करण्यासाठी साइन अप करा",
alreadyAccount: "तुमचे आधीच खाते आहे का?", loginLink: "लॉग इन करा",
adaptive: "अनुकूली", reviewAnswers: "चुकीच्या उत्तरांचे पुनरावलोकन करा",
cat_math: "गणित", cat_logic: "तर्क", cat_general: "सामान्य", cat_science: "विज्ञान", cat_history: "इतिहास", cat_geography: "भूगोल", cat_arts: "कला", cat_sociology: "समाजशास्त्र", cat_philosophy: "तत्त्वज्ञान", cat_economics: "अर्थशास्त्र",
alert_pwdMatch: "पासवर्ड जुळत नाहीत.", alert_regSuccess: "नोंदणी यशस्वी!", alert_enterEmail: "पासवर्ड रीसेट करण्यासाठी कृपया प्रथम तुमचा ईमेल पत्ता प्रविष्ट करा.", alert_resetSent: "पासवर्ड रीसेट ईमेल पाठवला! तुमचा इनबॉक्स तपासा.", alert_logoutSuccess: "IQ Master वापरल्याबद्दल धन्यवाद! तुम्ही यशस्वीरित्या लॉग आउट झाला आहात.", alert_acceptTnc: "IQ Master वापरण्यासाठी तुम्हाला नियम आणि अटी स्वीकारणे आवश्यक आहे.",
confirm_langChange: "भाषा बदलली. प्रश्नांवर नवीन भाषा लागू करण्यासाठी तुम्हाला चाचणी पुन्हा सुरू करायची आहे का?", confirm_endTest: "तुम्हाला नक्की चाचणी संपवायची आहे का? तुमची प्रगती नष्ट होईल.",
feedback_perfect: "परिपूर्ण! तुम्ही एक तार्किक نابغه आहात!", feedback_great: "उत्तम काम! तुमच्याकडे खूप मजबूत संज्ञानात्मक कौशल्ये आहेत.", feedback_good: "चांगला प्रयत्न, पण सुधारणेला वाव आहे.", feedback_keepPracticing: "सराव करत राहा! तर्क कोडी सोडवण्यासाठी वेळ आणि पुनरावृत्ती लागते.",
score_earned: "तुम्ही शक्य असलेल्या {1} पैकी <strong>{0}</strong> गुण मिळवले ({2}%).", score_simulated: "*हे मनोरंजनाच्या उद्देशाने एक सिम्युलेटेड स्कोअर आहे.", ans_timeout: "उत्तर नाही (वेळ संपली)", exp_default: "योग्य तार्किक निष्कर्ष {0} कडे नेतो. भविष्यातील चाचण्यांमध्ये तुमची अचूकता सुधारण्यासाठी या संकल्पनेचे पुनरावलोकन करा.", prog_points: "गुण: ", prog_question: "प्रश्न {0} / {1}", q_label: "प्र:", your_ans: "तुमचे उत्तर:", correct_ans: "बरोबर उत्तर:"
}
};
let baseQuestionBank = {};
let questionBank = {};
// 4. State Variables
let currentLang = 'en';
let currentIndex = 0;
let currentTestQuestions = [];
let answerLog = []; // To store { question, correct: true/false }
let questionTimerInterval = null; // To hold the timer's interval ID
// Sprint & Adaptive Mechanics Variables
let gameMode = 'standard';
let globalTimeLeft = 300; // 5 minutes
let globalTimerInterval = null;
let isAdaptive = false;
let adaptiveStreak = 0;
let currentDifficulty = 'beginner';
let weightedScore = 0;
let maxPossibleScore = 0;
let questionPools = { beginner: [], intermediate: [], advanced: [] };
let targetQuestionCount = 10;
// --- True Randomization Shuffle (Fisher-Yates) ---
function shuffleArray(array) {
let curId = array.length;
while (0 !== curId) {
let randId = Math.floor(Math.random() * curId);
curId -= 1;
let tmp = array[curId];
array[curId] = array[randId];
array[randId] = tmp;
}
return array;
}
// Constants
const TIME_PER_QUESTION = 20; // Seconds
const SPRINT_TIME = 300; // 5 minutes
const HIGH_SCORE_KEY = 'iqQuizHighScore';
const THEME_KEY = 'iqQuizTheme';
// 3. DOM Elements
const questionTextElement = document.getElementById("question-text");
const questionImageElement = document.getElementById("question-image");
const optionsContainer = document.getElementById("options-container");
const progressText = document.getElementById("progress-text");
const progressFill = document.getElementById("progress-fill");
const quizHeaderInfo = document.getElementById("quiz-header-info");
const configArea = document.getElementById("config-area");
const startBtn = document.getElementById("start-btn");
const quizArea = document.getElementById("quiz-area");
const resultArea = document.getElementById("result-area");
const scoreText = document.getElementById("score-text");
const restartBtn = document.getElementById("restart-btn");
const terminateBtn = document.getElementById("terminate-btn");
const iqScoreValue = document.getElementById("iq-score-value");
const resultsGraphContainer = document.getElementById("results-graph-container");
const explanationsContainer = document.getElementById("explanations-container");
const explanationsList = document.getElementById("explanations-list");
const timerText = document.getElementById("timer-text");
const timerContainer = document.getElementById("timer-container");
const highScoreDisplay = document.getElementById("high-score-display");
const questionCountSelect = document.getElementById('question-count');
const categorySelection = document.getElementById('category-selection');
const gameModeSelect = document.getElementById('game-mode');
const themeToggle = document.getElementById('theme-toggle');
const languageSelect = document.getElementById('language-select');
const authContainer = document.getElementById('auth-container');
const tncContainer = document.getElementById('tnc-container');
const tncCheckbox = document.getElementById('tnc-checkbox');
const tncAcceptBtn = document.getElementById('tnc-accept-btn');
const tncDeclineBtn = document.getElementById('tnc-decline-btn');
const mainAppContainer = document.getElementById('main-app-container');
const authForm = document.getElementById('auth-form');
const authEmail = document.getElementById('auth-email');
const authPassword = document.getElementById('auth-password');
const authConfirmPassword = document.getElementById('auth-confirm-password');
const confirmPasswordGroup = document.getElementById('confirm-password-group');
const authSubmitBtn = document.getElementById('auth-submit-btn');
const forgotPasswordContainer = document.getElementById('forgot-password-container');
const forgotPasswordLink = document.getElementById('forgot-password-link');
const userInfoDisplay = document.getElementById('user-info-display');
const authSwitchLink = document.getElementById('auth-switch-link');
const authSwitchText = document.getElementById('auth-switch-text');
const authTitle = document.getElementById('auth-title');
const authSubtitle = document.getElementById('auth-subtitle');
const googleLoginBtn = document.getElementById('google-login-btn');
const authMessage = document.getElementById('auth-message');
const logoutBtn = document.getElementById('logout-btn');
const body = document.body;
// 5. Core Functions
function generateAndStartQuiz() {
SoundEngine.init();
const level = document.querySelector('input[name="level"]:checked').value;
const selectedCategory = categorySelection.value;
gameMode = gameModeSelect.value;
targetQuestionCount = gameMode === 'sprint' ? Infinity : parseInt(questionCountSelect.value);
// Reset Adaptive pools & mechanics
questionPools = { beginner: [], intermediate: [], advanced: [] };
isAdaptive = level === 'adaptive';
adaptiveStreak = 0;
currentDifficulty = isAdaptive ? 'intermediate' : level; // Start adaptive in the middle
// Populate the drawing pools
if (isAdaptive) {
['beginner', 'intermediate', 'advanced'].forEach(diff => fillPool(diff, selectedCategory));
} else {
fillPool(level, selectedCategory);
}
weightedScore = 0;
maxPossibleScore = 0;
currentIndex = 0;
currentTestQuestions = [];
answerLog = [];
// Hide config screen, show quiz elements
configArea.classList.add("hidden");
quizArea.classList.remove("hidden");
quizHeaderInfo.classList.remove("hidden");
terminateBtn.classList.remove("hidden");
clearInterval(globalTimerInterval);
if (gameMode === 'sprint') {
timerContainer.classList.remove('hidden');
startSprintTimer();
} else if (gameMode === 'zen') {
timerContainer.classList.add('hidden');
} else {
timerContainer.classList.remove('hidden');
}
loadQuestion();
}
function fillPool(diff, cat) {
let langObj = questionBank[currentLang] || questionBank['en'];
let langLevel = langObj[diff] || {};
let enLevel = questionBank['en'][diff] || {};
let available = [];
if (cat === 'all') {
const allCats = new Set([...Object.keys(langLevel), ...Object.keys(enLevel)]);
allCats.forEach(c => {
if (langLevel[c] && langLevel[c].length > 0) available.push(...langLevel[c]);
else if (enLevel[c]) available.push(...enLevel[c]);
});
} else {
if (langLevel[cat] && langLevel[cat].length > 0) available.push(...langLevel[cat]);
else if (enLevel[cat]) available.push(...enLevel[cat]);
}
// Map them with a difficulty property for weighted scoring and properly shuffle
// We also make a deep copy so we don't accidentally mutate the bank
let mappedQuestions = available.map(q => ({ ...q, difficulty: diff, o: [...q.o] }));
questionPools[diff] = shuffleArray(mappedQuestions);
}
function getNextQuestion() {
let pool = questionPools[currentDifficulty];
if (pool.length === 0) {
// If empty, downgrade or upgrade
if (questionPools['intermediate'].length > 0) currentDifficulty = 'intermediate';
else if (questionPools['advanced'].length > 0) currentDifficulty = 'advanced';
else if (questionPools['beginner'].length > 0) currentDifficulty = 'beginner';
else return null; // Complete exhaustion
pool = questionPools[currentDifficulty];
}
return pool.pop(); // Take last since it's already shuffled
}
function getWeight(diff) {
if (diff === 'advanced') return 3;
if (diff === 'intermediate') return 2;
return 1;
}
function formatTime(seconds) {
if (gameMode !== 'sprint') return seconds;
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}:${s < 10 ? '0' : ''}${s}`;
}
function startSprintTimer() {
globalTimeLeft = SPRINT_TIME;
timerText.textContent = formatTime(globalTimeLeft);
timerText.style.color = 'var(--text-secondary)';
timerContainer.classList.remove('timer-low');
globalTimerInterval = setInterval(() => {
globalTimeLeft--;
timerText.textContent = formatTime(globalTimeLeft);
if (globalTimeLeft <= 15) {
timerText.style.color = 'var(--error-color)';
timerContainer.classList.add('timer-low');
}
if (globalTimeLeft <= 0) {
clearInterval(globalTimerInterval);
showResults();
}
}, 1000);
}
function startTimer() {
let timeLeft = TIME_PER_QUESTION;
timerText.textContent = formatTime(timeLeft);
timerText.style.color = 'var(--text-secondary)'; // Reset color
timerContainer.classList.remove('timer-low'); // Reset pulse animation
questionTimerInterval = setInterval(() => {
timeLeft--;
timerText.textContent = formatTime(timeLeft);
if (timeLeft <= 5) {
timerText.style.color = 'var(--error-color)'; // Red color for urgency
timerContainer.classList.add('timer-low');
}
if (timeLeft <= 0) {
clearInterval(questionTimerInterval);
handleTimeout();
}
}, 1000);
}
function handleTimeout() {
// Treat timeout as an incorrect answer without selecting anything
handleAnswer(null, null);
}
function loadQuestion() {
const dict = uiTranslations[currentLang] || uiTranslations['en'];
if (currentIndex >= targetQuestionCount && gameMode !== 'sprint') {
showResults();
return;
}
const nextQuestion = getNextQuestion();
if (!nextQuestion) {
showResults(); // Pool exhausted
return;
}
currentTestQuestions[currentIndex] = nextQuestion;
// Clear previous timer and start a new one
clearInterval(questionTimerInterval);
if (gameMode === 'standard') {
startTimer();
}
const currentQuestion = currentTestQuestions[currentIndex];
// Update text elements
questionTextElement.textContent = currentQuestion.q;
if (currentQuestion.img) {
questionImageElement.src = currentQuestion.img;
questionImageElement.classList.remove('hidden');
} else {
questionImageElement.classList.add('hidden');
questionImageElement.src = "";
}
progressText.textContent = gameMode === 'sprint' ? `${dict.prog_points}${weightedScore}` : dict.prog_question.replace('{0}', currentIndex + 1).replace('{1}', targetQuestionCount);
// Update the visual progress bar width
const progressPercentage = gameMode === 'sprint' ? ((SPRINT_TIME - globalTimeLeft) / SPRINT_TIME) * 100 : (currentIndex / targetQuestionCount) * 100;
progressFill.style.width = `${progressPercentage}%`;
// Clear out old options from the previous question
optionsContainer.innerHTML = "";
optionsContainer.classList.remove("options-disabled"); // Re-enable clicks
// Generate new buttons for the current question
let randomizedOptions = shuffleArray([...currentQuestion.o]); // clone and shuffle
randomizedOptions.forEach(option => {
const button = document.createElement("button");
button.textContent = option;
button.classList.add("option-btn");
// Store the value as a dataset attribute for easier validation later
button.dataset.value = option;
// When clicked, check the answer
button.addEventListener("click", () => {
SoundEngine.pop();
SoundEngine.vibrate(30);
handleAnswer(option, button);
});
optionsContainer.appendChild(button);
});
}
function handleAnswer(selectedOption, selectedButton) {
const dict = uiTranslations[currentLang] || uiTranslations['en'];
// Stop the timer as soon as an answer is given or time runs out
clearInterval(questionTimerInterval);
const currentQuestion = currentTestQuestions[currentIndex];
// Disable further clicking until the next question loads
optionsContainer.classList.add("options-disabled");
// Find the button that contains the correct answer
const allButtons = optionsContainer.querySelectorAll(".option-btn");
let correctButton = null;
allButtons.forEach(btn => {
if (btn.dataset.value === currentQuestion.a) {
correctButton = btn;
}
});
// Check answer (if an option was selected) and log result for the graph
const isCorrect = selectedOption === currentQuestion.a;
answerLog.push({
question: currentQuestion.q,
correct: isCorrect,
userAnswer: selectedOption || dict.ans_timeout,
correctAnswer: currentQuestion.a,
explanation: currentQuestion.exp || dict.exp_default.replace('{0}', currentQuestion.a)
});
const qWeight = getWeight(currentQuestion.difficulty);
maxPossibleScore += qWeight;
if (isCorrect) {
weightedScore += qWeight;
if (isAdaptive) {
adaptiveStreak++;
if (adaptiveStreak >= 2) {
if (currentDifficulty === 'beginner') currentDifficulty = 'intermediate';
else if (currentDifficulty === 'intermediate') currentDifficulty = 'advanced';
adaptiveStreak = 0;
}
}
if (selectedButton) {
selectedButton.classList.add("correct");
mainAppContainer.classList.add("screen-flash-correct");
SoundEngine.chime();
SoundEngine.vibrate([50, 50, 50]);
}
} else {
if (isAdaptive) {
if (currentDifficulty === 'advanced') currentDifficulty = 'intermediate';
else if (currentDifficulty === 'intermediate') currentDifficulty = 'beginner';
adaptiveStreak = 0;
}
if (selectedButton) {
selectedButton.classList.add("incorrect");
mainAppContainer.classList.add("screen-shake-incorrect");
SoundEngine.buzz();
SoundEngine.vibrate(200);
}
// Always show the correct answer, even on timeout
if (correctButton) correctButton.classList.add("correct");
}
currentIndex++;
// Wait 1.5 seconds before moving on so the user sees the visual feedback
setTimeout(() => {
mainAppContainer.classList.remove("screen-flash-correct", "screen-shake-incorrect");
// In sprint mode, if global timer died during the 1.5s delay, we shouldn't load another
if (gameMode === 'sprint' && globalTimeLeft <= 0) return;
loadQuestion();
}, 1500);
}
function calculateAndDisplayIQ(achieved, possible) {
if (possible === 0) {
iqScoreValue.textContent = "N/A";
return 0;
}
const percentage = (achieved / possible);
// This is a simplified, non-clinical mapping of percentage to an IQ-like scale (70-150)
const simulatedIQ = Math.round(70 + (percentage * 80));
iqScoreValue.textContent = simulatedIQ;
return simulatedIQ;
}
function updateHighScore(newScore) {
const currentHighScore = parseInt(localStorage.getItem(HIGH_SCORE_KEY)) || 0;
if (newScore > currentHighScore) {
localStorage.setItem(HIGH_SCORE_KEY, newScore);
displayHighScore();
}
}
function fireConfetti() {
const colors = ['#8b5cf6', '#06b6d4', '#10b981', '#ef4444', '#f59e0b'];
for(let i=0; i<80; i++) {
let conf = document.createElement('div');
conf.classList.add('confetti-piece');
conf.style.left = Math.random() * 100 + 'vw';
conf.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
conf.style.animation = `confettiFall ${Math.random() * 3 + 2}s linear forwards`;
conf.style.animationDelay = `${Math.random() * 1.5}s`;
document.body.appendChild(conf);
setTimeout(() => conf.remove(), 5000);
}
}
function renderResultsGraph() {
resultsGraphContainer.innerHTML = ""; // Clear previous graph
answerLog.forEach(log => {
const bar = document.createElement("div");
bar.classList.add("result-bar");
bar.classList.add(log.correct ? "correct" : "incorrect");
bar.title = `Q: ${log.question}\nAnswer: ${log.correct ? 'Correct' : 'Incorrect'}`;
resultsGraphContainer.appendChild(bar);
});
}
function showResults() {
const dict = uiTranslations[currentLang] || uiTranslations['en'];
// Swap visibility of main areas
clearInterval(questionTimerInterval); // Ensure timer is stopped
clearInterval(globalTimerInterval);
quizArea.classList.add("hidden");
quizHeaderInfo.classList.add("hidden");
terminateBtn.classList.add("hidden");
resultArea.classList.remove("hidden");
// Calculate and show simulated IQ
const finalIQ = calculateAndDisplayIQ(weightedScore, maxPossibleScore);
updateHighScore(finalIQ);
SoundEngine.victory();
if(weightedScore > 0) fireConfetti();
// Display final score
const percentage = maxPossibleScore > 0 ? Math.round((weightedScore / maxPossibleScore) * 100) : 0;
let feedbackText = "";
if (percentage === 100) feedbackText = dict.feedback_perfect;
else if (percentage >= 75) feedbackText = dict.feedback_great;
else if (percentage >= 50) feedbackText = dict.feedback_good;
else feedbackText = dict.feedback_keepPracticing;
scoreText.innerHTML = `${dict.score_earned.replace('{0}', weightedScore).replace('{1}', maxPossibleScore).replace('{2}', percentage)}<br><br>${feedbackText}<br><small>${dict.score_simulated}</small>`;
// Render the visual graph of answers
renderResultsGraph();
// Render explanations for incorrect answers
explanationsList.innerHTML = "";
let hasIncorrect = false;
answerLog.forEach(log => {
if (!log.correct) {
hasIncorrect = true;
const card = document.createElement("div");
card.classList.add("explanation-card");
card.innerHTML = `
<p><strong>${dict.q_label}</strong> ${log.question}</p>
<p><strong>${dict.your_ans}</strong> <span style="color: var(--error-color);">${log.userAnswer}</span></p>
<p><strong>${dict.correct_ans}</strong> <span style="color: var(--success-color);">${log.correctAnswer}</span></p>
<p class="exp-text">${log.explanation}</p>
`;
explanationsList.appendChild(card);
}
});
if (hasIncorrect) explanationsContainer.classList.remove("hidden");
else explanationsContainer.classList.add("hidden");
}
function applyTheme(theme) {
if (theme === 'light') {
body.classList.add('light-mode');
themeToggle.checked = true;
} else {
body.classList.remove('light-mode');
themeToggle.checked = false;
}
}
function toggleTheme() {
const newTheme = body.classList.contains('light-mode') ? 'dark' : 'light';
localStorage.setItem(THEME_KEY, newTheme);
applyTheme(newTheme);
}
function loadInitialTheme() {
const savedTheme = localStorage.getItem(THEME_KEY);
// Check system preference as a fallback, otherwise default to dark
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const defaultTheme = systemPrefersDark ? 'dark' : 'light';
applyTheme(savedTheme || defaultTheme);
}
function populateCategories() {
const dict = uiTranslations[currentLang] || uiTranslations['en'];
categorySelection.innerHTML = `<option value="all" data-i18n="allCategories">${dict.allCategories || "All Categories"}</option>`;
const allCategories = new Set();
Object.values(questionBank['en']).forEach(level => { // Use EN as base source of truth for categories
Object.keys(level).forEach(category => {
allCategories.add(category);
});
});
allCategories.forEach(category => {
const option = document.createElement('option');
option.value = category;
option.textContent = dict['cat_' + category] || (category.charAt(0).toUpperCase() + category.slice(1));
categorySelection.appendChild(option);
});
}
function displayHighScore() {
const highScore = localStorage.getItem(HIGH_SCORE_KEY) || '0';
highScoreDisplay.textContent = highScore;
}
function restartQuiz() {
// This function now acts as a general reset to the config screen
if (questionTimerInterval) clearInterval(questionTimerInterval);
if (globalTimerInterval) clearInterval(globalTimerInterval);
// Reset state variables
currentIndex = 0;
weightedScore = 0;
maxPossibleScore = 0;
currentTestQuestions = [];
answerLog = [];
// Swap visibility back to the config screen
resultArea.classList.add("hidden");
quizArea.classList.add("hidden");
explanationsContainer.classList.add("hidden");
quizHeaderInfo.classList.add("hidden");
terminateBtn.classList.add("hidden");
configArea.classList.remove("hidden");
progressFill.style.width = "0%";
// Ensure high score is up-to-date on the home screen
displayHighScore();
}
function updateLanguage(lang) {
currentLang = lang;
const dict = uiTranslations[lang];
// Update all elements with data-i18n attributes
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if(dict[key]) {
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
el.placeholder = dict[key];
} else {
el.textContent = dict[key];
}
}
});
populateCategories(); // Refresh categories
}
// --- Authentication Functions ---
onAuthStateChanged(auth, (user) => {
if (user) {
authContainer.classList.add('hidden');
userInfoDisplay.textContent = user.email || user.displayName || "User";
userInfoDisplay.style.display = "inline-block";
// Check if user has previously accepted T&C on this device
const termsAccepted = localStorage.getItem('termsAccepted_' + user.uid);
if (termsAccepted === 'true') {
tncContainer.classList.add('hidden');
mainAppContainer.classList.remove('hidden');
} else {
// Show T&C screen, hide main app
mainAppContainer.classList.add('hidden');
tncContainer.classList.remove('hidden');
// Reset checkbox and button state
tncCheckbox.checked = false;
tncAcceptBtn.disabled = true;
}
} else {
// User is signed out, show login window, hide main app
authContainer.classList.remove('hidden');
mainAppContainer.classList.add('hidden');
tncContainer.classList.add('hidden');
userInfoDisplay.textContent = "";
userInfoDisplay.style.display = "none";
// Clear credentials and messages upon logout
authEmail.value = '';
authPassword.value = '';
authPassword.type = 'password';
authConfirmPassword.value = '';
authConfirmPassword.type = 'password';
authMessage.textContent = '';
document.querySelectorAll('.password-toggle svg').forEach(svg => {
svg.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle>';
});
restartQuiz(); // Reset quiz state in case they log out mid-quiz
}
});
// --- T&C Functions ---
tncCheckbox.addEventListener('change', (e) => {
tncAcceptBtn.disabled = !e.target.checked;
});
tncAcceptBtn.addEventListener('click', () => {
if (auth.currentUser && tncCheckbox.checked) {
localStorage.setItem('termsAccepted_' + auth.currentUser.uid, 'true');
tncContainer.classList.add('hidden');
mainAppContainer.classList.remove('hidden');
}
});
tncDeclineBtn.addEventListener('click', () => {
signOut(auth).then(() => {
setTimeout(() => {
authMessage.textContent = "You must accept the Terms & Conditions to use IQ Master.";
authMessage.style.color = "var(--error-color)";
}, 50);
});
});
let isLoginMode = true;
authSwitchLink.addEventListener('click', (e) => {
e.preventDefault();
isLoginMode = !isLoginMode;
authMessage.textContent = "";
const dict = uiTranslations[currentLang];
if (isLoginMode) {
authTitle.textContent = dict.welcomeBack;
authSubtitle.textContent = dict.loginToContinue;
confirmPasswordGroup.classList.add('hidden');
forgotPasswordContainer.classList.remove('hidden');
authSubmitBtn.textContent = dict.loginBtn;
authSwitchText.textContent = dict.noAccount;
authSwitchLink.textContent = dict.signUpLink;
authConfirmPassword.removeAttribute('required');
} else {
authTitle.textContent = dict.createAccount;
authSubtitle.textContent = dict.signupText;
confirmPasswordGroup.classList.remove('hidden');
forgotPasswordContainer.classList.add('hidden');
authSubmitBtn.textContent = dict.alreadyAccount;
authSwitchText.textContent = dict.alreadyAccount;
authSwitchLink.textContent = dict.loginLink;
authConfirmPassword.setAttribute('required', 'true');
}
});
authForm.addEventListener('submit', (e) => {
e.preventDefault(); // Prevents page reload
const email = authEmail.value;
const password = authPassword.value;
const dict = uiTranslations[currentLang];
SoundEngine.init(); // Initialize audio context on first meaningful user interaction
authSubmitBtn.disabled = true;
authSubmitBtn.innerHTML = `<span class="spinner"></span> ${dict.wait}`;
authMessage.style.color = "var(--error-color)"; // Reset color to error for typical messages
if (isLoginMode) {
signInWithEmailAndPassword(auth, email, password)
.then(() => {
authMessage.textContent = "";
authSubmitBtn.disabled = false;
authSubmitBtn.innerHTML = dict.loginBtn;
})
.catch((error) => {
authMessage.textContent = error.message.replace('Firebase: ', '');
authSubmitBtn.disabled = false;
authSubmitBtn.innerHTML = dict.loginBtn;
});
} else {
if (password !== authConfirmPassword.value) {
authMessage.textContent = dict.alert_pwdMatch;
authSubmitBtn.disabled = false;
authSubmitBtn.textContent = dict.signUpLink;
return;
}
createUserWithEmailAndPassword(auth, email, password)
.then(() => {
authMessage.textContent = dict.alert_regSuccess;
authMessage.style.color = "var(--success-color)";
authSubmitBtn.disabled = false;
authSubmitBtn.innerHTML = dict.signUpLink;
})
.catch((error) => {
authMessage.textContent = error.message.replace('Firebase: ', '');
authSubmitBtn.disabled = false;
authSubmitBtn.innerHTML = dict.signUpLink;
});
}
});
// Forgot Password Functionality
forgotPasswordLink.addEventListener('click', (e) => {
e.preventDefault();
const email = authEmail.value.trim();
const dict = uiTranslations[currentLang] || uiTranslations['en'];
if (!email) {
authMessage.textContent = dict.alert_enterEmail;
authMessage.style.color = "var(--error-color)";
return;
}
sendPasswordResetEmail(auth, email)
.then(() => {
authMessage.textContent = dict.alert_resetSent;
authMessage.style.color = "var(--success-color)";
})
.catch((error) => {
authMessage.textContent = error.message.replace('Firebase: ', '');
authMessage.style.color = "var(--error-color)";
});
});
// Initialize Google Auth Provider
const googleProvider = new GoogleAuthProvider();
googleLoginBtn.addEventListener('click', (e) => {
e.preventDefault();
SoundEngine.init();
const originalContent = googleLoginBtn.innerHTML;
const dict = uiTranslations[currentLang] || uiTranslations['en'];
// Do not disable the button before opening the popup to avoid strict browser popup blockers
googleLoginBtn.innerHTML = `<span class="spinner"></span> ${dict.wait}`;
signInWithPopup(auth, googleProvider)
.then(() => {
authMessage.textContent = "";
googleLoginBtn.innerHTML = originalContent;
})
.catch((error) => {
authMessage.textContent = error.message.replace('Firebase: ', '');
googleLoginBtn.innerHTML = originalContent;
});
});
logoutBtn.addEventListener('click', () => {
const dict = uiTranslations[currentLang] || uiTranslations['en'];
signOut(auth).then(() => {
setTimeout(() => {
authMessage.textContent = dict.alert_logoutSuccess;
authMessage.style.color = "var(--success-color)";
}, 50); // Set slight delay so it displays after the input clearer runs
}).catch((error) => {
console.error("Logout Error:", error);
});
});
// 5. Event Listeners and Initialization
startBtn.addEventListener("click", generateAndStartQuiz);
restartBtn.addEventListener("click", restartQuiz);
themeToggle.addEventListener('change', toggleTheme);
gameModeSelect.addEventListener('change', (e) => {
questionCountSelect.disabled = e.target.value === 'sprint';
});
languageSelect.addEventListener('change', (e) => {
updateLanguage(e.target.value);
const dict = uiTranslations[currentLang] || uiTranslations['en'];
// If a test is actively running, prompt to restart to apply question language
if (!quizArea.classList.contains('hidden')) {
if (confirm(dict.confirm_langChange)) {
restartQuiz();
}
}
});
terminateBtn.addEventListener("click", () => {
const dict = uiTranslations[currentLang] || uiTranslations['en'];
if (confirm(dict.confirm_endTest)) {
restartQuiz();
}
});
// Fetch questions from external file and initialize app
fetch('questions.json')
.then(response => {
if (!response.ok) throw new Error("Failed to fetch questions");
return response.json();
})
.then(data => {
baseQuestionBank = data;
questionBank = new Proxy(baseQuestionBank, {
get: function(target, lang) {
return target[lang] || target['en'];
}
});
loadInitialTheme();
displayHighScore();
populateCategories();
updateLanguage('en');
})
.catch(err => {
console.error("Initialization Error:", err);
authMessage.textContent = "Failed to load question bank. Ensure you are running a local server (like Live Server).";
});
// Password Visibility Toggle
const passwordToggles = document.querySelectorAll('.password-toggle');
passwordToggles.forEach(toggle => {
toggle.addEventListener('click', () => {
const input = toggle.parentElement.querySelector('input');
const svg = toggle.querySelector('svg');
if (input.type === 'password') {
input.type = 'text';
svg.innerHTML = '<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line>';
} else {
input.type = 'password';
svg.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle>';
}
});
});