games_app/prediqo_web/src/features/auth/RegisterPage.tsx

329 lines
11 KiB
TypeScript

/**
* User registration with referral link/code support and required profile fields.
*/
import {
Alert,
Box,
Button,
Card,
CardContent,
Link,
Stack,
TextField,
Typography,
} from '@mui/material';
import { useEffect, useState } from 'react';
import { Link as RouterLink, useNavigate, useSearchParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Trans, useTranslation } from 'react-i18next';
import { CountryAutocomplete, type CountryOption } from '../../shared/components/CountryAutocomplete';
import { GenderSelect } from '../../shared/components/GenderSelect';
import type { UserGender } from '../../shared/constants/userGender';
import { api } from '../../shared/services/api';
import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher';
import { PrediqoLogo } from '../../shared/brand/PrediqoLogo';
import { apiErrorMessage } from '../../shared/utils/apiError';
type RegisterResponse = {
message: string;
userId: string;
referralCode: string;
emailVerificationRequired: boolean;
};
export function RegisterPage() {
const { t } = useTranslation();
const nav = useNavigate();
const [searchParams] = useSearchParams();
const refFromUrl = searchParams.get('ref') ?? '';
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [country, setCountry] = useState('');
const [nationality, setNationality] = useState('');
const [gender, setGender] = useState<UserGender | ''>('');
const [referralCode, setReferralCode] = useState(refFromUrl);
const [referralValid, setReferralValid] = useState<boolean | null>(null);
const [referralInvalidReason, setReferralInvalidReason] = useState<string | null>(null);
const [usingDefaultReferrer, setUsingDefaultReferrer] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const countriesQ = useQuery({
queryKey: ['registration-countries'],
queryFn: async () => {
const res = await api.get<CountryOption[]>('/api/v1/countries');
return res.data;
},
});
const countries = countriesQ.data ?? [];
useEffect(() => {
if (refFromUrl) {
setReferralCode(refFromUrl);
setUsingDefaultReferrer(false);
}
}, [refFromUrl]);
useEffect(() => {
const code = referralCode.trim();
if (!code) {
setReferralValid(null);
setReferralInvalidReason(null);
return;
}
setUsingDefaultReferrer(false);
const timer = setTimeout(async () => {
try {
const res = await api.get<{ valid: boolean; reason?: string }>(
`/api/v1/auth/referral/validate/${encodeURIComponent(code)}`
);
setReferralValid(res.data.valid);
setReferralInvalidReason(res.data.valid ? null : res.data.reason ?? null);
} catch {
setReferralValid(false);
setReferralInvalidReason(null);
}
}, 400);
return () => clearTimeout(timer);
}, [referralCode]);
const localizeReferralReason = (reason: string | null | undefined): string => {
if (!reason?.trim()) return t('auth.referralUnknown');
const key = `auth.referralReasons.${reason}` as const;
const localized = t(key);
return localized === key ? reason : localized;
};
const applyDefaultReferrer = () => {
setReferralCode('');
setReferralValid(null);
setReferralInvalidReason(null);
setUsingDefaultReferrer(true);
setError(null);
if (refFromUrl) {
nav('/register', { replace: true });
}
};
const resolvedCountry = country;
const submit = async () => {
setError(null);
setSuccess(null);
if (!fullName.trim() || !email.trim() || !password || !confirmPassword || !resolvedCountry || !gender) {
setError(t('auth.registerFieldsRequired'));
return;
}
if (password !== confirmPassword) {
setError(t('auth.passwordsMustMatch'));
return;
}
if (!/^[A-Z]{2}$/.test(resolvedCountry)) {
setError(t('auth.countryIsoInvalid'));
return;
}
if (referralValid === false && referralCode.trim()) {
setError(t('auth.referralFixOrUseDefault'));
return;
}
setLoading(true);
try {
const res = await api.post<RegisterResponse>('/api/v1/auth/register', {
fullName: fullName.trim(),
email: email.trim(),
phone: phone.trim() || undefined,
password,
countryOfResidence: resolvedCountry,
nationality: nationality.trim() || undefined,
gender,
referralCode: referralCode.trim() || undefined,
});
setSuccess(res.data.message || t('auth.registerSuccess'));
setTimeout(() => nav('/login', { replace: true, state: { verifyEmail: true } }), 4000);
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
const msg = apiErrorMessage(err, t('auth.registerFailed'));
setError(msg);
const lower = msg.toLowerCase();
if (
lower.includes('referral') ||
lower.includes('referrer') ||
lower.includes('parrain') ||
lower.includes('deposit')
) {
setReferralValid(false);
setReferralInvalidReason(err.response?.data?.error ?? msg);
}
} finally {
setLoading(false);
}
};
return (
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, py: 4, position: 'relative' }}>
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
<LanguageSwitcher />
</Box>
<Card sx={{ width: '100%', maxWidth: 560 }}>
<CardContent>
<PrediqoLogo size={40} />
<Typography variant="h5" sx={{ fontWeight: 900, mt: 1.5 }}>
{t('auth.createAccount')}
</Typography>
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>{t('auth.registerSubtitle')}</Typography>
{refFromUrl && !usingDefaultReferrer && (
<Alert severity="info" sx={{ mt: 2 }}>
<Trans i18nKey="auth.invitedWithCode" values={{ code: refFromUrl }} components={{ strong: <strong /> }} />
</Alert>
)}
<Stack spacing={2} sx={{ mt: 3 }}>
{error && (
<Alert
severity="error"
action={
referralValid === false ? (
<Button color="inherit" size="small" onClick={applyDefaultReferrer}>
{t('auth.useDefaultReferrer')}
</Button>
) : undefined
}
>
{error}
</Alert>
)}
{success && <Alert severity="success">{success}</Alert>}
<TextField
label={t('auth.fullNameRequired')}
value={fullName}
onChange={(e) => setFullName(e.target.value)}
fullWidth
autoComplete="name"
/>
<TextField
label={t('auth.emailRequired')}
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
fullWidth
autoComplete="email"
/>
<TextField
label={t('auth.phoneOptional')}
value={phone}
onChange={(e) => setPhone(e.target.value)}
fullWidth
autoComplete="tel"
/>
<TextField
label={t('auth.passwordRequired')}
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
fullWidth
autoComplete="new-password"
/>
<TextField
label={t('auth.confirmPasswordRequired')}
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
fullWidth
autoComplete="new-password"
error={confirmPassword.length > 0 && password !== confirmPassword}
helperText={
confirmPassword.length > 0 && password !== confirmPassword
? t('auth.passwordsMustMatch')
: undefined
}
/>
<CountryAutocomplete
label={t('auth.countryOfResidence')}
value={country}
onChange={setCountry}
options={countries}
loading={countriesQ.isLoading}
required
helperText={t('auth.countryHelper')}
/>
<GenderSelect value={gender} onChange={setGender} required helperText={t('gender.helper')} />
{countriesQ.isError && <Alert severity="warning">{t('auth.countriesLoadFailed')}</Alert>}
<CountryAutocomplete
label={t('auth.nationalityOptional')}
value={nationality}
onChange={setNationality}
options={countries}
loading={countriesQ.isLoading}
placeholder={t('auth.nationalityPlaceholder')}
/>
<Box>
<TextField
label={t('auth.referralCodeOptional')}
value={referralCode}
onChange={(e) => setReferralCode(e.target.value.toUpperCase())}
fullWidth
helperText={
usingDefaultReferrer && !referralCode.trim()
? t('auth.usingDefaultReferrer')
: referralValid === true
? t('auth.referralValid')
: referralValid === false
? referralInvalidReason
? t('auth.referralInvalidWithReason', {
reason: localizeReferralReason(referralInvalidReason),
})
: t('auth.referralUnknown')
: t('auth.referralEmpty')
}
error={referralValid === false && !!referralCode.trim()}
slotProps={{
formHelperText: {
sx:
usingDefaultReferrer && !referralCode.trim()
? { color: 'success.main' }
: undefined,
},
}}
/>
{referralValid === false && !!referralCode.trim() && (
<Button
variant="outlined"
size="small"
onClick={applyDefaultReferrer}
sx={{ mt: 1 }}
>
{t('auth.useDefaultReferrer')}
</Button>
)}
</Box>
<Button variant="contained" onClick={submit} disabled={loading} size="large">
{loading ? t('auth.creatingAccount') : t('auth.signUp')}
</Button>
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
{t('auth.alreadyHaveAccount')}{' '}
<Link component={RouterLink} to="/login">
{t('auth.signIn')}
</Link>
</Typography>
</Stack>
</CardContent>
</Card>
</Box>
);
}