forked from brendacalazans/DBQuest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbquest.html
More file actions
1603 lines (1429 loc) · 99.7 KB
/
dbquest.html
File metadata and controls
1603 lines (1429 loc) · 99.7 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
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DBQuest - Aprenda Banco de Dados</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- React -->
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<!-- Babel for JSX -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<style>
/* Animação de fade-in */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fadeIn 0.5s ease-out forwards;
}
/* Estilização da scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
</style>
</head>
<body class="bg-gray-900">
<div id="root"></div>
<script type="module">
// Importa as funções necessárias do Firebase v10+
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import {
getAuth,
onAuthStateChanged,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
GoogleAuthProvider,
signInWithPopup,
updateProfile,
signOut
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";
import {
getDatabase,
ref,
onValue,
set,
update,
increment,
get // <-- ADICIONADO
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-database.js";
// Configuração do Firebase
const firebaseConfig = {
apiKey: "AIzaSyDoI9Az5udHaeUHOybJc5-YW75oV-kKtgs",
authDomain: "dataquest-c39fd.firebaseapp.com",
databaseURL: "https://dataquest-c39fd-default-rtdb.firebaseio.com",
projectId: "dataquest-c39fd",
storageBucket: "dataquest-c39fd.appspot.com",
messagingSenderId: "130744038521",
appId: "1:130744038521:web:432aaa66a10650210e50a8"
};
// Inicializa o Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getDatabase(app); // Agora usando Realtime Database
// Exponha instâncias e funções para o objeto window para o script Babel
window.FB = {
auth, db, onAuthStateChanged, createUserWithEmailAndPassword,
signInWithEmailAndPassword, GoogleAuthProvider, signInWithPopup,
updateProfile, signOut, ref, onValue, set, update, increment,
get // <-- ADICIONADO
};
</script>
<script type="text/babel">
(function() { // <-- CORREÇÃO: Início da IIFE
// --- Desestruturação de Globais ---
const {
auth, db, onAuthStateChanged, createUserWithEmailAndPassword,
signInWithEmailAndPassword, GoogleAuthProvider, signInWithPopup,
updateProfile, signOut, ref, onValue, set, update, increment,
get // <-- ADICIONADO
} = window.FB;
// --- Desestruturação do React ---
const { useState, useEffect, useCallback, memo, createContext, useContext } = React;
// --- Ícones como Componentes React (Memoizados) ---
const Trophy = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>);
const Star = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>);
const Sparkles = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 3-1.9 1.9-1.9-1.9-1.9 1.9-1.9-1.9L2.5 5l1.9 1.9-1.9 1.9 1.9 1.9-1.9 1.9 1.9 1.9 1.9-1.9 1.9 1.9 1.9-1.9 1.9 1.9 1.9-1.9-1.9-1.9 1.9-1.9-1.9-1.9 1.9-1.9Z"/><path d="M22 12.5 20.1 14.4 22 16.3 20.1 18.2 22 20.1 18.2 20.1 16.3 22 14.4 20.1 12.5 22 12.5 18.2 10.6 20.1 8.7 18.2 10.6 16.3 8.7 14.4 10.6 12.5 8.7 10.6 10.6 8.7 12.5 6.8 14.4 8.7 16.3 10.6 18.2 12.5Z"/></svg>);
const Flame = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>);
const Database = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/></svg>);
const Lock = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>);
const Check = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>);
const X = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>);
const Heart = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>);
const HeartCrack = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/><path d="m12 13-1-1 2-2-3-3 2-2"/></svg>);
const Gem = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 3h12l4 6-10 13L2 9Z"/><path d="M12 22V9"/><path d="m3.5 8.5 17 0"/></svg>);
const Award = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="6"/><path d="M15.477 12.89 17 22l-5-3-5 3 1.523-9.11"/></svg>);
const Target = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>);
const Code = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>);
const ChevronRight = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>);
const ArrowLeft = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></svg>);
const BookOpen = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>);
const PenTool = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 19 7-7 3 3-7 7-3-3z"/><path d="m18 13-1.5-1.5"/><path d="m2 2 7.586 7.586"/><path d="m11 11 1 1"/></svg>);
const GraduationCap = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0l8.59-3.9z"/><path d="M6 12v5c0 1.66 3.13 3 7 3s7-1.34 7-3v-5"/></svg>);
const FileText = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/></svg>);
const Play = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>);
const Clock = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>);
const User = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>);
const Edit2 = memo(() => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>); // Novo ícone
const getInitials = (name) => {
if (!name || typeof name !== 'string' || name.length === 0) return '👤';
const words = name.split(' ');
if (words.length > 1 && words[words.length - 1].length > 0) {
return (words[0][0] + words[words.length - 1][0]).toUpperCase();
}
return name[0].toUpperCase();
};
// --- Componente Toast (NOVO E GLOBAL) ---
const Toast = memo(({ message, type, onDismiss }) => {
useEffect(() => {
const timer = setTimeout(onDismiss, 3000);
return () => clearTimeout(timer);
}, [onDismiss]);
const bgColor = type === 'success' ? 'bg-green-600' : 'bg-red-600';
return (
<div className={`fixed top-5 right-5 ${bgColor} text-white px-6 py-3 rounded-lg shadow-lg animate-fade-in z-50`}>
{message}
</div>
);
});
// --- Componente AuthScreen (ATUALIZADO PARA O DESIGN DA IMAGEM) ---
const AuthScreen = memo(({ auth }) => {
const [localToast, setLocalToast] = useState(null);
const [view, setView] = useState('login'); // 'login' or 'register'
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [name, setName] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleLogin = async (e) => {
e.preventDefault();
setIsLoading(true);
try {
await signInWithEmailAndPassword(auth, email, password);
// Success is handled by onAuthStateChanged in App
} catch (error) {
console.error(error);
setLocalToast({ message: 'Email ou senha inválidos.', type: 'error' });
} finally {
setIsLoading(false);
}
};
const handleRegister = async (e) => {
e.preventDefault();
if (password !== confirmPassword) {
setLocalToast({ message: 'As senhas não correspondem.', type: 'error' });
return;
}
setIsLoading(true);
try {
const cred = await createUserWithEmailAndPassword(auth, email, password);
await updateProfile(cred.user, { displayName: name });
// Success is handled by onAuthStateChanged in App
} catch (error) {
console.error(error);
setLocalToast({ message: error.message, type: 'error' });
} finally {
setIsLoading(false);
}
};
const handleGoogleLogin = async () => {
const provider = new GoogleAuthProvider();
try {
await signInWithPopup(auth, provider);
// Success is handled by onAuthStateChanged in App
} catch (error) {
console.error(error);
setLocalToast({ message: error.message, type: 'error' });
}
};
return (
<div className="min-h-screen bg-gray-100 text-gray-900 font-sans antialiased flex items-center justify-center p-5">
{localToast && <Toast message={localToast.message} type={localToast.type} onDismiss={() => setLocalToast(null)} />}
<div className="w-full max-w-6xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-10 items-center">
{/* Coluna da Esquerda (Branding) - ATUALIZADO */}
<div className="flex-1 text-center md:text-left p-8">
<div className="flex items-center justify-center md:justify-start gap-3 mb-6">
<Database className="w-12 h-12 text-purple-600" />
<h1 className="text-5xl font-bold text-gray-900">DBQuest</h1>
</div>
<h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
Aprenda <span className="text-purple-600">Banco de Dados</span> como nunca antes
</h2>
<p className="text-lg text-gray-600">
Domine SQL, NoSQL e conceitos de banco de dados através de exercícios interativos e gamificação.
</p>
</div>
{/* Coluna da Direita (Formulário) - ATUALIZADO */}
<div className="flex-1 w-full max-w-md mx-auto">
<div className="bg-white rounded-2xl p-8 shadow-2xl">
<h2 className="text-3xl font-bold text-center text-gray-900 mb-2">
{view === 'login' ? 'Bem-vindo de volta!' : 'Criar Conta'}
</h2>
<p className="text-center text-gray-600 mb-6">
{view === 'login' ? 'Faça login para continuar' : 'Preencha os campos para se registrar'}
</p>
<form onSubmit={view === 'login' ? handleLogin : handleRegister} className="space-y-4">
{view === 'register' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Nome</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-lg text-gray-900 focus:ring-purple-500 focus:border-purple-500"
/>
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Email</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-lg text-gray-900 focus:ring-purple-500 focus:border-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Senha</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-lg text-gray-900 focus:ring-purple-500 focus:border-purple-500"
/>
</div>
{view === 'register' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Confirmar Senha</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
className="w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-lg text-gray-900 focus:ring-purple-500 focus:border-purple-500"
/>
</div>
)}
<button
type="submit"
disabled={isLoading}
className="w-full bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 text-white font-bold py-3 px-6 rounded-lg transition-colors disabled:opacity-50"
>
{isLoading ? 'Carregando...' : (view === 'login' ? 'Entrar' : 'Registrar')}
</button>
</form>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-200"></div></div>
<div className="relative flex justify-center text-sm"><span className="px-2 bg-white text-gray-500">ou</span></div>
</div>
<button
onClick={handleGoogleLogin}
className="w-full bg-white border border-gray-300 text-gray-700 font-bold py-3 px-6 rounded-lg transition-colors hover:bg-gray-50 flex items-center justify-center gap-3"
>
<svg className="w-5 h-5" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"></path><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"></path><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"></path><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"></path><path fill="none" d="M0 0h48v48H0z"></path></svg>
Entrar com Google
</button>
<p className="mt-6 text-center text-sm text-gray-600">
{view === 'login' ? 'Não tem conta?' : 'Já tem uma conta?'}
<button
onClick={() => setView(view === 'login' ? 'register' : 'login')}
className="font-semibold text-purple-600 hover:text-purple-700 ml-1"
>
{view === 'login' ? 'Registre-se' : 'Faça login'}
</button>
</p>
</div>
</div>
</div>
</div>
);
});
function App() {
// --- ESTADO DA APLICAÇÃO (Restaurado) ---
// Estados de Autenticação e Usuário
const [userId, setUserId] = useState(null);
const [isAuthChecked, setIsAuthChecked] = useState(false);
const [userProgress, setUserProgress] = useState({
username: 'Carregando...',
avatar: '👤',
level: 1,
totalXP: 0,
streak: 0,
gems: 0,
lives: 5,
completedLessons: [],
lastCompletedLessonDate: null,
lastLifeResetDate: null,
cooldownUntil: null
});
// Estados de Navegação e Conteúdo
const [currentView, setCurrentView] = useState('home');
const [selectedTrail, setSelectedTrail] = useState(null);
const [currentLesson, setCurrentLesson] = useState(null);
const [currentQuestion, setCurrentQuestion] = useState(0);
const [filterType, setFilterType] = useState('all');
// Estados de Dados (Trilhas e Ranking)
const [studyTrails, setStudyTrails] = useState([]);
const [leaderboard, setLeaderboard] = useState([]);
const [isRankingLoading, setIsRankingLoading] = useState(true);
// Estados da Lição
const [answeredQuestions, setAnsweredQuestions] = useState([]);
const [showResult, setShowResult] = useState(false);
const [selectedAnswer, setSelectedAnswer] = useState(null);
// Estados de Desafio (IA)
const [challenge, setChallenge] = useState(null);
const [isChallengeLoading, setIsChallengeLoading] = useState(false);
const [aiExplanation, setAiExplanation] = useState('');
const [isAiExplanationLoading, setIsAiExplanationLoading] = useState(false);
// Estado de Notificação
const [toast, setToast] = useState(null);
// --- EFEITOS (Restaurados) ---
// Efeito: Observador de Autenticação
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setUserId(user ? user.uid : null);
setIsAuthChecked(true);
});
return () => unsubscribe(); // Limpa ao desmontar
}, []);
// Efeito: Carregar Dados do Usuário e Trilha
useEffect(() => {
// Carrega as trilhas estáticas (simulação de API)
// (Esta parte estava faltando, adicionei a estrutura de dados)
const trailsData = [
{
id: 'trail1',
icon: '🚀',
color: 'from-blue-500 to-cyan-400',
title: 'Fundamentos de SQL',
description: 'Comece sua jornada aprendendo os comandos básicos de SQL.',
lessons: [
{ id: 'l1-1', title: 'O que é um Banco de Dados?', type: 'article', duration: '5 min', xp: 20, content: 'Um banco de dados é uma coleção organizada de informações - ou dados - estruturadas, geralmente armazenadas eletronicamente em um sistema de computador. Um banco de dados é geralmente controlado por um sistema de gerenciamento de banco de dados (DBMS). Juntos, os dados e o DBMS, juntamente com os aplicativos associados a eles, são chamados de sistema de banco de dados, ou simplesmente banco de dados.\n\nDados dentro dos tipos mais comuns de bancos de dados em operação atualmente são normalmente modelados em linhas e colunas em uma série de tabelas para tornar o processamento e a consulta de dados eficientes. Os dados podem ser facilmente acessados, gerenciados, modificados, atualizados, controlados e organizados. A maioria dos bancos de dados usa a linguagem de consulta estruturada (SQL) para escrever e consultar dados.' },
{ id: 'l1-2', title: 'Introdução ao SELECT', type: 'lesson', duration: '10 min', xp: 50, questions: [
{ question: 'Qual comando é usado para buscar dados de uma tabela?', options: ['GET', 'SELECT', 'FETCH', 'PULL'], correct: 1, explanation: 'O comando SELECT é usado para consultar e extrair dados de um banco de dados.' },
{ question: 'Qual símbolo seleciona todas as colunas?', options: ['*', '#', 'ALL', '&'], correct: 0, explanation: 'O asterisco (*) é um curinga que seleciona todas as colunas da tabela.' }
]},
{ id: 'l1-3', title: 'Filtrando com WHERE', type: 'lesson', duration: '12 min', xp: 60, questions: [
{ question: 'Qual cláusula filtra os resultados?', options: ['FILTER', 'WHERE', 'IF', 'FIND'], correct: 1, explanation: 'A cláusula WHERE é usada para filtrar registros que satisfazem uma condição específica.' },
{ question: 'Como você selecionaria usuários com idade superior a 18?', options: ['SELECT * FROM users WHERE age > 18', 'SELECT * FROM users IF age > 18', 'SELECT * FROM users FILTER age > 18', 'SELECT * FROM users WITH age > 18'], correct: 0, explanation: 'A sintaxe correta usa WHERE seguido da condição `age > 18`.' }
]}
]
},
{
id: 'trail2',
icon: '🧩',
color: 'from-purple-500 to-indigo-400',
title: 'SQL Intermediário',
description: 'Aprofunde-se com JOINs, GROUP BY e funções agregadas.',
lessons: [
{ id: 'l2-1', title: 'Unindo Tabelas com JOIN', type: 'lesson', duration: '15 min', xp: 75, questions: [
{ question: 'Qual comando combina linhas de duas ou mais tabelas?', options: ['COMBINE', 'MERGE', 'JOIN', 'LINK'], correct: 2, explanation: 'O comando JOIN é usado para combinar linhas de duas ou mais tabelas com base em uma coluna relacionada entre elas.' }
]},
{ id: 'l2-2', title: 'Agrupando com GROUP BY', type: 'lesson', duration: '15 min', xp: 75, questions: [
{ question: 'Qual cláusula é usada com funções agregadas para agrupar o conjunto de resultados por uma ou mais colunas?', options: ['GROUP BY', 'ORDER BY', 'HAVING', 'CLUSTER BY'], correct: 0, explanation: 'A cláusula GROUP BY é usada para agrupar linhas que têm os mesmos valores em colunas especificadas.' }
]}
]
},
{
id: 'trail3',
icon: '🌌',
color: 'from-pink-500 to-rose-500',
title: 'SQL Avançado',
description: 'Domine subconsultas, índices e otimização de performance.',
lessons: [
{ id: 'l3-1', title: 'Subconsultas (Subqueries)', type: 'article', duration: '10 min', xp: 40, content: 'Uma subconsulta é uma consulta SQL aninhada dentro de outra consulta SQL. Elas podem ser usadas em cláusulas WHERE, FROM ou SELECT para realizar operações complexas e filtrar dados com base nos resultados de outra consulta.' },
{ id: 'l3-2', title: 'Prática de Subconsulta', type: 'practice', duration: '20 min', xp: 100, questions: [
{ question: 'Qual comando você usaria para encontrar clientes que fizeram pedidos?', options: ['SELECT nome FROM clientes WHERE id IN (SELECT cliente_id FROM pedidos)', 'SELECT nome FROM clientes WHERE EXISTS pedidos', 'SELECT nome FROM clientes JOIN pedidos', 'SELECT nome FROM clientes AND pedidos'], correct: 0, explanation: 'Usar `IN` com uma subconsulta `(SELECT cliente_id FROM pedidos)` é uma maneira eficaz de encontrar clientes que existem na tabela de pedidos.' }
]}
]
}
];
setStudyTrails(trailsData);
// Observador do Ranking
const leaderboardRef = ref(db, 'leaderboard');
const offLeaderboard = onValue(leaderboardRef, (snapshot) => {
const data = snapshot.val();
if (data) {
const sortedData = Object.entries(data)
.map(([id, values]) => ({ id, ...values }))
.sort((a, b) => b.totalXP - a.totalXP);
setLeaderboard(sortedData);
}
setIsRankingLoading(false);
});
// Observador de Dados do Usuário
let offUserProgress = () => {};
if (userId) {
const userRef = ref(db, `users/${userId}`);
offUserProgress = onValue(userRef, async (snapshot) => {
if (snapshot.exists()) {
const data = snapshot.val();
// --- Verificação de Ofensiva e Vidas (Restaurado) ---
const today = new Date();
today.setHours(0, 0, 0, 0);
const todayTimestamp = today.getTime();
const lastResetDate = data.lastLifeResetDate ? new Date(data.lastLifeResetDate) : null;
let lives = data.gamification.lives;
let cooldown = data.cooldownUntil ? new Date(data.cooldownUntil) : null;
const updates = {};
let needsUpdate = false;
// Check for daily life reset
if (!lastResetDate || lastResetDate.getTime() < todayTimestamp) {
if (lives < 5) {
updates['gamification/lives'] = 5;
updates['cooldownUntil'] = null;
updates['lastLifeResetDate'] = todayTimestamp;
lives = 5;
cooldown = null;
needsUpdate = true;
}
}
// Check if cooldown has ended
if (cooldown && cooldown.getTime() <= Date.now()) {
updates['gamification/lives'] = 5;
updates['cooldownUntil'] = null;
updates['lastLifeResetDate'] = todayTimestamp;
lives = 5;
needsUpdate = true;
}
// Check for streak reset
const lastCompleted = data.lastCompletedLessonDate ? new Date(data.lastCompletedLessonDate) : null;
if (lastCompleted) {
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
// Se a última lição completada foi ANTES de ontem, zera a ofensiva
if (lastCompleted.getTime() < yesterday.getTime()) {
updates['gamification/streak'] = 0;
needsUpdate = true;
}
}
if (needsUpdate) {
await update(userRef, updates);
}
// Atualiza o estado local com os dados do DB (e possíveis atualizações)
setUserProgress({
...data.gamification,
username: data.name || auth.currentUser.displayName || 'Aluno',
avatar: data.avatar || '👤',
cooldownUntil: cooldown ? cooldown.toISOString() : null,
lives: lives
});
// Garante que o ranking esteja atualizado
const rankRef = ref(db, `leaderboard/${userId}`);
const rankSnapshot = await get(rankRef); // 'get' precisa ser importado
if (!rankSnapshot.exists() || rankSnapshot.val().username !== data.name || rankSnapshot.val().avatar !== data.avatar) {
update(rankRef, {
username: data.name,
totalXP: data.gamification.totalXP,
avatar: data.avatar || '👤'
});
}
} else {
// --- Cria novo usuário no DB (Restaurado) ---
const newUser = {
name: auth.currentUser.displayName || 'Novo Aluno',
avatar: '👤',
email: auth.currentUser.email,
joinedDate: new Date().toISOString(),
gamification: {
level: 1,
totalXP: 0,
streak: 0,
gems: 100,
lives: 5,
completedLessons: [],
lastCompletedLessonDate: null,
lastLifeResetDate: new Date().setHours(0,0,0,0)
},
cooldownUntil: null
};
await set(userRef, newUser);
setUserProgress(newUser.gamification);
// Adiciona ao leaderboard
await set(ref(db, `leaderboard/${userId}`), {
username: newUser.name,
totalXP: 0,
avatar: newUser.avatar
});
}
});
} else {
// Reseta o progresso se o usuário deslogar
setUserProgress({
username: 'Convidado', avatar: '👤', level: 1, totalXP: 0,
streak: 0, gems: 0, lives: 5, completedLessons: []
});
}
// Função de limpeza
return () => {
offLeaderboard();
offUserProgress();
};
// Adicionada a importação de 'get' que estava faltando
}, [userId, db, auth]); // Adicionado 'get'
// --- Funções de Handler (Restauradas) ---
const handleLogout = async () => {
try {
await signOut(auth);
setCurrentView('home'); // Redireciona para home (que mostrará AuthScreen)
setToast({ message: "Sessão terminada com sucesso.", type: 'success' });
} catch (error) {
console.error("Erro ao terminar sessão:", error);
setToast({ message: "Erro ao terminar sessão.", type: 'error' });
}
};
const startLesson = (trail, lesson) => {
if (userProgress.lives <= 0) {
setCurrentView('noLives');
return;
}
setSelectedTrail(trail);
setCurrentLesson(lesson);
setCurrentQuestion(0);
setAnsweredQuestions([]);
setShowResult(false);
setSelectedAnswer(null);
if (lesson.type === 'article') {
setCurrentView('article');
} else {
setCurrentView('lesson');
}
};
const getContentTypeInfo = useCallback((type) => {
switch (type) {
case 'article': return { label: 'Artigo', icon: <FileText />, color: 'border-blue-400 text-blue-300', bgGradient: 'from-blue-900/30 to-blue-800/20' };
case 'lesson': return { label: 'Aula', icon: <GraduationCap />, color: 'border-cyan-400 text-cyan-300', bgGradient: 'from-cyan-900/30 to-cyan-800/20' };
case 'theory': return { label: 'Teoria', icon: <BookOpen />, color: 'border-purple-400 text-purple-300', bgGradient: 'from-purple-900/30 to-purple-800/20' };
case 'practice': return { label: 'Prática', icon: <PenTool />, color: 'border-green-400 text-green-300', bgGradient: 'from-green-900/30 to-green-800/20' };
default: return { label: 'Conteúdo', icon: <FileText />, color: 'border-gray-400 text-gray-300', bgGradient: 'from-gray-900/30 to-gray-800/20' };
}
}, []);
const checkAnswer = useCallback((optionIndex) => {
if (showResult) return;
setSelectedAnswer(optionIndex);
setShowResult(true);
const question = currentLesson.questions[currentQuestion];
const isCorrect = optionIndex === question.correct;
setAnsweredQuestions(prev => [...prev, { ...question, selected: optionIndex, isCorrect }]);
// Lógica de gamificação
if (!isCorrect) {
const newLives = userProgress.lives - 1;
setUserProgress(prev => ({ ...prev, lives: newLives }));
update(ref(db, `users/${userId}/gamification`), { lives: newLives });
if (newLives <= 0) {
const cooldownTime = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 horas
setUserProgress(prev => ({ ...prev, cooldownUntil: cooldownTime.toISOString() }));
update(ref(db, `users/${userId}`), { cooldownUntil: cooldownTime.toISOString() });
}
}
}, [showResult, currentLesson, currentQuestion, userProgress.lives, userId, db]);
// --- LÓGICA DE OFENSIVA (STREAK) CORRIGIDA ---
const handleLessonCompletion = (lessonId, lessonXP) => {
const today = new Date();
today.setHours(0, 0, 0, 0); // Zera a hora para comparar apenas o dia
const lastCompletedDate = userProgress.lastCompletedLessonDate ? new Date(userProgress.lastCompletedLessonDate) : null;
if (lastCompletedDate) {
lastCompletedDate.setHours(0, 0, 0, 0); // Zera a hora da última data
}
let newStreak = userProgress.streak;
// Só incrementa a ofensiva se a última lição foi ANTES de hoje
if (!lastCompletedDate || lastCompletedDate.getTime() < today.getTime()) {
newStreak += 1;
console.log("Ofensiva incrementada!");
} else {
console.log("Lição completada hoje, ofensiva mantida.");
}
const newXP = (Number(userProgress.totalXP) || 0) + (Number(lessonXP) || 0);
const newLevel = Math.floor(newXP / 100) + 1;
const completed = [...(userProgress.completedLessons || [])];
if (!completed.includes(lessonId)) {
completed.push(lessonId);
}
const updates = {
totalXP: newXP,
level: newLevel,
streak: newStreak,
lastCompletedLessonDate: new Date().toISOString(), // Salva a data E hora exata
completedLessons: completed
};
update(ref(db, `users/${userId}/gamification`), updates);
update(ref(db, `leaderboard/${userId}`), { totalXP: newXP, streak: newStreak });
return newXP;
};
const nextQuestion = useCallback(() => {
setShowResult(false);
setSelectedAnswer(null);
setAiExplanation('');
if (currentQuestion < currentLesson.questions.length - 1) {
setCurrentQuestion(prev => prev + 1);
} else {
// Lição concluída
const correctAnswers = answeredQuestions.filter(a => a.isCorrect).length;
const totalQuestions = currentLesson.questions.length;
if (correctAnswers === totalQuestions) {
// Chama a nova função centralizada
handleLessonCompletion(currentLesson.id, currentLesson.xp);
setCurrentView('completion');
} else {
// Falhou na lição
setCurrentView('completion'); // Mostra os resultados mesmo se falhar
}
}
}, [currentQuestion, currentLesson, answeredQuestions, userProgress, userId, db]);
const handleArticleCompletion = useCallback(() => {
// Chama a nova função centralizada
const newXP = handleLessonCompletion(currentLesson.id, currentLesson.xp);
setCurrentView('home'); // Volta para a home
setToast({ message: `Artigo concluído! +${currentLesson.xp} XP`, type: 'success' });
}, [currentLesson, userProgress, userId, db]);
const handleRefillLives = useCallback(() => {
const refillCost = 100; // Custo em gemas
if (userProgress.gems >= refillCost) {
const newGems = userProgress.gems - refillCost;
const newLives = 5;
update(ref(db, `users/${userId}/gamification`), {
gems: newGems,
lives: newLives
});
update(ref(db, `users/${userId}`), {
cooldownUntil: null,
lastLifeResetDate: new Date().setHours(0,0,0,0)
});
setUserProgress(prev => ({
...prev,
gems: newGems,
lives: newLives,
cooldownUntil: null
}));
setCurrentView('home'); // Volta para a home
setToast({ message: "Vidas recarregadas!", type: 'success' });
} else {
setToast({ message: "Gemas insuficientes.", type: 'error' });
}
}, [userProgress.gems, userId, db]);
const handleCooldownEnd = useCallback(() => {
setUserProgress(prev => ({ ...prev, lives: 5, cooldownUntil: null }));
setCurrentView('home'); // Volta para a home
}, []);
// --- Componentes Memoizados ---
const Header = memo(({ userProgress, onNavigate }) => {
const initials = getInitials(userProgress.username); // Get initials
return (
<header className="bg-white/10 backdrop-blur-md border-b border-white/20 sticky top-0 z-20">
<div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-3 cursor-pointer" onClick={() => onNavigate('home')}>
<Database className="w-8 h-8 text-cyan-300" />
<h1 className="text-2xl font-bold">DBQuest</h1>
</div>
<nav className="hidden md:flex items-center gap-6">
<button onClick={() => onNavigate('home')} className="text-white/80 hover:text-white font-semibold transition-colors">Trilhas</button>
<button onClick={() => onNavigate('ranking')} className="text-white/80 hover:text-white font-semibold transition-colors">Ranking</button>
</nav>
<div className="flex items-center gap-4 md:gap-6">
<div className="flex items-center gap-2 bg-orange-500/20 px-3 py-2 rounded-full"> <Flame /> <span className="font-bold">{userProgress.streak}</span> </div>
<div className="flex items-center gap-2 bg-cyan-500/20 px-3 py-2 rounded-full"> <Gem /> <span className="font-bold">{userProgress.gems}</span> </div>
<div className="flex items-center gap-2 bg-red-500/20 px-3 py-2 rounded-full"> <Heart className={`${userProgress.lives > 0 ? 'text-red-400' : 'text-gray-500'}`} /> <span className="font-bold">{userProgress.lives}</span> </div>
<button onClick={() => onNavigate('profile')} className="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center text-white font-bold text-2xl">{userProgress.avatar ? userProgress.avatar : initials}</button>
</div>
</div>
</header>
);
});
const HomeView = memo(({ userProgress, studyTrails, onSelectTrail, onGenerateChallenge }) => (
<main className="max-w-6xl mx-auto px-6 py-6 animate-fade-in">
<div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 border border-white/20">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-16 h-16 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-full flex items-center justify-center"><Trophy /></div>
<div>
<div className="text-white/60 text-sm">Nível {userProgress.level}</div>
<div className="text-2xl font-bold">{userProgress.totalXP} XP</div>
</div>
</div>
<div className="flex items-center gap-8">
<div className="text-center hidden md:block"><div className="text-3xl font-bold">{(userProgress.completedLessons || []).length}</div><div className="text-white/60 text-sm">Lições Completas</div></div>
<div className="text-center"><div className="text-3xl font-bold text-cyan-400">{userProgress.streak}</div><div className="text-white/60 text-sm">Dias de Ofensiva</div></div>
</div>
</div>
<div className="mt-4">
<div className="bg-white/20 rounded-full h-3 overflow-hidden"><div className="bg-gradient-to-r from-cyan-400 to-blue-500 h-full rounded-full transition-all duration-500" style={{ width: `${(userProgress.totalXP % 100)}%` }} /></div>
<div className="text-white/60 text-xs mt-1 text-right">{100 - (userProgress.totalXP % 100)} XP para o próximo nível</div>
</div>
</div>
{/* Gemini API Feature: Quick Challenge */}
<div className="mt-10">
<h2 className="text-2xl font-bold text-white mb-6 flex items-center gap-2"><Sparkles className="text-purple-400" /> Desafio Rápido</h2>
<div className="bg-white/10 backdrop-blur-md rounded-2xl border border-white/20 overflow-hidden transition-all p-6 text-center">
<p className="text-white/80 mb-4">Teste seus conhecimentos com um desafio de SQL gerado por IA!</p>
<button onClick={onGenerateChallenge} className="bg-gradient-to-r from-purple-500 to-indigo-500 text-white font-bold py-3 px-8 rounded-lg hover:scale-105 transition-transform">
Gerar Desafio
</button>
</div>
</div>
<div className="mt-10">
<h2 className="text-2xl font-bold text-white mb-6 flex items-center gap-2"><Target /> Trilhas de Aprendizado</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{studyTrails.map((trail, index) => {
const completedCount = trail.lessons.filter(l => (userProgress.completedLessons || []).includes(l.id)).length;
const progress = studyTrails.length > 0 && trail.lessons.length > 0 ? (completedCount / trail.lessons.length) * 100 : 0;
let isLocked = false;
if (index > 0) {
const previousTrail = studyTrails[index - 1];
const isPreviousTrailComplete = previousTrail.lessons.every(lesson =>
(userProgress.completedLessons || []).includes(lesson.id)
);
if (!isPreviousTrailComplete) {
isLocked = true;
}
}
return (
<div key={trail.id} className={`bg-white/10 backdrop-blur-md rounded-2xl border border-white/20 overflow-hidden transition-all relative ${isLocked ? 'opacity-60 cursor-not-allowed' : 'hover:border-white/40 cursor-pointer'}`} onClick={() => !isLocked && onSelectTrail(trail)}>
{isLocked && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center z-10">
<Lock />
</div>
)}
<div className={`bg-gradient-to-r ${trail.color} p-6`}>
<div className="flex items-center justify-between mb-3"><div className="text-5xl">{trail.icon}</div><div className="bg-white/20 px-3 py-1 rounded-full text-white text-sm font-bold">{completedCount}/{trail.lessons.length}</div></div>
<h3 className="text-2xl font-bold text-white mb-1">{trail.title}</h3><p className="text-white/80 text-sm">{trail.description}</p>
</div>
<div className="p-6">
<div className="bg-white/20 rounded-full h-2 overflow-hidden mb-3"><div className="bg-gradient-to-r from-green-400 to-emerald-500 h-full rounded-full transition-all duration-500" style={{ width: `${progress}%` }} /></div>
<div className="flex justify-between items-center">
<div className="text-white/60 text-sm">{progress.toFixed(0)}% Completo</div>
<button className="text-white/80 hover:text-white font-bold flex items-center gap-1">Ver Lições <ChevronRight /></button>
</div>
</div>
</div>
);
})}
</div>
</div>
</main>
));
const TrailDetailView = memo(({ selectedTrail, userProgress, onStartLesson, onBack, getContentTypeInfo, filterType, onFilterChange }) => {
const filteredLessons = selectedTrail.lessons.filter(lesson => {
if (filterType === 'all') return true;
return lesson.type === filterType;
});
return (
<main className="max-w-5xl mx-auto px-6 py-8 animate-fade-in">
<button onClick={onBack} className="flex items-center gap-2 text-white/60 hover:text-white mb-6">
<ArrowLeft /> Voltar para as Trilhas
</button>
<div className={`bg-gradient-to-r ${selectedTrail.color} rounded-2xl p-8 mb-8 border border-white/20`}>
<div className="flex items-center justify-between mb-4">
<div className="text-6xl">{selectedTrail.icon}</div>
<div className="text-right"><div className="text-3xl font-bold">{(((selectedTrail.lessons.filter(l => (userProgress.completedLessons || []).includes(l.id)).length) / selectedTrail.lessons.length) * 100).toFixed(0)}%</div><div className="text-white/70">Completo</div></div>
</div>
<h2 className="text-3xl font-bold mb-2">{selectedTrail.title}</h2><p className="text-white/80 mb-6 max-w-2xl">{selectedTrail.description}</p>
</div>
<div className="bg-black/20 backdrop-blur-md rounded-2xl p-8 border border-white/10">
<div className="flex items-center gap-3 mb-6 overflow-x-auto pb-2 -mx-8 px-8">
<button onClick={() => onFilterChange('all')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${filterType === 'all' ? 'bg-white/10 text-white' : 'bg-white/5 text-white/60 hover:bg-white/10 hover:text-white'}`}>Todos</button>
<button onClick={() => onFilterChange('article')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-2 ${filterType === 'article' ? 'bg-white/10 text-white' : 'bg-white/5 text-white/60 hover:bg-white/10 hover:text-white'}`}><FileText className="w-4 h-4" />Artigos</button>
<button onClick={() => onFilterChange('lesson')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-2 ${filterType === 'lesson' ? 'bg-white/10 text-white' : 'bg-white/5 text-white/60 hover:bg-white/10 hover:text-white'}`}><GraduationCap className="w-4 h-4" />Aulas</button>
<button onClick={() => onFilterChange('theory')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-2 ${filterType === 'theory' ? 'bg-white/10 text-white' : 'bg-white/5 text-white/60 hover:bg-white/10 hover:text-white'}`}><BookOpen className="w-4 h-4" />Teoria</button>
<button onClick={() => onFilterChange('practice')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex items-center gap-2 ${filterType === 'practice' ? 'bg-white/10 text-white' : 'bg-white/5 text-white/60 hover:bg-white/10 hover:text-white'}`}><PenTool className="w-4 h-4" />Prática</button>
</div>
<h3 className="text-xl font-bold mb-6 flex items-center gap-2"><BookOpen />Conteúdo da Trilha</h3>
<div className="space-y-4">
{filteredLessons.map((lesson) => {
const lessonIndex = selectedTrail.lessons.findIndex(l => l.id === lesson.id);
const isCompleted = (userProgress.completedLessons || []).includes(lesson.id);
let isLocked = false;
if (lessonIndex > 0) {
const previousLesson = selectedTrail.lessons[lessonIndex - 1];
if (!(userProgress.completedLessons || []).includes(previousLesson.id)) {
isLocked = true;
}
}
const contentType = getContentTypeInfo(lesson.type);
return (
<div key={lesson.id} onClick={() => !isLocked && onStartLesson(selectedTrail, lesson)} className={`bg-gradient-to-r ${contentType.bgGradient} rounded-2xl p-6 border ${isLocked ? 'opacity-50 cursor-not-allowed border-white/10' : 'hover:scale-[1.01] cursor-pointer border-white/20 hover:border-white/30'} transition-all`}>
<div className="flex items-start gap-5">
<div className={`w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 font-bold text-lg ${isCompleted ? 'bg-green-500/20 text-green-300' : isLocked ? 'bg-white/5 text-white/30' : 'bg-cyan-500/20 text-cyan-300'}`}>{isLocked ? <Lock /> : isCompleted ? <Check /> : lessonIndex + 1}</div>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-4 mb-2">
<h4 className="font-bold text-lg">{lesson.title}</h4>
<div className={`px-3 py-1 rounded-lg text-xs font-bold border flex items-center gap-1 whitespace-nowrap ${contentType.color}`}>{lesson.type === 'article' && <FileText className="w-3 h-3" />}{lesson.type === 'lesson' && <GraduationCap className="w-3 h-3" />}{lesson.type === 'theory' && <BookOpen className="w-3 h-3" />}{lesson.type === 'practice' && <PenTool className="w-3 h-3" />}{contentType.label}</div>
</div>
<div className="flex items-center gap-4 text-sm text-white/60 mb-3">
<div className="flex items-center gap-1"><Clock />{lesson.duration}</div>
<div className="flex items-center gap-1"><Star />+{lesson.xp} XP</div>
</div>
{!isLocked && (<button className="bg-white/10 text-white px-6 py-2 rounded-lg font-bold text-sm hover:bg-white/20 transition-colors flex items-center gap-2">{isCompleted ? <><Check className="w-4 h-4" />Revisar</> : <><Play className="w-4 h-4" />Começar</>}</button>)}
</div>
</div>
</div>
);
})}
</div>
</div>
</main>
);
});
const ArticleView = memo(({ currentLesson, onNavigate }) => {
return (
<div className="min-h-screen bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-900 text-white flex flex-col animate-fade-in">
<header className="bg-white/10 border-b border-white/20">
<div className="max-w-4xl mx-auto px-6 py-4 flex items-center gap-4">
<button onClick={() => onNavigate('trailDetail')} className="text-white/80 hover:text-white"><ArrowLeft/></button>
<div className="w-full bg-white/20 h-4 rounded-full"><div className="bg-gradient-to-r from-cyan-400 to-blue-500 h-full rounded-full" style={{width: '100%'}} /></div>
</div>
</header>
<main className="max-w-4xl mx-auto px-6 py-8 flex-1">
<h2 className="text-3xl font-bold mb-6">{currentLesson.title}</h2>
<div className="prose prose-invert prose-lg text-white/90 max-w-none space-y-4">
{currentLesson.content.split('\n\n').map((paragraph, index) => (
<p key={index}>{paragraph}</p>
))}
</div>
</main>
<footer className="bg-white/10 border-t border-white/20 p-6 sticky bottom-0">
<div className="max-w-4xl mx-auto">
<button
onClick={onNavigate}
className="w-full bg-gradient-to-r from-cyan-500 to-blue-500 text-white font-bold py-4 rounded-xl hover:scale-105 transition-transform"
>
Concluir Artigo
</button>
</div>
</footer>
</div>
);
});
const LessonView = memo(({ currentLesson, currentQuestion, userProgress, onCheckAnswer, onNextQuestion, onNavigate, showResult, answeredQuestions, selectedAnswer, setSelectedAnswer, onGetAiExplanation, aiExplanation, isAiExplanationLoading }) => {
const question = currentLesson.questions[currentQuestion];
const progress = ((currentQuestion + 1) / currentLesson.questions.length) * 100;
const getOptionClasses = (index) => {
if (showResult) {
if (index === question.correct) {
return `bg-green-500/30 border-green-400 text-white`;
}
if (selectedAnswer === index) {
return `bg-red-500/30 border-red-400 text-white`;
}
return `bg-white/5 border-white/10 opacity-60 cursor-not-allowed`;
}
if (selectedAnswer === index) {
return `bg-cyan-500/30 border-cyan-400`;
}
return `bg-gray-800/50 border-white/20 text-gray-200 hover:bg-gray-800/70 hover:border-white/30`;
};
const isCorrect = selectedAnswer === question.correct;
return (
<div className="min-h-screen bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-900 text-white flex flex-col">
<header className="bg-white/10 border-b border-white/20">
<div className="max-w-4xl mx-auto px-6 py-4 flex items-center gap-4">
<button onClick={() => onNavigate('trailDetail')} className="text-white/80 hover:text-white"><X/></button>
<div className="w-full bg-white/20 h-4 rounded-full"><div className="bg-gradient-to-r from-cyan-400 to-blue-500 h-full rounded-full transition-all duration-300" style={{width: `${progress}%`}} /></div>
<div className="flex items-center gap-2 text-red-400"> <Heart /> <span className="font-bold">{userProgress.lives}</span> </div>
</div>
</header>
<main className="max-w-4xl mx-auto px-6 py-8 flex-1 w-full">
<h2 className="text-2xl md:text-3xl font-bold mb-8 text-center">{question.question}</h2>
<div className="space-y-4">
{question.options.map((option, index) => (
<button
key={index}
onClick={() => onCheckAnswer(index)}
disabled={showResult}
className={`w-full text-left p-5 rounded-2xl border-2 transition-all ${getOptionClasses(index)}`}
>
{/* Adiciona verificação se a opção é um código para aplicar font-mono */}
<span className={option.includes('SELECT') || option.includes('FROM') ? 'font-mono' : ''}>{option}</span>
</button>
))}
</div>
</main>
{showResult && (
<footer className="bg-white/10 border-t border-white/20 p-6 sticky bottom-0 animate-fade-in">