File size: 81,118 Bytes
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
10a21dd
ddd8084
 
10a21dd
 
ddd8084
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
10a21dd
 
ddd8084
 
 
 
10a21dd
 
ddd8084
 
10a21dd
 
 
 
ddd8084
 
10a21dd
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
ddd8084
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
10a21dd
 
 
 
 
 
 
ddd8084
10a21dd
 
ddd8084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
10a21dd
ddd8084
10a21dd
ddd8084
 
10a21dd
 
 
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
 
 
 
 
 
 
 
 
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
10a21dd
 
ddd8084
10a21dd
 
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd8084
10a21dd
ddd8084
10a21dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GAKR AI - Login/Signup</title>
    <link rel="stylesheet" href="https://cdn.replit.com/agent/bootstrap-agent-dark-theme.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
         :root {
            --gakr-blue: #4285F4;
            --gakr-blue-dark: #1a73e8;
            --gakr-blue-light: #e8f0fe;
            --gakr-grey-text: #5f6368;
            --gakr-grey-hover-bg: rgba(95, 99, 104, 0.1);
         }

          :root[data-bs-theme="dark"] {
             --gakr-blue: #8ab4f8;
             --gakr-blue-dark: #669df6;
             --gakr-blue-light: rgba(138, 180, 248, 0.1);
             --gakr-grey-text: #bdc1c6;
             --gakr-grey-hover-bg: rgba(189, 193, 198, 0.1);
          }

        @import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Poppins', sans-serif;
        }

        html, body {
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 100%;
            width: 100%;
            background: -webkit-linear-gradient(left, #003366,#004080,#0059b3 , #0073e6);
            color: var(--bs-body-color);
            padding-top: calc(64px + 5vh);
            padding-bottom: 5vh;
            min-height: 100vh;
            /* Allow space for modal overlay */
            position: relative;
        }

        ::selection {
            background: var(--gakr-blue);
            color: #fff;
        }

        .wrapper {
            overflow: hidden;
            max-width: 440px;
            width: 90%;
            background: var(--bs-body-bg);
            box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5);
            padding: 30px;
            border-radius: 15px;
            margin-top: 10px;
            margin-bottom: 10px;
            z-index: 10; /* Ensure wrapper is below modal but above background */
        }

        .wrapper .title-text {
            display: flex;
            width: 200%;
        }

        .wrapper .title {
            width: 50%;
            font-size: 35px;
            font-weight: 600;
            text-align: center;
            transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
            color: var(--bs-body-color);
        }

        .wrapper .slide-controls {
            position: relative;
            display: flex;
            height: 50px;
            width: 100%;
            overflow: hidden;
            margin: 30px 0 10px 0;
            justify-content: space-between;
            border: 1px solid var(--bs-border-color);
            border-radius: 15px;
        }

        .slide-controls .slide {
            height: 100%;
            width: 100%;
            color: var(--bs-body-color);
            font-size: 18px;
            font-weight: 500;
            text-align: center;
            line-height: 48px;
            cursor: pointer;
            z-index: 1;
            transition: all 0.6s ease;
        }

        .slide-controls label.signup{
            color: var(--bs-body-color);
        }

        .slide-controls .slider-tab {
            position: absolute;
            height: 100%;
            width: 50%;
            left: 0;
            z-index: 0;
            border-radius: 15px;
            background: var(--gakr-blue);
            transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }

        input[type="radio"]{
          display: none;
        }

        #signup:checked ~ .slider-tab{
          left: 50%;
        }
        #signup:checked ~ label.signup{
          color: #fff;
          cursor: default;
          user-select: none;
        }
        #signup:checked ~ label.login{
          color: var(--bs-body-color);
        }
        #login:checked ~ label.signup{
          color: var(--bs-body-color);
        }
        #login:checked ~ label.login{
          color: #fff;
          cursor: default;
          user-select: none;
        }

        .wrapper .form-container {
            width: 100%;
            overflow: hidden;
        }

        .form-container .form-inner {
            display: flex;
            width: 200%;
        }

        .form-container .form-inner form {
            width: 50%;
            transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }

        .form-inner form .field {
            height: 50px;
            width: 100%;
            margin-top: 20px;
            position: relative;
        }

         .form-inner form .field:has(+ .field.btn) {
              margin-bottom: 25px;
         }

        .form-inner form .field input{
            height: 100%;
            width: 100%;
            outline: none;
            padding-left: 15px;
            border-radius: 15px;
            border: 1px solid var(--bs-border-color);
            border-bottom-width: 2px;
            font-size: 17px;
            transition: all 0.3s ease;
            color: var(--bs-body-color);
            background-color: var(--bs-body-bg);
        }

        .form-inner form .field input.error {
             border-color: red;
        }

        .form-inner form .field input::placeholder{
            color: var(--bs-secondary-color);
            transition: all 0.3s ease;
        }

        form .field input:focus::placeholder{
            color: var(--gakr-blue);
        }

        .form-inner form .pass-link{
          margin-top: 5px;
            font-size: 0.9rem;
            text-align: right; /* Align to right */
        }

        .form-inner form .signup-link{
          text-align: center;
          margin-top: 30px;
            font-size: 0.9rem;
        }

        .form-inner form .pass-link a,
        .form-inner form .signup-link a{
            color: var(--gakr-blue);
            text-decoration: none;
            transition: color 0.2s ease-in-out;
        }

        .form-inner form .pass-link a:hover,
        form-inner form .signup-link a:hover{
          text-decoration: underline;
          color: var(--gakr-blue-dark);
        }

        form .btn {
            height: 50px;
            width: 100%;
            margin-top: 20px;
            border-radius: 15px;
            position: relative;
            overflow: hidden;
            background: none;
            transition: none;
        }

        form .btn input[type="submit"] {
            height: 100%;
            width: 100%;
            z-index: 1;
            position: relative;
            background: var(--gakr-blue);
            border: none;
            color: #fff;
            padding: 0;
            border-radius: 15px;
            font-size: 20px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out, transform 0.1s ease-in-out;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        form .btn input[type="submit"]:hover {
            background-color: var(--gakr-blue-dark);
        }

        form .btn input[type="submit"]:active {
             transform: scale(0.98);
             transition: background-color 0s, transform 0.1s;
        }

        .error-message {
            color: red;
            font-size: 0.8rem;
            margin-top: 4px;
            position: absolute;
            bottom: -18px;
            left: 15px;
            white-space: nowrap;
        }

         .form-message {
            text-align: center;
            margin-top: 20px;
            font-size: 0.9rem;
            min-height: 1.2em;
         }

         .form-message.success {
            color: green;
         }

         .form-message.error {
            color: red;
         }

         .loading-spinner {
            display: inline-block;
            width: 18px;
            height: 18px;
            border: 3px solid rgba(255, 255, 255, .3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
            margin-left: 10px;
            vertical-align: middle;
         }

         @keyframes spin {
           to { -webkit-transform: rotate(360deg); }
         }

         .form-inner form .btn input[type="submit"]:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            position: relative;
         }

         /* --- Modal Styles --- */
         .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6); /* Semi-transparent black overlay */
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 100; /* On top of everything */
            visibility: hidden; /* Hidden by default */
            opacity: 0;
            transition: visibility 0s, opacity 0.3s ease-in-out;
         }

         .modal-overlay.show {
            visibility: visible;
            opacity: 1;
         }

         .modal-content {
            background-color: var(--bs-body-bg);
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0px 5px 20px rgba(0, 0, 0, 0.7);
            text-align: center;
            max-width: 350px;
            width: 80%;
            transform: translateY(-20px); /* Slight animation on show */
            transition: transform 0.3s ease-in-out;
         }

         .modal-overlay.show .modal-content {
             transform: translateY(0);
         }

         .modal-message {
            font-size: 1.1rem;
            margin-bottom: 25px;
            color: var(--bs-body-color);
         }
         .modal-message p {
            margin-bottom: 10px; /* Spacing for paragraphs in modal message */
            line-height: 1.4;
         }
         .modal-message strong {
            font-size: 1.2rem; /* Heading for attempts message */
            display: block;
            margin-bottom: 15px;
         }
         .modal-message ul {
            list-style: none;
            padding: 0;
            margin-bottom: 20px;
         }
         .modal-message ul li {
            margin-bottom: 8px;
            font-size: 1rem;
         }


         .modal-button {
            background-color: var(--gakr-blue);
            color: #fff;
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out, transform 0.1s ease-in-out;
         }

         .modal-button:hover {
            background-color: var(--gakr-blue-dark);
         }

         .modal-button:active {
            transform: scale(0.98);
         }
         
         .modal-buttons-stacked {
            display: flex;
            flex-direction: column; /* Stack buttons vertically */
            gap: 10px;
            margin-top: 20px;
         }

         .modal-buttons-stacked .modal-button {
            width: 100%; /* Make buttons full width */
         }

         .modal-buttons-inline {
            display: flex;
            justify-content: space-between; /* Space them out */
            gap: 15px;
            margin-top: 20px;
         }
         .modal-buttons-inline .modal-button {
             flex-grow: 1; /* Allow buttons to grow to fill space */
             max-width: none; /* Override max-width from .modal-buttons */
         }


         /* Eye icon styles */
         .field .toggle-password {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: var(--bs-secondary-color);
            font-size: 0.9rem;
         }

         .field .toggle-password:hover {
             color: var(--gakr-blue);
         }

         /* Added styles for Forgot/Reset Modals */
         .modal-form {
             text-align: left;
             margin-top: 20px;
         }
         .modal-form .field {
             margin-bottom: 15px;
             height: auto; /* Override default field height */
         }
         .modal-form label {
             display: block;
             margin-bottom: 5px;
             font-size: 0.9rem;
             color: var(--bs-body-color);
         }
         .otp-input-container {
             display: flex;
             gap: 5px;
             justify-content: center;
             margin-bottom: 10px;
         }
         .otp-digit {
             width: 40px;
             height: 40px;
             text-align: center;
             border: 1px solid var(--bs-border-color);
             border-radius: 5px;
             font-size: 1.2rem;
             background-color: var(--bs-body-bg);
             color: var(--bs-body-color);
         }
         .otp-digit:focus {
             border-color: var(--gakr-blue);
             outline: none;
         }
         .modal-form .error-message {
            position: static; /* Remove absolute positioning */
            margin-top: 5px;
            margin-left: 0;
            white-space: normal; /* Allow message to wrap */
         }
         .modal-buttons {
             display: flex;
             justify-content: center;
             gap: 15px;
             margin-top: 20px;
         }
         .modal-buttons button {
             width: 100%;
             max-width: 150px;
         }

        /* Header styles */
        .gakr-chat-header {
            padding: 0.75rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--bs-border-color);
            height: 64px;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            width: 100%;
            background-color: var(--bs-body-bg);
            z-index: 10;
        }

        .gakr-logo-area {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .gakr-brand-logo {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .gakr-brand-text {
            font-size: 1.25rem;
            font-weight: 500;
            color: var(--gakr-blue);
        }

        .gakr-nav-controls {
            display: flex;
            align-items: center;
        }

        .gakr-login-button {
            color: var(--gakr-blue);
            text-decoration: none;
            background: transparent;
            border: 1px solid var(--gakr-blue);
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-size: 0.9rem;
            transition: background-color 0.2s;
        }

        .gakr-login-button:hover {
            background-color: rgba(66, 133, 244, 0.1);
        }

        .gakr-profile-button {
            color: var(--gakr-blue);
            text-decoration: none;
            background: transparent;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-size: 0.9rem;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .gakr-profile-button:hover {
            background-color: rgba(66, 133, 244, 0.1);
        }
    </style>
</head>
<body>
    <header class="gakr-chat-header">
        <div class="gakr-logo-area">
            <a href="/" class="gakr-brand-logo">
                <i class="fas fa-robot" style="color: var(--gakr-blue);"></i>
            </a>
            <a href="/" class="gakr-brand-text" style="text-decoration: none;">GAKR AI</a>
        </div>

        <div class="gakr-nav-controls" id="authButtonContainer">
            <a href="/auth" class="gakr-login-button">Sign in / Register</a>
        </div>
    </header>

    <div class="wrapper">
        <div class="title-text">
            <div class="title login">Login Form</div>
            <div class="title signup">Signup Form</div>
        </div>
        <div class="form-container">
            <div class="slide-controls">
                <input type="radio" name="slide" id="login" checked>
                <input type="radio" name="slide" id="signup">
                <label for="login" class="slide login">Login</label>
                <label for="signup" class="slide signup">Signup</label>
                <div class="slider-tab"></div>
            </div>
            <div class="form-inner">
                <form action="#" class="login" id="loginForm">
                    <div class="field">
                        <input type="text" placeholder="Username or Email" required id="loginUsernameOrEmail" name="username_or_email">
                        <div class="error-message" id="loginUsernameOrEmailError"></div>
                    </div>
                    <div class="field">
                        <input type="password" placeholder="Password" required id="loginPassword" name="password">
                        <span class="toggle-password fa-solid fa-eye-slash"></span>
                        <div class="error-message" id="loginPasswordError"></div>
                    </div>
                    <div class="pass-link"><a href="#" id="forgotPasswordLink">Forgot password?</a></div>
                    <div class="field btn">
                        <input type="submit" value="Login">
                    </div>
                    <div class="signup-link">Not a member? <a href="">Signup now</a></div>
                </form>
                <form action="#" class="signup" id="signupForm">
                    <div class="field">
                        <input type="text" placeholder="Name" required id="signupName" name="name">
                        <div class="error-message" id="signupNameError"></div>
                    </div>
                    <div class="field">
                        <input type="text" placeholder="Email Address" required id="signupEmail" name="email">
                        <div class="error-message" id="signupEmailError"></div>
                    </div>
                    <div class="field">
                        <input type="password" placeholder="Password" required id="signupPassword" name="password">
                        <span class="toggle-password fa-solid fa-eye-slash"></span>
                        <div class="error-message" id="signupPasswordError"></div>
                    </div>
                    <div class="field">
                        <input type="password" placeholder="Confirm password" required id="signupConfirmPassword" name="confirm_password">
                        <span class="toggle-password fa-solid fa-eye-slash"></span>
                        <div class="error-message" id="signupConfirmPasswordError"></div>
                    </div>
                    <div class="field btn">
                        <input type="submit" value="Signup">
                    </div>
                </form>
            </div>
        </div>
        <div class="form-message" id="generalFormMessage"></div>
    </div>

    <div class="modal-overlay" id="customModal">
        <div class="modal-content">
            <div class="modal-message" id="modalMessage"></div>
            <div id="modalButtonsContainer" class="modal-buttons">
            </div>
        </div>
    </div>

    <div class="modal-overlay" id="forgotPasswordRequestModal">
        <div class="modal-content" style="max-width: 450px;">
            <h3 style="text-align: center; margin-bottom: 20px; color: var(--gakr-blue);">Reset Password</h3>
            <p class="modal-message" id="forgotModalMessage" style="text-align: center; margin-bottom: 25px;">Enter your registered email address to receive a password reset code.</p>
            
            <form id="forgotPasswordRequestForm" class="modal-form">
                <div class="field" style="margin-bottom: 30px;">
                    <label for="forgotEmail" style="display: block; margin-bottom: 8px; font-weight: 500; color: var(--bs-body-color);">Email Address:</label>
                    <input type="email" id="forgotEmail" name="email" required style="width: 100%; padding: 12px; border: 2px solid var(--bs-border-color); border-radius: 8px; font-size: 16px; background-color: var(--bs-body-bg); color: var(--bs-body-color);" placeholder="Enter your email">
                    <div class="error-message" id="forgotEmailError" style="margin-top: 8px;"></div>
                </div>
                <div class="modal-buttons-stacked">
                    <button type="submit" class="modal-button" id="forgotSubmitButton" style="width: 100%; padding: 12px; font-size: 16px;">Send Reset Code</button>
                    <button type="button" class="modal-button" id="forgotCancelButton" style="width: 100%; padding: 12px; font-size: 16px; background-color: var(--bs-secondary-color); margin-top: 10px;">Cancel</button>
                </div>
            </form>

            <div id="otpSection" style="display: none;">
                <h3 style="text-align: center; margin-bottom: 20px; color: var(--gakr-blue);">Enter Verification Code</h3>
                <p style="text-align: center; margin-bottom: 25px; color: var(--bs-secondary-color);">We've sent a 8-digit code to your email. Enter it below to continue.</p>
                <form id="verifyOtpForm" class="modal-form">
                    <div class="field" style="margin-bottom: 30px;">
                        <label style="display: block; margin-bottom: 15px; font-weight: 500; color: var(--bs-body-color); text-align: center;">Verification Code:</label>
                        <div class="otp-input-container" style="display: flex; justify-content: center; gap: 8px; margin-bottom: 10px;">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                            <input type="text" class="otp-digit" maxlength="1" pattern="\d" required style="width: 45px; height: 50px; text-align: center; font-size: 20px; font-weight: bold; border: 2px solid var(--bs-border-color); border-radius: 8px; background-color: var(--bs-body-bg); color: var(--bs-body-color);">
                        </div>
                        <input type="hidden" id="otpInput" name="otp">
                        <div class="error-message" id="otpError" style="text-align: center; margin-top: 10px;"></div>
                    </div>
                    <div class="modal-buttons-stacked">
                        <button type="submit" class="modal-button" id="verifyOtpButton" style="width: 100%; padding: 12px; font-size: 16px;">Verify Code</button>
                        <button type="button" class="modal-button" id="resendOtpButton" style="width: 100%; padding: 12px; font-size: 16px; margin-top: 10px;">Send Code Again</button>
                        <button type="button" class="modal-button" id="otpCancelButton" style="width: 100%; padding: 12px; font-size: 16px; background-color: var(--bs-secondary-color); margin-top: 10px;">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal-overlay" id="resetPasswordModal">
        <div class="modal-content">
            <p class="modal-message">Enter your new password.</p>
            <form id="resetPasswordForm" class="modal-form">
                <div class="field">
                    <label for="resetEmail">Email:</label>
                    <input type="email" id="resetEmail" name="email" required readonly style="background-color: var(--bs-secondary-bg); cursor: not-allowed;">
                    <div class="error-message" id="resetEmailError"></div>
                </div>
                <div class="field">
                    <label for="newPassword">New Password:</label>
                    <input type="password" id="newPassword" name="new_password" required>
                    <span class="toggle-password fa-solid fa-eye-slash"></span>
                    <div class="error-message" id="newPasswordError"></div>
                </div>
                <div class="field">
                    <label for="confirmNewPassword">Confirm New Password:</label>
                    <input type="password" id="confirmNewPassword" name="confirm_new_password" required>
                    <span class="toggle-password fa-solid fa-eye-slash"></span>
                    <div class="error-message" id="confirmNewPasswordError"></div>
                </div>
                <div class="modal-buttons-stacked">
                    <button type="submit" class="modal-button" id="resetSubmitButton">Reset Password</button>
                    <button type="button" class="modal-button" id="resetCancelButton" style="background-color: var(--bs-secondary-color);">Cancel</button>
                </div>
            </form>
        </div>
    </div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // --- Authentication Status Check ---
        function updateAuthButton() {
            const authButtonContainer = document.getElementById('authButtonContainer');
            const userIsLoggedIn = localStorage.getItem('isLoggedIn') === 'true';

            if (userIsLoggedIn) {
                authButtonContainer.innerHTML = `
                    <a href="/profile" class="gakr-profile-button">
                        <i class="fas fa-user-circle me-2"></i>Profile
                    </a>
                `;
                 const profileButton = authButtonContainer.querySelector('.gakr-profile-button');
                 if (profileButton) {
                     profileButton.addEventListener('click', function(event) {
                         console.log("Profile button clicked!");
                     });
                 }
            } else {
                authButtonContainer.innerHTML = `
                    <a href="/auth" class="gakr-login-button">Sign in / Register</a>
                `;
            }
        }

        updateAuthButton();
        window.addEventListener('focus', updateAuthButton);
        window.addEventListener('storage', updateAuthButton);

        const loginText = document.querySelector(".title-text .login");
        const loginFormDiv = document.querySelector("form.login");
        const signupLink = document.querySelector("form .signup-link a");
        const loginRadio = document.getElementById('login');
        const signupRadio = document.getElementById('signup');

        const loginForm = document.getElementById('loginForm');
        const signupForm = document.getElementById('signupForm');

        // Existing form inputs and error displays
        const loginUsernameOrEmailInput = document.getElementById('loginUsernameOrEmail');
        const loginPasswordInput = document.getElementById('loginPassword');
        const loginSubmitButton = loginForm ? loginForm.querySelector('input[type="submit"]') : null;

        const signupNameInput = document.getElementById('signupName');
        const signupEmailInput = document.getElementById('signupEmail');
        const signupPasswordInput = document.getElementById('signupPassword');
        const signupConfirmPasswordInput = document.getElementById('signupConfirmPassword');
        const signupSubmitButton = signupForm ? signupForm.querySelector('input[type="submit"]') : null;

        const loginUsernameOrEmailError = document.getElementById('loginUsernameOrEmailError');
        const loginPasswordError = document.getElementById('loginPasswordError');

        const signupNameError = document.getElementById('signupNameError');
        const signupEmailError = document.getElementById('signupEmailError');
        const signupPasswordError = document.getElementById('signupPasswordError');
        const signupConfirmPasswordError = document.getElementById('signupConfirmPasswordError');

        const generalFormMessage = document.getElementById('generalFormMessage');

        // Modal elements (main alert modal)
        const customModal = document.getElementById('customModal');
        const modalMessageDiv = document.getElementById('modalMessage');
        const modalButtonsContainer = document.getElementById('modalButtonsContainer');

        // OTP digit inputs
        const otpDigits = document.querySelectorAll('.otp-digit');
        otpDigits.forEach((input, index) => {
            input.addEventListener('input', function() {
                if (this.value.length === 1 && index < otpDigits.length - 1) {
                    otpDigits[index + 1].focus();
                }
            });
            input.addEventListener('keydown', function(e) {
                if (e.key === 'Backspace' && this.value === '' && index > 0) {
                    otpDigits[index - 1].focus();
                }
            });
        });
        const forgotPasswordLink = document.getElementById('forgotPasswordLink');
        const forgotPasswordRequestModal = document.getElementById('forgotPasswordRequestModal'); // The main overlay for forgot/otp
        const forgotModalMessage = document.getElementById('forgotModalMessage'); // Message within the forgot/otp modal

        // Elements for Step 1: Request Email
        const forgotPasswordRequestForm = document.getElementById('forgotPasswordRequestForm');
        const forgotEmailInput = document.getElementById('forgotEmail');
        const forgotEmailError = document.getElementById('forgotEmailError');
        const forgotSubmitButton = document.getElementById('forgotSubmitButton');
        const forgotCancelButton = document.getElementById('forgotCancelButton');

        // Elements for Step 2: Enter OTP
        const otpSection = document.getElementById('otpSection'); // The container for OTP input and buttons
        const verifyOtpForm = document.getElementById('verifyOtpForm');
        const otpInput = document.getElementById('otpInput');
        const otpError = document.getElementById('otpError');
        const verifyOtpButton = document.getElementById('verifyOtpButton');
        const resendOtpButton = document.getElementById('resendOtpButton');
        const otpCancelButton = document.getElementById('otpCancelButton');

        // Reset Password Modal elements (Step 3: New Password)
        const resetPasswordModal = document.getElementById('resetPasswordModal');
        const resetPasswordForm = document.getElementById('resetPasswordForm');
        const resetEmailInput = document.getElementById('resetEmail'); // Hidden but read-only email field
        const newPasswordInput = document.getElementById('newPassword');
        const confirmNewPasswordInput = document.getElementById('confirmNewPassword');
        const resetEmailError = document.getElementById('resetEmailError'); // Error for reset email (should be rare)
        const newPasswordError = document.getElementById('newPasswordError');
        const confirmNewPasswordError = document.getElementById('confirmNewPasswordError');
        const resetSubmitButton = document.getElementById('resetSubmitButton');
        const resetCancelButton = document.getElementById('resetCancelButton');

        // New: Login Attempt Counter
        let loginAttempts = 0;
        const MAX_LOGIN_ATTEMPTS = 3;

        // Stores the email across the forgot password/OTP/reset flow
        let currentForgotEmail = '';

        // Resend OTP cooldown variables
        let resendCooldown = 0;
        let resendInterval = null;

        // Function to start resend cooldown timer
        function startResendCooldown() {
            resendCooldown = 60; // 60 seconds
            resendOtpButton.disabled = true;
            resendOtpButton.textContent = `Send Again (60s)`;
            resendOtpButton.style.backgroundColor = 'var(--bs-secondary-color)'; // Gray during cooldown

            resendInterval = setInterval(() => {
                resendCooldown--;
                if (resendCooldown > 0) {
                    resendOtpButton.textContent = `Send Again (${resendCooldown}s)`;
                } else {
                    clearInterval(resendInterval);
                    resendInterval = null;
                    resendOtpButton.disabled = false;
                    resendOtpButton.textContent = 'Send Code Again';
                    resendOtpButton.style.backgroundColor = ''; // Reset to default (primary blue)
                }
            }, 1000);
        }

        // Function to clear all error messages and input error classes
        function clearErrors(formType = 'all') {
            if (formType === 'all' || formType === 'main') {
                document.querySelectorAll('.error-message').forEach(el => el.textContent = '');
                document.querySelectorAll('.form-inner form .field input').forEach(el => el.classList.remove('error'));
                if (generalFormMessage) {
                    generalFormMessage.textContent = '';
                    generalFormMessage.className = 'form-message';
                }
            }
            if (formType === 'all' || formType === 'forgot') {
                if (forgotEmailError) forgotEmailError.textContent = '';
                if (forgotEmailInput) forgotEmailInput.classList.remove('error');
                // Also clear the general forgotModalMessage when resetting for new flow
                if (forgotModalMessage) forgotModalMessage.innerHTML = 'Enter your registered email to request a password reset.';
            }
            if (formType === 'all' || formType === 'otp') {
                if (otpError) otpError.textContent = '';
                if (otpInput) otpInput.classList.remove('error');
            }
            if (formType === 'all' || formType === 'reset') {
                if (resetEmailError) resetEmailError.textContent = '';
                if (newPasswordError) newPasswordError.textContent = '';
                if (confirmNewPasswordError) confirmNewPasswordError.textContent = '';
                if (resetEmailInput) resetEmailInput.classList.remove('error');
                if (newPasswordInput) newPasswordInput.classList.remove('error');
                if (confirmNewPasswordInput) confirmNewPasswordInput.classList.remove('error');
            }
        }

        // Function to display general form-level message (below the forms)
        function displayFormMessage(message, type = 'info') {
            if (generalFormMessage) {
                generalFormMessage.textContent = message;
                generalFormMessage.className = 'form-message ' + type;
            }
        }

        // Universal modal display function
        function showCustomModal(modalElement) {
            modalElement.classList.add('show');
        }

        // Universal modal hide function
        function hideCustomModal(modalElement) {
            modalElement.classList.remove('show');
            clearErrors(); // Clear all errors when any modal is hidden
        }

        // Function to show a flexible custom modal (for general alerts/info)
        function showFlexibleModal(messageHTML, buttonsConfig, callback = null) {
            modalMessageDiv.innerHTML = messageHTML;
            modalButtonsContainer.innerHTML = ''; // Clear previous buttons

            if (buttonsConfig && buttonsConfig.length > 0) {
                const isInline = buttonsConfig.every(btn => !btn.newline);
                modalButtonsContainer.className = isInline ? 'modal-buttons-inline' : 'modal-buttons-stacked';

                buttonsConfig.forEach(btnConf => {
                    const button = document.createElement('button');
                    button.className = 'modal-button';
                    button.textContent = btnConf.text;
                    if (btnConf.style) {
                        button.style = btnConf.style;
                    }
                    button.onclick = function() {
                        hideCustomModal(customModal);
                        if (btnConf.action && typeof btnConf.action === 'function') {
                            btnConf.action();
                        }
                        if (callback && typeof callback === 'function') {
                            callback();
                        }
                    };
                    modalButtonsContainer.appendChild(button);
                });
            } else {
                const okButton = document.createElement('button');
                okButton.className = 'modal-button';
                okButton.textContent = 'OK';
                okButton.onclick = function() {
                    hideCustomModal(customModal);
                    if (callback && typeof callback === 'function') {
                        callback();
                    }
                };
                modalButtonsContainer.classList.remove('modal-buttons-inline', 'modal-buttons-stacked');
                modalButtonsContainer.classList.add('modal-buttons');
                modalButtonsContainer.appendChild(okButton);
            }
            showCustomModal(customModal);
        }

        // Slide logic
        function slideToSignup() {
            if (loginFormDiv && loginText) {
                loginFormDiv.style.marginLeft = "-50%";
                loginText.style.marginLeft = "-50%";
                clearErrors('main');
            }
        }

        function slideToLogin() {
            if (loginFormDiv && loginText) {
                loginFormDiv.style.marginLeft = "0%";
                loginText.style.marginLeft = "0%";
                clearErrors('main');
            }
        }

        // Event listeners for radio buttons and signup link
        if (signupRadio) {
            signupRadio.addEventListener('change', function() {
                if (this.checked) {
                    slideToSignup();
                }
            });
        }

        if (loginRadio) {
            loginRadio.addEventListener('change', function() {
                if (this.checked) {
                    slideToLogin();
                }
            });
        }

        if (signupLink && signupRadio) {
            signupLink.onclick = ((e) => {
                e.preventDefault();
                signupRadio.checked = true;
                slideToSignup();
            });
        }

        // Handle URL parameter for initial tab
        const urlParams = new URLSearchParams(window.location.search);
        const showSignup = urlParams.get('signup');

        if (showSignup === 'true') {
            if (signupRadio) {
                signupRadio.checked = true;
                slideToSignup();
            }
        } else {
            if (loginRadio) {
                loginRadio.checked = true;
                slideToLogin();
            }
        }

        // Function to toggle password visibility
        function setupPasswordToggle(passwordInput, toggleIcon) {
            if (passwordInput && toggleIcon) {
                toggleIcon.addEventListener('click', function() {
                    const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                    passwordInput.setAttribute('type', type);
                    this.classList.toggle('fa-eye');
                    this.classList.toggle('fa-eye-slash');
                });
            }
        }

        // Setup password toggles for all password fields
        setupPasswordToggle(loginPasswordInput, document.querySelector('#loginForm .toggle-password'));
        setupPasswordToggle(signupPasswordInput, document.querySelector('#signupForm #signupPassword + .toggle-password'));
        setupPasswordToggle(signupConfirmPasswordInput, document.querySelector('#signupForm #signupConfirmPassword + .toggle-password'));
        setupPasswordToggle(newPasswordInput, document.querySelector('#resetPasswordForm #newPassword + .toggle-password'));
        setupPasswordToggle(confirmNewPasswordInput, document.querySelector('#resetPasswordForm #confirmNewPassword + .toggle-password'));


        // Login Form Submission Handler
        if (loginForm) {
            loginForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                clearErrors('main'); // Clear main form errors

                // Only proceed if login attempts are below limit
                if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
                    showLoginAttemptsLimitModal();
                    return; // Stop submission
                }

                let isValid = true;

                const usernameOrEmail = loginUsernameOrEmailInput.value.trim();
                const password = loginPasswordInput.value.trim();

                if (usernameOrEmail === '') {
                    isValid = false;
                    loginUsernameOrEmailError.textContent = 'Username or Email is required';
                    loginUsernameOrEmailInput.classList.add('error');
                }
                if (password === '') {
                    isValid = false;
                    loginPasswordError.textContent = 'Password is required';
                    loginPasswordInput.classList.add('error');
                }

                if (isValid) {
                    // Check if user exists
                    try {
                        const checkResponse = await fetch('/api/check_user', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ identifier: usernameOrEmail })
                        });
                        const checkData = await checkResponse.json();
                        if (!checkData.exists) {
                            loginUsernameOrEmailError.textContent = 'User does not exist.';
                            loginUsernameOrEmailInput.classList.add('error');
                            return;
                        }
                    } catch (error) {
                        console.error('Error checking user:', error);
                        // Proceed anyway
                    }
                    submitFormData(event.target, loginSubmitButton, '/api/login', 'main');
                }
            });
        }

        // Signup Form Submission Handler
        if (signupForm) {
            signupForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                clearErrors('main');

                let isValid = true;

                const name = signupNameInput.value.trim();
                const email = signupEmailInput.value.trim();
                const password = signupPasswordInput.value.trim();
                const confirmPassword = signupConfirmPasswordInput.value.trim();

                if (name === '') {
                    isValid = false;
                    signupNameError.textContent = 'Name is required';
                    signupNameInput.classList.add('error');
                }

                if (email === '') {
                    isValid = false;
                    signupEmailError.textContent = 'Email is required';
                    signupEmailInput.classList.add('error');
                } else if (!isValidEmail(email)) {
                    isValid = false;
                    signupEmailError.textContent = 'Enter a valid email address';
                    signupEmailInput.classList.add('error');
                }

                if (password === '') {
                    isValid = false;
                    signupPasswordError.textContent = 'Password is required';
                    signupPasswordInput.classList.add('error');
                } else if (password.length < 6) {
                    isValid = false;
                    signupPasswordError.textContent = 'Password must be at least 6 characters';
                    signupPasswordInput.classList.add('error');
                }

                if (confirmPassword === '') {
                    isValid = false;
                    signupConfirmPasswordError.textContent = 'Confirm password is required';
                    signupConfirmPasswordInput.classList.add('error');
                } else if (password !== confirmPassword) {
                    isValid = false;
                    signupConfirmPasswordError.textContent = 'Passwords do not match';
                    signupConfirmPasswordInput.classList.add('error');
                    signupPasswordInput.classList.add('error');
                }

                if (isValid) {
                    // Check if user already exists
                    try {
                        const checkResponse = await fetch('/api/check_user', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ identifier: email })
                        });
                        const checkData = await checkResponse.json();
                        if (checkData.exists) {
                            signupEmailError.textContent = 'Email already registered.';
                            signupEmailInput.classList.add('error');
                            return;
                        }
                    } catch (error) {
                        console.error('Error checking user:', error);
                        // Proceed anyway
                    }
                    submitFormData(event.target, signupSubmitButton, '/api/signup', 'main');
                }
            });
        }

        // Forgot Password Link Handler (Initial Click)
        if (forgotPasswordLink) {
            forgotPasswordLink.addEventListener('click', function(event) {
                event.preventDefault();
                clearErrors('forgot'); // Clear errors for email request
                clearErrors('otp'); // Clear errors for OTP section

                forgotPasswordRequestForm.reset(); // Clear email input
                otpInput.value = ''; // Clear OTP input
                // Reset the general message for the forgot password modal
                forgotModalMessage.innerHTML = 'Enter your registered email to request a password reset.';

                // Show the email request form and hide the OTP section
                forgotPasswordRequestForm.style.display = 'block';
                if (otpSection) otpSection.style.display = 'none'; // Ensure OTP section is hidden initially

                // Reset modal size for email input
                const modalContent = forgotPasswordRequestModal.querySelector('.modal-content');
                if (modalContent) {
                    modalContent.style.maxWidth = '450px';
                }

                showCustomModal(forgotPasswordRequestModal);
            });
        }

        // Step 1: Forgot Password Request Form Submission Handler (Requests OTP)
        if (forgotPasswordRequestForm) {
            forgotPasswordRequestForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                clearErrors('forgot'); // Clear errors specific to the email request form

                let isValid = true;
                const email = forgotEmailInput.value.trim();

                if (email === '') {
                    isValid = false;
                    forgotEmailError.textContent = 'Email is required.';
                    forgotEmailInput.classList.add('error');
                } else if (!isValidEmail(email)) {
                    isValid = false;
                    forgotEmailError.textContent = 'Enter a valid email address.';
                    forgotEmailInput.classList.add('error');
                }

                if (isValid) {
                    forgotSubmitButton.disabled = true;
                    forgotSubmitButton.innerHTML = '<span class="loading-spinner"></span> Sending OTP...';

                    try {
                        const response = await fetch('/api/forgot_password_request', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ email: email })
                        });

                        const result = await response.json();

                        if (response.ok) {
                            currentForgotEmail = email; // Store email for subsequent steps

                            // Transition to OTP input section
                            forgotPasswordRequestForm.style.display = 'none';
                            if (otpSection) otpSection.style.display = 'block';
                            otpInput.value = ''; // Clear previous OTP in case of resend

                            // Increase modal size for OTP section
                            const modalContent = forgotPasswordRequestModal.querySelector('.modal-content');
                            if (modalContent) {
                                modalContent.style.maxWidth = '550px';
                            }

                            // Update message for OTP section
                            let messageText = `<p>An OTP has been sent to <strong>${email}</strong>. Please enter it below.</p>`;
                            // Note: Do not display simulated OTP in production. This is for testing convenience.
                            // if (result.simulated_otp) {
                            //     messageText += `<p><strong>SIMULATED OTP (FOR TESTING):</strong> ${result.simulated_otp}</p>`;
                            // }
                            forgotModalMessage.innerHTML = messageText;
                            startResendCooldown(); // Start the cooldown timer for the resend button

                        } else {
                            // Handle different error types
                            if (response.status === 404) {
                                // Email not registered - show registration modal
                                hideCustomModal(forgotPasswordRequestModal);
                                showFlexibleModal(
                                    '<p>The email address you entered is not registered yet.</p><p>Please sign up to create an account.</p>',
                                    [
                                        { text: 'Sign Up', action: () => {
                                            signupRadio.checked = true;
                                            slideToSignup();
                                            // Pre-fill the email in signup form
                                            signupEmailInput.value = email;
                                        }},
                                        { text: 'Try Again', style: 'background-color: var(--bs-secondary-color);' }
                                    ]
                                );
                            } else {
                                // Other errors (400, 500) - show in modal
                                result.status = response.status;
                                displayModalFormErrors(result, forgotPasswordRequestForm, 'forgot');
                            }
                        }
                    } catch (error) {
                        console.error('Fetch error:', error);
                        showFlexibleModal('<p>Network error. Could not request OTP. Please try again.</p>', [{ text: 'OK' }]);
                    } finally {
                        forgotSubmitButton.disabled = false;
                        forgotSubmitButton.innerHTML = 'Request OTP';
                    }
                }
            });
        }

        // Step 2: OTP Verification Form Submission Handler
        if (verifyOtpForm) {
            verifyOtpForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                clearErrors('otp'); // Clear errors specific to the OTP verification form

                let isValid = true;
                const otpDigits = document.querySelectorAll('.otp-digit');
                const otp = Array.from(otpDigits).map(d => d.value).join('');

                if (otp.length !== 8 || !/^\d{8}$/.test(otp)) {
                    isValid = false;
                    otpError.textContent = 'Please enter all 8 digits of the OTP.';
                    otpDigits.forEach(d => d.classList.add('error'));
                }

                if (isValid) {
                    otpInput.value = otp; // Set hidden input
                    verifyOtpButton.disabled = true;
                    verifyOtpButton.innerHTML = '<span class="loading-spinner"></span> Verifying...';

                    try {
                        const response = await fetch('/api/verify_otp', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ email: currentForgotEmail, otp: otp })
                        });

                        const result = await response.json();

                        if (response.ok) {
                            hideCustomModal(forgotPasswordRequestModal); // Hide the OTP modal
                            resetEmailInput.value = currentForgotEmail; // Pre-fill email in new password form
                            newPasswordInput.value = ''; // Clear new password field
                            confirmNewPasswordInput.value = ''; // Clear confirm new password field
                            showCustomModal(resetPasswordModal); // Show the new password modal

                        } else {
                            otpError.textContent = result.message || 'OTP verification failed.';
                            otpInput.classList.add('error');
                            otpInput.classList.add('error'); // Ensure input field is marked
                            // Update the main message area of the OTP modal if a general message is returned
                            if (result.message) {
                                forgotModalMessage.innerHTML = `<p>${result.message}</p>`;
                            }
                        }
                    } catch (error) {
                        console.error('Fetch error:', error);
                        showFlexibleModal('<p>Network error. Could not verify OTP. Please try again.</p>', [{ text: 'OK' }]);
                    } finally {
                        verifyOtpButton.disabled = false;
                        verifyOtpButton.innerHTML = 'Verify OTP';
                    }
                }
            });
        }

        // Step 2: Resend OTP Button Handler
        if (resendOtpButton) {
            resendOtpButton.addEventListener('click', async function(event) {
                event.preventDefault();
                clearErrors('otp'); // Clear any previous OTP errors
                resendOtpButton.disabled = true;
                resendOtpButton.innerHTML = '<span class="loading-spinner"></span> Resending...';

                try {
                    const response = await fetch('/api/forgot_password_request', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ email: currentForgotEmail })
                    });

                    const result = await response.json();

                    if (response.ok) {
                        let messageText = `<p>New OTP sent to <strong>${currentForgotEmail}</strong>. Please enter it below.</p>`;
                        // if (result.simulated_otp) { // Again, remove in production
                        //     messageText += `<p><strong>SIMULATED OTP (FOR TESTING):</strong> ${result.simulated_otp}</p>`;
                        // }
                        forgotModalMessage.innerHTML = messageText;
                        otpInput.value = ''; // Clear previous OTP
                        otpInput.classList.remove('error'); // Clear error state
                        otpError.textContent = ''; // Clear error message
                        startResendCooldown(); // Start the cooldown timer
                    } else {
                        // If there's an error on resend, display it in the OTP section's error message
                        otpError.textContent = result.message || 'Failed to resend OTP.';
                        otpInput.classList.add('error'); // Potentially highlight OTP input again
                        if (result.message) {
                             forgotModalMessage.innerHTML = `<p>${result.message}</p>`;
                        }
                    }
                } catch (error) {
                    console.error('Fetch error:', error);
                    showFlexibleModal('<p>Network error. Could not resend OTP. Please try again.</p>', [{ text: 'OK' }]);
                } finally {
                    resendOtpButton.disabled = false;
                    resendOtpButton.innerHTML = 'Send Again';
                }
            });
        }

        // Handlers for Cancel buttons in the forgot/reset modals
        if (forgotCancelButton) {
            forgotCancelButton.addEventListener('click', function() {
                hideCustomModal(forgotPasswordRequestModal);
                forgotPasswordRequestForm.reset();
                currentForgotEmail = ''; // Clear stored email
                clearErrors('forgot'); // Ensure all forgot-related errors are cleared
                // Clear resend cooldown
                if (resendInterval) {
                    clearInterval(resendInterval);
                    resendInterval = null;
                    resendCooldown = 0;
                }
                // Reset resend button styling
                resendOtpButton.disabled = false;
                resendOtpButton.textContent = 'Send Code Again';
                resendOtpButton.style.backgroundColor = '';
            });
        }

        if (otpCancelButton) {
            otpCancelButton.addEventListener('click', function() {
                hideCustomModal(forgotPasswordRequestModal);
                verifyOtpForm.reset();
                currentForgotEmail = ''; // Clear stored email
                clearErrors('otp'); // Ensure all OTP-related errors are cleared
                // Clear resend cooldown
                if (resendInterval) {
                    clearInterval(resendInterval);
                    resendInterval = null;
                    resendCooldown = 0;
                }
                // Reset resend button styling
                resendOtpButton.disabled = false;
                resendOtpButton.textContent = 'Send Code Again';
                resendOtpButton.style.backgroundColor = '';
            });
        }

        if (resetCancelButton) {
            resetCancelButton.addEventListener('click', function() {
                hideCustomModal(resetPasswordModal);
                resetPasswordForm.reset();
                currentForgotEmail = ''; // Clear stored email
                clearErrors('reset'); // Ensure all reset-related errors are cleared
                // Clear resend cooldown
                if (resendInterval) {
                    clearInterval(resendInterval);
                    resendInterval = null;
                    resendCooldown = 0;
                }
                // Reset resend button styling
                resendOtpButton.disabled = false;
                resendOtpButton.textContent = 'Send Code Again';
                resendOtpButton.style.backgroundColor = '';
            });
        }

        // Step 3: Reset Password Form Submission Handler
        if (resetPasswordForm) {
            resetPasswordForm.addEventListener('submit', async function(event) {
                event.preventDefault();
                clearErrors('reset'); // Clear errors specific to the reset password form

                let isValid = true;
                const email = resetEmailInput.value.trim(); // This should be currentForgotEmail
                const newPassword = newPasswordInput.value.trim();
                const confirmNewPassword = confirmNewPasswordInput.value.trim();


                if (email === '') { // Should be pre-filled, but a final check
                    isValid = false;
                    resetEmailError.textContent = 'Email is required.';
                    resetEmailInput.classList.add('error');
                } else if (!isValidEmail(email)) {
                    isValid = false;
                    resetEmailError.textContent = 'Invalid email format.'; // Should not happen if pre-filled correctly
                    resetEmailInput.classList.add('error');
                }

                if (newPassword === '') {
                    isValid = false;
                    newPasswordError.textContent = 'New password is required.';
                    newPasswordInput.classList.add('error');
                } else if (newPassword.length < 6) {
                    isValid = false;
                    newPasswordError.textContent = 'New password must be at least 6 characters.';
                    newPasswordInput.classList.add('error');
                }

                if (confirmNewPassword === '') {
                    isValid = false;
                    confirmNewPasswordError.textContent = 'Confirm new password is required.';
                    confirmNewPasswordInput.classList.add('error');
                } else if (newPassword !== confirmNewPassword) {
                    isValid = false;
                    confirmNewPasswordError.textContent = 'Passwords do not match.';
                    confirmNewPasswordInput.classList.add('error');
                    newPasswordInput.classList.add('error'); // Highlight both if they don't match
                }


                if (isValid) {
                    resetSubmitButton.disabled = true;
                    resetSubmitButton.innerHTML = '<span class="loading-spinner"></span> Resetting...';

                    try {
                        const response = await fetch('/api/reset_password', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ email: email, new_password: newPassword }) // Ensure correct variable name for new password
                        });

                        const result = await response.json();

                        if (response.ok) {
                            hideCustomModal(resetPasswordModal);
                            resetPasswordForm.reset();
                            currentForgotEmail = ''; // Clear stored email after successful reset
                            // Clear resend cooldown
                            if (resendInterval) {
                                clearInterval(resendInterval);
                                resendInterval = null;
                                resendCooldown = 0;
                            }
                            // Reset resend button styling
                            resendOtpButton.disabled = false;
                            resendOtpButton.textContent = 'Send Code Again';
                            resendOtpButton.style.backgroundColor = '';
                            showFlexibleModal(
                                '<p>Password reset successful. You can now login with your new password.</p>',
                                [{ text: 'OK', action: () => {
                                    loginRadio.checked = true;
                                    slideToLogin();
                                }}]
                            );
                        } else {
                            // Display error messages from the backend
                            result.status = response.status;
                            displayModalFormErrors(result, resetPasswordForm, 'reset');
                            if (result.message && (result.message.includes('OTP not verified') || result.message.includes('not initiated'))) {
                                showFlexibleModal(
                                    `<p>${result.message}</p><p>Please start the password reset process again.</p>`,
                                    [{ text: 'Start Over', action: () => {
                                        hideCustomModal(resetPasswordModal);
                                        forgotPasswordLink.click(); // Re-open the initial forgot password modal
                                    }}],
                                    null // No general callback
                                );
                            }
                        }
                    } catch (error) {
                        console.error('Fetch error:', error);
                        showFlexibleModal('<p>Network error. Could not reset password. Please try again.</p>', [{ text: 'OK' }]);
                    } finally {
                        resetSubmitButton.disabled = false;
                        resetSubmitButton.innerHTML = 'Reset Password';
                    }
                }
            });
        }

        // This function handles displaying errors from the backend for the main login/signup forms
        function handleMainFormErrors(result, formElement, endpoint) {
            if (endpoint === '/api/login') {
                if (result.message && (result.message.includes('Account not found') || result.message.includes('Invalid credentials'))) {
                     showFlexibleModal(
                        `<p>${result.message}</p><p>If you are not registered, please sign up.</p>`,
                        [{ text: 'Sign Up', action: () => {
                            signupRadio.checked = true;
                            slideToSignup();
                        }}, { text: 'OK', style: 'background-color: var(--bs-secondary-color);' }]
                     );
                }
            } else if (endpoint === '/api/signup') {
                if (result.message && (result.message.includes('Email already registered') || result.message.includes('Username already taken'))) {
                    showFlexibleModal(
                        `<p>${result.message}</p><p>If you are already registered, please log in.</p>`,
                        [{ text: 'Login', action: () => {
                            loginRadio.checked = true;
                            slideToLogin();
                        }}, { text: 'OK', style: 'background-color: var(--bs-secondary-color);' }]
                    );
                }
            }
            if (result.errors) {
                for (const field in result.errors) {
                    let inputElement, errorElement;

                    if (formElement.id === 'loginForm' && field === 'username_or_email') {
                        inputElement = loginUsernameOrEmailInput;
                        errorElement = loginUsernameOrEmailError;
                    } else if (formElement.id === 'signupForm' && field === 'name') {
                         inputElement = signupNameInput;
                         errorElement = signupNameError;
                    }
                    else {
                        // This handles password errors for login and email/password for signup
                        // Need to be careful with field names. Example: if backend returns 'password' for signup.
                        inputElement = formElement.querySelector(`[name="${field}"]`);
                        // This assumes predictable error element IDs based on input IDs
                        const inputId = inputElement ? inputElement.id : null;
                        errorElement = inputId ? document.getElementById(`${inputId}Error`) : null;
                    }

                    if (errorElement) errorElement.textContent = result.errors[field];
                    if (inputElement) inputElement.classList.add('error');
                }
            }
        }

        // Generic function for handling errors in modals (forgot, otp, reset)
        function displayModalFormErrors(result, formElement, formContext) {
            // Clear errors specific to the current modal's form context
            clearErrors(formContext);

            if (result.errors) {
                for (const field in result.errors) {
                    // This is robust: Find the input element by its 'name' attribute
                    const inputElement = formElement.querySelector(`[name="${field}"]`);
                    // Then, find its associated error message element by looking for a sibling with the ID pattern
                    const errorElement = inputElement ? document.getElementById(`${inputElement.id}Error`) : null;

                    if (errorElement) errorElement.textContent = result.errors[field];
                    if (inputElement) inputElement.classList.add('error');
                }
            }
            // Update the main message area of the modal if a general message is returned
            const targetModalMessage = formElement.closest('.modal-content').querySelector('.modal-message');
            if (targetModalMessage && result.message) {
                // Check if this is an error response (status codes 400-599 indicate errors)
                const isError = result.status >= 400 && result.status < 600;
                const messageClass = isError ? 'error-message' : '';
                targetModalMessage.innerHTML = `<p class="${messageClass}">${result.message}</p>`;
            }
        }

        // Main data submission function (unchanged for main forms, adapted for modals)
        async function submitFormData(formElement, submitButton, endpoint, formContext) {
            if (!formElement || !submitButton || !endpoint) {
                console.error("submitFormData called with missing arguments.");
                return;
            }

            const formData = new FormData(formElement);
            const data = {};
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }

            submitButton.disabled = true;
            if (formContext === 'main') {
                displayFormMessage("Submitting...", 'info');
            } else {
                // For modal buttons, update their innerHTML directly
                submitButton.innerHTML = '<span class="loading-spinner"></span> Submitting...';
            }

            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data),
                });

                const result = await response.json();

                if (response.ok) {
                    if (formContext === 'main') {
                        clearErrors('main');
                        formElement.reset();
                        displayFormMessage('', 'info'); // Clear "Submitting..." message
                        loginAttempts = 0; // Reset login attempts on successful login

                        if (endpoint === '/api/signup') {
                            showFlexibleModal(
                                '<p>Registration successful! Please log in.</p>',
                                [{ text: 'OK', action: () => {
                                    loginRadio.checked = true;
                                    slideToLogin();
                                    const url = new URL(window.location);
                                    url.searchParams.delete('signup'); // Clean up URL
                                    window.history.replaceState({}, '', url.toString());
                                }}]
                            );
                        } else if (endpoint === '/api/login') {
                            showFlexibleModal(
                                '<p>Login successful!</p>',
                                [{ text: 'OK', action: () => {
                                    localStorage.setItem('isLoggedIn', 'true');
                                    localStorage.setItem('user', JSON.stringify(result.user));
                                    window.location.href = '/';
                                }}]
                            );
                        }
                    }
                    // For forgot/otp/reset, successful handling is now done directly in their respective event listeners
                    // so no generic handling here for those contexts.
                } else { // Server returned an error (response.ok is false)
                    if (formContext === 'main') {
                        if (endpoint === '/api/login' && result.message && result.message.includes('Invalid credentials')) {
                            loginAttempts++;
                            loginPasswordInput.classList.add('error');
                            loginPasswordError.textContent = result.message;

                            if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
                                showLoginAttemptsLimitModal();
                                loginPasswordInput.value = ''; // Clear password after max attempts
                            } else {
                                displayFormMessage(`Incorrect password. You have ${MAX_LOGIN_ATTEMPTS - loginAttempts} attempts left.`, 'error');
                            }
                        } else {
                            displayFormMessage(result.message || 'An error occurred.', 'error');
                            handleMainFormErrors(result, formElement, endpoint);
                        }
                    } else if (formContext === 'forgot') {
                        result.status = response.status;
                        displayModalFormErrors(result, formElement, 'forgot');
                    } else if (formContext === 'otp') {
                        result.status = response.status;
                        displayModalFormErrors(result, formElement, 'otp');
                    } else if (formContext === 'reset') {
                        result.status = response.status;
                        displayModalFormErrors(result, formElement, 'reset');
                    }
                }
            } catch (error) {
                console.error('Fetch error:', error);
                if (formContext === 'main') {
                    displayFormMessage('Network error. Please try again.', 'error');
                } else {
                    showFlexibleModal(
                        '<p>Network error. Please check your internet connection and try again.</p>',
                        [{ text: 'OK' }]
                    );
                }
            } finally {
                submitButton.disabled = false;
                // Reset button text specifically for modal forms if not handled by success/error flows above
                if (formContext === 'forgot') {
                    submitButton.innerHTML = 'Send Reset Code';
                } else if (formContext === 'otp') {
                    submitButton.innerHTML = 'Verify Code';
                } else if (formContext === 'reset') {
                    submitButton.innerHTML = 'Reset Password';
                }
            }
        }


        function showLoginAttemptsLimitModal() {
            const messageHtml = `
                <strong>You have made three incorrect login attempts.</strong>
                <ul>
                    <li>1. If you are not registered, please <a href="#" id="modalSignupLink">sign up now</a>.</li>
                    <li>2. If you are already registered, please <a href="#" id="modalLoginLink">login now</a> with correct credentials.</li>
                    <li>3. If you have forgotten your password, click <a href="#" id="modalForgotPasswordLink">forgot password</a> to reset it.</li>
                </ul>
            `;
            
            const buttons = [
                { text: 'Login', action: () => {
                    loginRadio.checked = true;
                    slideToLogin();
                    loginAttempts = 0;
                    loginPasswordInput.value = '';
                }},
                { text: 'Signup', action: () => {
                    signupRadio.checked = true;
                    slideToSignup();
                    loginAttempts = 0;
                    loginPasswordInput.value = '';
                }}
            ];

            showFlexibleModal(messageHtml, buttons, () => {
                const modalSignupLink = document.getElementById('modalSignupLink');
                const modalLoginLink = document.getElementById('modalLoginLink');
                const modalForgotPasswordLink = document.getElementById('modalForgotPasswordLink');

                if (modalSignupLink) {
                    modalSignupLink.onclick = (e) => {
                        e.preventDefault();
                        hideCustomModal(customModal);
                        signupRadio.checked = true;
                        slideToSignup();
                        loginAttempts = 0;
                        loginPasswordInput.value = '';
                    };
                }
                if (modalLoginLink) {
                    modalLoginLink.onclick = (e) => {
                        e.preventDefault();
                        hideCustomModal(customModal);
                        loginRadio.checked = true;
                        slideToLogin();
                        loginAttempts = 0;
                        loginPasswordInput.value = '';
                    };
                }
                if (modalForgotPasswordLink) {
                    modalForgotPasswordLink.onclick = (e) => {
                        e.preventDefault();
                        hideCustomModal(customModal);
                        forgotPasswordLink.click();
                        loginAttempts = 0;
                        loginPasswordInput.value = '';
                    };
                }
            });
        }

        function isValidEmail(email) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(email);
        }
    });
</script>
</body>
</html>