-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathregistration-container.tsx
More file actions
2126 lines (1995 loc) · 80.9 KB
/
Copy pathregistration-container.tsx
File metadata and controls
2126 lines (1995 loc) · 80.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client";
import { useState, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import { signOut } from "firebase/auth";
import { auth } from "@/Firebase";
import { useAuth } from "@/hooks/use-auth";
import { useRecaptcha } from "@/hooks/use-recaptcha";
import { useToast } from "@/hooks/use-toast";
import {
LogIn,
UserPlus,
Zap,
Info,
ExternalLink,
Trash2,
ChevronLeft,
ChevronRight,
ShieldCheck,
Terminal,
CircleCheck,
CircleDot,
Lock,
User as UserIcon,
FileText,
Link as LinkIcon,
ClipboardCheck,
Pencil,
AlertCircle,
} from "lucide-react";
import { FormInput } from "./form-input";
import { FormTextarea } from "./form-textarea";
import { FormSelect } from "./form-select";
import { FormFileUpload } from "./form-file-upload";
import { FormPhoneInput, isValidPhoneNumber } from "./form-phone-input";
import { FormSection } from "./form-section";
import { RecaptchaNotice } from "./recaptcha-notice";
import { GoogleButton } from "./google-button";
import { Button } from "./button";
import { Card } from "./card";
import { StickyAlert } from "./sticky-alert";
import { Spinner } from "@/components/ui/spinner";
import { Modal } from "./modal";
import { API_ENDPOINTS } from "@/lib/api-config";
import { HudFrame } from "./hud-frame";
// PRODUCTION MODE - Debug features disabled
const DEBUG_MODE = false;
// LocalStorage key for form data persistence
const REGISTRATION_FORM_STORAGE_KEY = "zenith_registration_form_data";
interface RegistrationContainerProps {
onSuccess?: () => void;
}
type StepId = "account" | "identity" | "profile" | "links" | "review";
const STEPS: Array<{
id: StepId;
label: string;
hint: string;
icon: typeof Lock;
}> = [
{ id: "account", label: "Account", hint: "Credentials", icon: Lock },
{ id: "identity", label: "Identity", hint: "Who you are", icon: UserIcon },
{ id: "profile", label: "Profile", hint: "Bio & files", icon: FileText },
{ id: "links", label: "Links", hint: "Socials", icon: LinkIcon },
{ id: "review", label: "Review", hint: "Confirm & submit", icon: ClipboardCheck },
];
export function RegistrationContainer({
onSuccess,
}: RegistrationContainerProps) {
const router = useRouter();
const {
register,
registerWithGoogle,
signInWithGoogle,
getToken,
firebaseUser,
user,
} = useAuth();
const { executeRecaptcha } = useRecaptcha();
const { toast } = useToast();
const [authMode, setAuthMode] = useState<"login" | "register">("register");
const [alert, setAlert] = useState<{
type: "success" | "error" | "warning" | "info";
message: string;
} | null>(null);
// Helper function to get initial form data from localStorage
const getInitialFormData = () => {
try {
const savedData = localStorage.getItem(REGISTRATION_FORM_STORAGE_KEY);
if (savedData) {
const parsed = JSON.parse(savedData);
if (parsed.registerData) {
// Merge with default values to ensure all fields exist
return {
name: "",
email: "",
password: "",
confirmPassword: "",
discord_username: "",
phone: "",
age: "",
organisation: "",
bio: "",
github: "",
linkedin: "",
ctf: "",
portfolio: "",
...parsed.registerData,
};
}
}
} catch (error) {
console.error("Error reading form data from localStorage:", error);
}
// Return default empty values
return {
name: "",
email: "",
password: "",
confirmPassword: "",
discord_username: "",
phone: "",
age: "",
organisation: "",
bio: "",
github: "",
linkedin: "",
ctf: "",
portfolio: "",
};
};
// Registration form state - initialized from localStorage
const [registerData, setRegisterData] = useState(getInitialFormData);
// Login form state
const [loginData, setLoginData] = useState({
email: "",
password: "",
});
// File states. Files (and their displayed metadata) are intentionally NOT
// persisted to localStorage — File objects can't be serialized, and showing
// a stale filename when the underlying File ref is null misleads the user
// into thinking the file is still attached on retry. Always start empty.
const [resume, setResume] = useState<File | null>(null);
const [profilePhoto, setProfilePhoto] = useState<File | null>(null);
const [resumeFileName, setResumeFileName] = useState("");
const [profilePhotoFileName, setProfilePhotoFileName] = useState("");
// Errors
const [errors, setErrors] = useState<Record<string, string>>({});
const [isSubmitting, setIsSubmitting] = useState(false);
// True while a reCAPTCHA-guarded availability check (email / Discord) is in
// flight, so the "Continue" button can show progress and block double-clicks.
const [checkingAvailability, setCheckingAvailability] = useState(false);
// Google SSO. authMethod "google" means the user authenticated via the Google
// popup; we then collect the remaining profile fields, lock the name, and skip
// the password/account step entirely. googleData holds the verified identity
// for display + prefill (a fresh ID token is fetched at submit via getToken()).
const [authMethod, setAuthMethod] = useState<"email" | "google">("email");
const [googleData, setGoogleData] = useState<{
email: string;
name: string;
uid: string;
} | null>(null);
const [googleLoading, setGoogleLoading] = useState(false);
// Account step progressive disclosure: the password fields appear only once
// the email field has been focused (or already carries a value).
const [accountExpanded, setAccountExpanded] = useState(false);
// Guards the auto-enter-Google-mode effect so it runs at most once.
const googleHydratedRef = useRef(false);
const [isCodeOfConductModalOpen, setIsCodeOfConductModalOpen] =
useState(false);
const [acceptedCodeOfConduct, setAcceptedCodeOfConduct] = useState(false);
const [attendedZenith, setAttendedZenith] = useState(false);
const [attendedPBCTF4, setAttendedPBCTF4] = useState(false);
const [cocScrolledToBottom, setCocScrolledToBottom] = useState(false);
const cocScrollRef = useRef<HTMLDivElement | null>(null);
// Reset scroll + read state every time the CoC modal opens
useEffect(() => {
if (isCodeOfConductModalOpen) {
setCocScrolledToBottom(false);
// Defer to next paint so the dialog has mounted
requestAnimationFrame(() => {
if (cocScrollRef.current) cocScrollRef.current.scrollTop = 0;
});
}
}, [isCodeOfConductModalOpen]);
// Lock background scroll + close on Escape while CoC modal is open.
// Without this the user can scroll the page behind the overlay (and
// on iOS the modal can drift off-screen if it's portalled into a
// transformed ancestor).
useEffect(() => {
if (!isCodeOfConductModalOpen) return;
const { body, documentElement } = document;
const prevBodyOverflow = body.style.overflow;
const prevHtmlOverflow = documentElement.style.overflow;
body.style.overflow = "hidden";
documentElement.style.overflow = "hidden";
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setIsCodeOfConductModalOpen(false);
};
window.addEventListener("keydown", onKey);
return () => {
body.style.overflow = prevBodyOverflow;
documentElement.style.overflow = prevHtmlOverflow;
window.removeEventListener("keydown", onKey);
};
}, [isCodeOfConductModalOpen]);
const handleCocScroll = (e: React.UIEvent<HTMLDivElement>) => {
const el = e.currentTarget;
// 16px slack so the gate doesn't require pixel-perfect scrolling
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 16) {
setCocScrolledToBottom(true);
}
};
// Multi-step wizard state
const [currentStepIndex, setCurrentStepIndex] = useState(0);
// Track if component has mounted to avoid saving empty data on initial mount
const isInitialMount = useRef(true);
// Key for file inputs to force reset when clearing
const [fileInputKey, setFileInputKey] = useState(0);
// Save form data to localStorage whenever it changes (excluding sensitive
// password fields and file metadata — see comment on file state above).
useEffect(() => {
// Skip saving on initial mount since we just loaded from localStorage
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
try {
// Exclude password fields from localStorage for security
const { password, confirmPassword, ...safeRegisterData } = registerData;
const dataToSave = {
registerData: safeRegisterData,
};
localStorage.setItem(
REGISTRATION_FORM_STORAGE_KEY,
JSON.stringify(dataToSave),
);
} catch (error) {
console.error("Error saving form data to localStorage:", error);
}
}, [registerData]);
// Auto-enter Google mode when the user arrives already signed in with Google
// but without a profile — e.g. they clicked "Continue with Google" on the
// login page and were redirected here to finish registering. Prefill name +
// email, lock the name, and jump straight to the Identity step.
useEffect(() => {
if (googleHydratedRef.current) return;
if (authMethod === "google") return;
// `user` is the Mongo profile; if it exists they're fully registered.
if (!firebaseUser || user) return;
const cameFromGoogle = firebaseUser.providerData.some(
(p) => p.providerId === "google.com",
);
if (!cameFromGoogle) return;
googleHydratedRef.current = true;
const gEmail = firebaseUser.email ?? "";
const gName = firebaseUser.displayName ?? "";
setGoogleData({ email: gEmail, name: gName, uid: firebaseUser.uid });
setAuthMethod("google");
setRegisterData((prev: typeof registerData) => ({ ...prev, email: gEmail, name: gName }));
setCurrentStepIndex(1); // Identity
}, [firebaseUser, user, authMethod]);
// Clears errors for the account fields (used when switching to Google mode,
// where password/confirm no longer apply).
const clearAccountErrors = () => {
setErrors((prev) => {
const next = { ...prev };
delete next.email;
delete next.password;
delete next.confirmPassword;
delete next.name;
return next;
});
};
// "Continue with Google" — open the popup, then either send an already
// registered user to the dashboard or drop a new user into the Identity step.
const handleGoogleSignIn = async () => {
setGoogleLoading(true);
setAlert(null);
try {
const res = await signInWithGoogle();
if (res.hasProfile) {
// Already registered — just sign them in.
router.push("/dashboard");
return;
}
googleHydratedRef.current = true;
setGoogleData({ email: res.email, name: res.name, uid: res.uid });
setAuthMethod("google");
setRegisterData((prev: typeof registerData) => ({
...prev,
email: res.email,
name: res.name,
}));
clearAccountErrors();
setCurrentStepIndex(1); // Identity
} catch (err: any) {
if (err?.code === "popup_cancelled") {
// User dismissed the popup — stay put silently.
return;
}
if (err?.code === "link_password_required") {
setAlert({
type: "error",
message:
"This email is already registered with a password. Please log in instead.",
});
return;
}
setAlert({
type: "error",
message: err?.message || "Google sign-in failed. Please try again.",
});
} finally {
setGoogleLoading(false);
}
};
// Switch back to email/password registration. Sign the Google session out so
// the auto-enter effect above doesn't immediately re-enter Google mode.
const resetToEmailMode = async () => {
try {
await signOut(auth);
} catch (error) {
console.error("Failed to sign out Google session:", error);
}
googleHydratedRef.current = false;
setGoogleData(null);
setAuthMethod("email");
setAccountExpanded(false);
setRegisterData((prev: typeof registerData) => ({ ...prev, email: "", name: "" }));
clearAccountErrors();
setCurrentStepIndex(0);
};
// DEBUG: Auto-fill function
const handleAutoFill = () => {
const randomId = Math.floor(Math.random() * 1000);
setRegisterData({
name: `Test User ${randomId}`,
email: `testuser${randomId}@example.com`,
password: "Password@123",
confirmPassword: "Password@123",
discord_username: "testuser.discord",
phone: "+919876543210",
age: "22",
organisation: "Test University/Company",
bio: "I'm a passionate developer interested in AI, web development, and hackathons. Looking forward to participating in PBCTF 5.0!",
github: "https://github.com/testuser",
linkedin: "https://linkedin.com/in/testuser",
portfolio: "https://testuser.dev",
ctf: "https://ctftime.org/user/testuser",
referralCode: "TEST2024",
});
// Create a dummy PDF file for resume
const resumeBlob = new Blob(["This is a test resume PDF content"], {
type: "application/pdf",
});
const resumeFile = new File([resumeBlob], "test_resume.pdf", {
type: "application/pdf",
});
setResume(resumeFile);
setResumeFileName("test_resume.pdf");
setAlert({
type: "info",
message: "Form auto-filled with test data! (Debug mode)",
});
setTimeout(() => setAlert(null), 3000);
};
// Handle Login
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
// TODO: Implement login logic
setAlert({
type: "info",
message: "Login functionality will be implemented separately",
});
setTimeout(() => setAlert(null), 3000);
};
const validateField = (fieldName: string, value: string): string | null => {
switch (fieldName) {
case "name":
if (!value.trim()) return "Name is required";
break;
case "email":
if (!value.trim()) return "Email is required";
if (!/\S+@\S+\.\S+/.test(value))
return "Please enter a valid email address";
break;
case "password":
const passwordRegex =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/;
if (!value) return "Password is required";
if (!passwordRegex.test(value))
return "Password must be 8+ chars, incl, uppercase, lowercase, number, special char";
break;
case "confirmPassword":
if (!value) return "Please confirm your password";
if (value !== registerData.password) return "Passwords do not match";
break;
case "discord_username":
if (!value.trim()) return "Discord username is required";
break;
case "phone":
if (!value || !value.trim()) return "Phone is required";
if (!isValidPhoneNumber(value)) {
return "Please enter a valid phone number";
}
break;
case "age":
if (!value || !value.trim()) return "Age is required";
const ageNum = parseInt(value.trim());
if (isNaN(ageNum) || ageNum < 13 || ageNum > 100) {
return "Please enter a valid age (13-100)";
}
break;
case "organisation":
if (!value.trim()) return "Organisation is required";
break;
case "github":
if (!value.trim()) return "GitHub link is required";
const githubPattern =
/^(https?:\/\/)?(www\.)?github\.com\/[\w-]+(\/)?$/i;
if (!githubPattern.test(value.trim())) {
return "Please enter a valid GitHub URL (e.g., https://github.com/username)";
}
break;
case "linkedin":
if (!value.trim()) return "LinkedIn link is required";
const linkedinPattern =
/^(https?:\/\/)?(www\.)?linkedin\.com\/(in|profile)\/[\w-]+(\/)?$/i;
if (!linkedinPattern.test(value.trim())) {
return "Please enter a valid LinkedIn URL (e.g., https://linkedin.com/in/username)";
}
break;
case "portfolio":
if (value.trim()) {
try {
new URL(value.trim());
} catch {
return "Please enter a valid portfolio URL";
}
}
break;
case "ctf":
if (value.trim()) {
try {
new URL(value.trim());
} catch {
return "Please enter a valid CTF profile URL";
}
}
break;
default:
return null;
}
return null;
};
const handleFieldBlur =
(fieldName: string) =>
(e?: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const value =
fieldName === "phone" ? registerData.phone : e?.target.value || "";
const error = validateField(fieldName, value);
if (error) {
setErrors((prev) => ({ ...prev, [fieldName]: error }));
} else {
setErrors((prev) => {
const newErrors = { ...prev };
delete newErrors[fieldName];
return newErrors;
});
}
};
const validateAllFields = (): Record<string, string> => {
const validationErrors: Record<string, string> = {};
const requiredFields: Array<keyof typeof registerData> = [
"name",
"email",
// Google users have no password — it's handled by Firebase.
...(authMethod === "google"
? []
: (["password", "confirmPassword"] as Array<keyof typeof registerData>)),
"discord_username",
"phone",
"age",
"organisation",
"github",
"linkedin",
];
requiredFields.forEach((field) => {
const error = validateField(field as string, registerData[field]);
if (error) {
validationErrors[field as string] = error;
}
});
const optionalFields: Array<keyof typeof registerData> = [
"portfolio",
"bio",
"ctf",
];
optionalFields.forEach((field) => {
if (registerData[field] && registerData[field].trim()) {
const error = validateField(field as string, registerData[field]);
if (error) {
validationErrors[field as string] = error;
}
}
});
if (!resume) {
validationErrors.resume = "Resume is required";
}
if (!acceptedCodeOfConduct) {
validationErrors.codeOfConduct =
"You must accept the Code of Conduct to register";
}
return validationErrors;
};
const isFormValid = (): boolean => {
const validationErrors = validateAllFields();
return Object.keys(validationErrors).length === 0;
};
// Per-step validation
const stepFieldMap: Record<StepId, Array<keyof typeof registerData>> = {
account: ["email", "password", "confirmPassword"],
identity: ["name", "age", "phone", "discord_username", "organisation"],
profile: [],
links: ["github", "linkedin", "portfolio", "ctf"],
review: [],
};
const validateStep = (stepId: StepId): Record<string, string> => {
const stepErrors: Record<string, string> = {};
// In Google mode the account step is satisfied by the Google sign-in.
if (stepId === "account" && authMethod === "google") {
return stepErrors;
}
const fields = stepFieldMap[stepId];
fields.forEach((field) => {
const value = registerData[field] || "";
const error = validateField(field as string, value);
if (error) {
stepErrors[field as string] = error;
}
});
if (stepId === "profile" && !resume) {
stepErrors.resume = "Resume is required";
}
return stepErrors;
};
const isStepValid = (stepId: StepId): boolean => {
return Object.keys(validateStep(stepId)).length === 0;
};
const stepStatus = (idx: number): "complete" | "active" | "pending" => {
if (idx < currentStepIndex) return "complete";
if (idx === currentStepIndex) return "active";
return "pending";
};
const isFieldTaken = async (
field: "email" | "discord_username",
value: string,
): Promise<boolean> => {
try {
const token = await executeRecaptcha("check_registration");
const params = new URLSearchParams({ [field]: value });
if (token) params.set("recaptcha_token", token);
const res = await fetch(`${API_ENDPOINTS.register}?${params.toString()}`);
if (!res.ok) return false;
const data = await res.json();
return data?.exists === true;
} catch (error) {
console.error("[registration] availability check failed:", error);
return false;
}
};
const goNext = async () => {
const stepId = STEPS[currentStepIndex].id;
const stepErrors = validateStep(stepId);
if (Object.keys(stepErrors).length > 0) {
setErrors((prev) => ({ ...prev, ...stepErrors }));
setAlert({
type: "error",
message: "Resolve the highlighted fields to continue.",
});
setTimeout(() => setAlert(null), 3000);
return;
}
const checks: Array<{
field: "email" | "discord_username";
value: string;
message: string;
}> = [];
if (stepId === "account" && authMethod === "email") {
checks.push({
field: "email",
value: registerData.email.trim(),
message: "This email is already registered.",
});
}
if (stepId === "identity") {
checks.push({
field: "discord_username",
value: registerData.discord_username.trim(),
message: "This Discord username is already registered.",
});
}
if (checks.length > 0) {
setCheckingAvailability(true);
try {
for (const check of checks) {
if (await isFieldTaken(check.field, check.value)) {
setErrors((prev) => ({ ...prev, [check.field]: check.message }));
setAlert({ type: "error", message: check.message });
setTimeout(() => setAlert(null), 3000);
return;
}
}
} finally {
setCheckingAvailability(false);
}
}
setAlert(null);
if (currentStepIndex < STEPS.length - 1) {
setCurrentStepIndex((i) => i + 1);
if (typeof window !== "undefined") {
window.scrollTo({ top: 0, behavior: "smooth" });
}
}
};
const goBack = () => {
setAlert(null);
if (currentStepIndex > 0) {
setCurrentStepIndex((i) => i - 1);
if (typeof window !== "undefined") {
window.scrollTo({ top: 0, behavior: "smooth" });
}
}
};
const jumpToStep = (idx: number) => {
// Allow jumping back freely; jumping forward requires prior steps to be valid
if (idx <= currentStepIndex) {
setCurrentStepIndex(idx);
setAlert(null);
return;
}
for (let i = currentStepIndex; i < idx; i++) {
const stepErrors = validateStep(STEPS[i].id);
if (Object.keys(stepErrors).length > 0) {
setErrors((prev) => ({ ...prev, ...stepErrors }));
setAlert({
type: "error",
message: `Complete step ${i + 1} (${STEPS[i].label}) before advancing.`,
});
setTimeout(() => setAlert(null), 3000);
return;
}
}
setCurrentStepIndex(idx);
setAlert(null);
};
const handleRegister = async (e: React.FormEvent) => {
e.preventDefault();
const validationErrors = validateAllFields();
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors);
setIsSubmitting(false);
// Save form data even when validation fails (text fields only — files
// and their displayed names are intentionally not persisted).
try {
const { password, confirmPassword, ...safeRegisterData } = registerData;
const dataToSave = {
registerData: safeRegisterData,
};
localStorage.setItem(
REGISTRATION_FORM_STORAGE_KEY,
JSON.stringify(dataToSave),
);
} catch (error) {
console.error("Error saving form data to localStorage:", error);
}
return;
}
setIsSubmitting(true);
setAlert(null);
try {
// Save form data before submission to ensure it's persisted (text fields
// only — files and their displayed names are intentionally not persisted).
try {
const { password, confirmPassword, ...safeRegisterData } = registerData;
const dataToSave = {
registerData: safeRegisterData,
};
localStorage.setItem(
REGISTRATION_FORM_STORAGE_KEY,
JSON.stringify(dataToSave),
);
} catch (error) {
console.error("Error saving form data to localStorage:", error);
}
let formattedPhone = registerData.phone.trim();
const phoneDigits = formattedPhone.replace(/\D/g, "");
if (phoneDigits.length === 10) {
formattedPhone = `+91${phoneDigits}`;
} else if (phoneDigits.length === 12 && phoneDigits.startsWith("91")) {
formattedPhone = `+${phoneDigits}`;
} else if (phoneDigits.length === 11 && phoneDigits.startsWith("0")) {
formattedPhone = `+91${phoneDigits.substring(1)}`;
}
const isGoogle = authMethod === "google";
// For Google, fetch a FRESH ID token at submit time — the one from the
// initial popup may have expired while the user filled out the form.
let googleIdToken: string | null = null;
if (isGoogle) {
googleIdToken = await getToken();
if (!googleIdToken) {
throw new Error(
"Your Google session expired. Please sign in with Google again.",
);
}
}
// Create FormData for API request
const formData = new FormData();
formData.append("name", registerData.name);
formData.append("email", registerData.email);
formData.append("discord_username", registerData.discord_username);
formData.append("phone", formattedPhone);
formData.append("age", registerData.age);
formData.append("organisation", registerData.organisation);
formData.append("bio", registerData.bio);
formData.append("github_link", registerData.github);
formData.append("linkedin_link", registerData.linkedin);
if (isGoogle) {
// Server trusts the verified token (email + uid), not the password.
formData.append("auth_provider", "google");
formData.append("id_token", googleIdToken as string);
} else {
formData.append("password", registerData.password);
}
if (resume) formData.append("resume", resume);
if (profilePhoto) formData.append("profile_picture", profilePhoto);
if (registerData.portfolio)
formData.append("portfolio_link", registerData.portfolio);
if (registerData.ctf) formData.append("ctf_profile", registerData.ctf);
if (registerData.referralCode)
formData.append("referral_code", registerData.referralCode);
formData.append("attended_zenith", String(attendedZenith));
formData.append("attended_pbctf4", String(attendedPBCTF4));
// reCAPTCHA v3 background token — scored server-side, no user interaction.
const recaptchaToken = await executeRecaptcha("register");
if (recaptchaToken) formData.append("recaptcha_token", recaptchaToken);
if (isGoogle) {
await registerWithGoogle(formData);
} else {
await register(formData);
}
// Clear localStorage on successful registration
try {
localStorage.removeItem(REGISTRATION_FORM_STORAGE_KEY);
} catch (error) {
console.error("Error clearing form data from localStorage:", error);
}
setAlert({
type: "success",
message: "Operator profile initialized. Routing to dashboard...",
});
// Give user time to see success message, then redirect
setTimeout(() => {
if (onSuccess) {
onSuccess();
} else {
// Redirect to dashboard
router.push("/dashboard");
}
}, 1500);
} catch (error) {
let errorMessage = "Registration failed. Please try again.";
const fieldErrors: Record<string, string> = {};
const fieldNameMap: Record<string, string> = {
github_link: "github",
linkedin_link: "linkedin",
portfolio_link: "portfolio",
ctf_profile: "ctf",
};
if (error instanceof Error) {
const fieldErrorsFromApi = (error as any).fieldErrors;
if (
fieldErrorsFromApi &&
typeof fieldErrorsFromApi === "object" &&
Object.keys(fieldErrorsFromApi).length > 0
) {
Object.keys(fieldErrorsFromApi).forEach((backendField) => {
const frontendField = fieldNameMap[backendField] || backendField;
fieldErrors[frontendField] = fieldErrorsFromApi[backendField];
});
const errorKeys = Object.keys(fieldErrors);
if (errorKeys.length === 1) {
errorMessage = fieldErrors[errorKeys[0]];
} else {
errorMessage = error.message || errorMessage;
}
} else {
errorMessage = error.message || errorMessage;
const errorMsg = error.message.toLowerCase();
if (
errorMsg.includes("email already exists") ||
errorMsg.includes("email is already")
) {
fieldErrors.email = "This email is already registered";
} else if (
errorMsg.includes("discord username already exists") ||
errorMsg.includes("discord username is already")
) {
fieldErrors.discord_username =
"This Discord username is already registered";
} else if (
errorMsg.includes("phone number already exists") ||
errorMsg.includes("phone number is already")
) {
fieldErrors.phone = "This phone number is already registered";
} else if (
errorMsg.includes("invalid portfolio") ||
errorMsg.includes("portfolio link")
) {
fieldErrors.portfolio = "Invalid Portfolio URL";
} else if (
errorMsg.includes("invalid github") ||
errorMsg.includes("github profile")
) {
fieldErrors.github = "Invalid GitHub URL";
} else if (
errorMsg.includes("invalid linkedin") ||
errorMsg.includes("linkedin profile")
) {
fieldErrors.linkedin = "Invalid LinkedIn URL";
}
}
} else if (typeof error === "string") {
errorMessage = error;
const errorMsg = error.toLowerCase();
if (
errorMsg.includes("invalid ctf") ||
errorMsg.includes("ctf profile")
) {
fieldErrors.ctf = "Invalid CTF profile URL";
} else if (
errorMsg.includes("invalid portfolio") ||
errorMsg.includes("portfolio link")
) {
fieldErrors.portfolio = "Invalid Portfolio URL";
} else if (
errorMsg.includes("invalid github") ||
errorMsg.includes("github profile")
) {
fieldErrors.github = "Invalid GitHub URL";
} else if (
errorMsg.includes("invalid linkedin") ||
errorMsg.includes("linkedin profile")
) {
fieldErrors.linkedin = "Invalid LinkedIn URL";
}
} else if (error && typeof error === "object" && "message" in error) {
errorMessage = String(error.message);
const errorMsg = errorMessage.toLowerCase();
if (
errorMsg.includes("invalid ctf") ||
errorMsg.includes("ctf profile")
) {
fieldErrors.ctf = "Invalid CTF profile URL";
} else if (
errorMsg.includes("invalid portfolio") ||
errorMsg.includes("portfolio link")
) {
fieldErrors.portfolio = "Invalid Portfolio URL";
} else if (
errorMsg.includes("invalid github") ||
errorMsg.includes("github profile")
) {
fieldErrors.github = "Invalid GitHub URL";
} else if (
errorMsg.includes("invalid linkedin") ||
errorMsg.includes("linkedin profile")
) {
fieldErrors.linkedin = "Invalid LinkedIn URL";
}
}
if (Object.keys(fieldErrors).length > 0) {
setErrors(fieldErrors);
const fieldErrorKeys = Object.keys(fieldErrors);
let toastMessage: string;
let alertMessage: string;
if (fieldErrorKeys.length === 1) {
toastMessage = fieldErrors[fieldErrorKeys[0]];
alertMessage = fieldErrors[fieldErrorKeys[0]];
} else {
const fieldDisplayNameMap: Record<string, string> = {
ctf: "CTF Profile",
portfolio: "Portfolio",
github: "GitHub",
linkedin: "LinkedIn",
email: "Email",
password: "Password",
discord_username: "Discord Username",
phone: "Phone",
age: "Age",
organisation: "Organisation",
bio: "Bio",
name: "Name",
};
const errorList = fieldErrorKeys
.map((key) => {
const fieldDisplayName =
fieldDisplayNameMap[key] ||
key.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
return `${fieldDisplayName}: ${fieldErrors[key]}`;
})
.join(", ");
toastMessage = `Validation errors: ${errorList}`;
alertMessage = `Resolve ${fieldErrorKeys.length} error(s) highlighted below.`;
}
setAlert({
type: "error",
message: alertMessage,
});
toast({
variant: "destructive",
title: "Registration Failed",
description: toastMessage,
});
// Jump to the earliest step that contains an error so the user sees it