NOVAESPORT / src /components /LoginView.tsx
Musabek's picture
Update codebase from AI Studio Build
87d7a37
Raw History Blame Contribute Delete
20.2 kB
import React, { useState } from 'react';
import { auth, googleProvider, db } from '../firebase';
import { signInWithPopup, signInWithEmailAndPassword, createUserWithEmailAndPassword, updateProfile } from 'firebase/auth';
import { doc, getDoc, setDoc } from 'firebase/firestore';
import { Gamepad2, Chrome, ShieldCheck, Mail, Lock, User, CheckCircle2 } from 'lucide-react';
import { Language } from '../translations';
interface LoginViewProps {
onLoginSuccess: (user: any) => void;
currentLanguage: Language;
setLanguage: (lang: Language) => void;
}
type AuthMode = 'login' | 'register';
export const LoginView: React.FC<LoginViewProps> = ({ onLoginSuccess, currentLanguage, setLanguage }) => {
const [mode, setMode] = useState<AuthMode>('login');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Form states
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [agreedToTerms, setAgreedToTerms] = useState(false);
const localUi = {
EN: {
welcome: 'WELCOME TO NOVA ESPORTS',
prompt: 'GAMER PORTAL GATEWAY',
desc: 'Lock in your competitive achievements, organize elite clans, and coordinate tournament actions in real-time.',
googleBtnLabel: 'Sign In with Google',
loadingText: 'Decrypting credentials...',
securitySecure: 'Level 4 Encrypted Security Gate Active',
footerDisclaimer: 'By entering the arena, you agree to fair-play rules and global guidelines.',
tabLogin: 'Sign In',
tabRegister: 'Create Account',
namePlaceholder: 'Your Gamer Name (Nickname)',
emailPlaceholder: 'Email Address (Gmail)',
passwordPlaceholder: 'Secret Access Code (Password)',
confirmPasswordPlaceholder: 'Verify Access Code',
agreeTermsText: 'I agree to the competitive fair-play regulations and rules',
loginSubmit: 'Launch Portal Sign-In',
registerSubmit: 'Initialize Elite Registration',
errPasswordMismatch: 'Access codes do not match!',
errAgreeTerms: 'You must accept the terms & regulations to proceed.',
orLabel: 'OR ENTER VIA'
},
UZ: {
welcome: 'NOVA ESPORTS-GA XUSH KELIBSIZ',
prompt: 'GAMER PORTAL TIZIMI',
desc: 'Natijalaringizni saqlang, elita klanlarni tashkil qiling va real vaqt rejimida turnirlarni muvofiqlashtiring.',
googleBtnLabel: 'Google orqali kirish',
loadingText: 'Gamer hisobi yuklanmoqda...',
securitySecure: '4-darajali himoyalangan xavfsizlik darvozasi faol',
footerDisclaimer: 'Aronaga kirish orqali siz halol o‘yin va global qoidalarga rozilik bildirasiz.',
tabLogin: 'Kirish',
tabRegister: 'Roʻyxatdan oʻtish',
namePlaceholder: 'Gamer ismi (Taxallusingiz)',
emailPlaceholder: 'Email manzili (Gmail)',
passwordPlaceholder: 'Maxfiy kirish kodi (Parol)',
confirmPasswordPlaceholder: 'Parolni tasdiqlash',
agreeTermsText: 'Men halol o‘yin qoidalari va musobaqa nizomiga roziman',
loginSubmit: 'Portalga kirish',
registerSubmit: 'Gamer sifatida roʻyxatdan oʻtish',
errPasswordMismatch: 'Kiritilgan parollar mos kelmadi!',
errAgreeTerms: 'Davom etish uchun qoidalarga rozilik berishingiz shart.',
orLabel: 'YOKI QUYIDAGI ORQALI'
},
RU: {
welcome: 'ДОБРО ПОЖАЛОВАТЬ В NOVA ESPORTS',
prompt: 'ВХОД В ИГРОВОЙ ПОРТАЛ',
desc: 'Фиксируйте свои достижения, создавайте элитные кланы и координируйте турнирные матчи в реальном времени.',
googleBtnLabel: 'Войти через Google',
loadingText: 'Дешифрование доступов...',
securitySecure: 'Активен шлюз безопасности 4-го уровня',
footerDisclaimer: 'Входя на арену, вы соглашаетесь с правилами честной игры и регламентом.',
tabLogin: 'Войти',
tabRegister: 'Регистрация',
namePlaceholder: 'Имя геймера (Никнейм)',
emailPlaceholder: 'Адрес электронной почты (Gmail)',
passwordPlaceholder: 'Секретный код доступа (Пароль)',
confirmPasswordPlaceholder: 'Подтвердите код доступа',
agreeTermsText: 'Я согласен с регламентом честной игры и правилами',
loginSubmit: 'Войти в портал',
registerSubmit: 'Создать аккаунт геймера',
errPasswordMismatch: 'Пароли не совпадают!',
errAgreeTerms: 'Вы должны согласиться с правилами для продолжения.',
orLabel: 'ИЛИ ВОЙТИ С ПОМОЩЬЮ'
}
};
const ui = localUi[currentLanguage] || localUi['EN'];
// Safe Firestore Profile Synchronizer
const syncUserProfile = async (uid: string, userEmail: string, displayName: string, photoURL?: string) => {
const userRef = doc(db, 'users', uid);
const docSnap = await getDoc(userRef);
let finalUserData;
const latestName = displayName || 'GamerGladiator';
const latestEmail = userEmail || '';
const latestAvatar = photoURL || '👤';
if (!docSnap.exists()) {
const isOwnerAdmin = latestEmail === 'musabekqurbonov7@gmail.com' || latestEmail === 'musabekqurbonov10@gmail.com';
// Initialize stats to 0/empty
finalUserData = {
id: uid,
username: latestName,
email: latestEmail,
avatar: latestAvatar,
role: isOwnerAdmin ? 'admin' : 'user',
points: 0,
registeredTournaments: [],
joinedAt: new Date().toLocaleDateString(),
achievements: [],
notifications: [
{
id: `notif-${Date.now()}`,
title: currentLanguage === 'UZ' ? 'Hush kelibsiz!' : 'Welcome Gladiator!',
message: currentLanguage === 'UZ'
? 'Siz muvaffaqiyatli ro‘yxatdan o‘tdingiz. Barcha ko‘rsatkichlar 0 ko‘rsatmoqda.'
: 'Successfully entered the arena. All parameters are reset to 0.',
time: 'Just now',
read: false,
type: 'success'
}
]
};
await setDoc(userRef, finalUserData);
} else {
const existingData = docSnap.data() as any;
const isOwnerAdmin = latestEmail === 'musabekqurbonov7@gmail.com' || latestEmail === 'musabekqurbonov10@gmail.com';
const newRole = isOwnerAdmin ? 'admin' : (existingData.role || 'user');
// Keep metadata synced up
if (
existingData.username !== latestName ||
existingData.email !== latestEmail ||
existingData.role !== newRole
) {
const { updateDoc } = await import('firebase/firestore');
await updateDoc(userRef, {
username: latestName,
email: latestEmail,
role: newRole
});
existingData.username = latestName;
existingData.email = latestEmail;
existingData.role = newRole;
}
finalUserData = existingData;
}
return finalUserData;
};
const handleGoogleSignIn = async () => {
setLoading(true);
setError(null);
try {
const result = await signInWithPopup(auth, googleProvider);
const user = result.user;
const finalProfile = await syncUserProfile(user.uid, user.email || '', user.displayName || 'GamerGladiator', user.photoURL || '👤');
onLoginSuccess(finalProfile);
} catch (err: any) {
console.error('Google Sign-In Error:', err);
setError(err.message || String(err));
} finally {
setLoading(false);
}
};
const handleEmailAuth = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
if (!email || !password) {
return;
}
setLoading(true);
try {
if (mode === 'register') {
// Registration validation
if (password !== confirmPassword) {
setError(ui.errPasswordMismatch);
setLoading(false);
return;
}
if (!agreedToTerms) {
setError(ui.errAgreeTerms);
setLoading(false);
return;
}
// Create Firebase Auth User
const result = await createUserWithEmailAndPassword(auth, email, password);
const user = result.user;
// Set Auth Display Name
await updateProfile(user, { displayName: name });
// Save User Details to Firestore
const finalProfile = await syncUserProfile(user.uid, email, name, '👤');
onLoginSuccess(finalProfile);
} else {
// Sign In
const result = await signInWithEmailAndPassword(auth, email, password);
const user = result.user;
const finalProfile = await syncUserProfile(user.uid, user.email || email, user.displayName || 'GamerGladiator');
onLoginSuccess(finalProfile);
}
} catch (err: any) {
console.error('Auth Error:', err);
// Simplify Firebase error messages for the user
let errMsg = err.message || String(err);
if (err.code === 'auth/email-already-in-use') {
errMsg = currentLanguage === 'UZ' ? 'Ushbu email allaqachon ro‘yxatdan o‘tkazilgan.' : 'This email is already registered.';
} else if (err.code === 'auth/wrong-password') {
errMsg = currentLanguage === 'UZ' ? 'Noto‘g‘ri parol kiritildi.' : 'Incorrect password.';
} else if (err.code === 'auth/user-not-found') {
errMsg = currentLanguage === 'UZ' ? 'Ushbu email bilan foydalanuvchi topilmadi.' : 'No account found with this email.';
} else if (err.code === 'auth/weak-password') {
errMsg = currentLanguage === 'UZ' ? 'Parol juda kuchsiz (kamida 6 ta belgi bo‘lishi kerak).' : 'Password is too weak (min 6 characters).';
} else if (err.code === 'auth/invalid-email') {
errMsg = currentLanguage === 'UZ' ? 'Noto‘g‘ri email formati.' : 'Invalid email format.';
}
setError(errMsg);
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen bg-[#020205] text-slate-100 flex flex-col justify-between relative overflow-hidden font-sans" id="login-screen-v5">
{/* Abstract Glowing Background Orbs */}
<div className="absolute -top-40 -left-40 w-96 h-96 bg-purple-600/10 rounded-full blur-[140px] pointer-events-none z-0"></div>
<div className="absolute bottom-10 -right-40 w-96 h-96 bg-cyan-500/10 rounded-full blur-[140px] pointer-events-none z-0"></div>
{/* Language Bar Top Right */}
<div className="relative z-10 max-w-7xl mx-auto w-full px-6 py-4 flex justify-end gap-2.5">
{(['UZ', 'RU', 'EN'] as const).map((lang) => (
<button
key={lang}
onClick={() => setLanguage(lang)}
className={`px-3 py-1 bg-white/5 border text-xs font-mono rounded-lg transition-all cursor-pointer ${
currentLanguage === lang
? 'text-cyan-400 border-cyan-500 bg-white/10 font-bold shadow-[0_0_8px_rgba(34,211,238,0.2)]'
: 'text-slate-400 border-white/5 hover:text-white hover:border-white/10'
}`}
>
{lang}
</button>
))}
</div>
{/* Center authentication Box */}
<div className="relative z-10 flex-1 flex items-center justify-center px-4 py-8">
<div className="bg-[#0b0c14] border border-white/10 hover:border-cyan-500/15 max-w-md w-full rounded-2xl p-6 md:p-8 space-y-6 shadow-[0_20px_50px_rgba(0,0,0,0.5)] transition-all flex flex-col">
{/* Logo element matches style precisely */}
<div className="flex flex-col items-center gap-2.5 text-center">
<div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-cyan-400 to-purple-600 p-[1.5px] shadow-[0_0_15px_rgba(34,211,238,0.25)]">
<div className="w-full h-full bg-[#020205]/60 backdrop-blur-md rounded-[14px] flex items-center justify-center font-black text-white text-xl font-mono">
<span className="text-cyan-400">N</span>E
</div>
</div>
<div className="space-y-0.5">
<span className="text-[10px] text-cyan-400 tracking-[0.2em] font-black uppercase font-mono">{ui.welcome}</span>
<h2 className="text-base font-black text-white uppercase tracking-wider font-mono">{ui.prompt}</h2>
</div>
</div>
{/* Toggle Tabs between Sign In and Create Account */}
<div className="grid grid-cols-2 p-1 bg-white/5 rounded-xl border border-white/15" id="auth-mode-tabs">
<button
type="button"
onClick={() => { setMode('login'); setError(null); }}
className={`py-2 text-xs font-bold rounded-lg transition-all ${
mode === 'login'
? 'bg-gradient-to-r from-cyan-500 to-blue-600 text-white shadow-md'
: 'text-slate-400 hover:text-slate-200'
}`}
>
{ui.tabLogin}
</button>
<button
type="button"
onClick={() => { setMode('register'); setError(null); }}
className={`py-2 text-xs font-bold rounded-lg transition-all ${
mode === 'register'
? 'bg-gradient-to-r from-cyan-500 to-blue-600 text-white shadow-md'
: 'text-slate-400 hover:text-slate-200'
}`}
>
{ui.tabRegister}
</button>
</div>
{error && (
<div className="p-3 bg-red-950/20 border border-red-500/20 text-red-400 rounded-xl text-xs font-mono text-center">
{error}
</div>
)}
{/* Email and Password authentication form */}
<form onSubmit={handleEmailAuth} className="space-y-4">
{mode === 'register' && (
<div className="space-y-1.5">
<label className="text-[10px] font-bold tracking-wider font-mono text-cyan-400 uppercase flex items-center gap-1">
<User className="w-3 h-3" /> NAME / USERNAME
</label>
<input
type="text"
required
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={ui.namePlaceholder}
className="w-full bg-[#05060b] border border-white/10 focus:border-cyan-500/50 rounded-xl px-4 py-3 text-xs text-white outline-none font-mono placeholder:text-slate-600"
/>
</div>
)}
<div className="space-y-1.5">
<label className="text-[10px] font-bold tracking-wider font-mono text-cyan-400 uppercase flex items-center gap-1">
<Mail className="w-3 h-3" /> EMAIL ADDRESS
</label>
<input
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={ui.emailPlaceholder}
className="w-full bg-[#05060b] border border-white/10 focus:border-cyan-500/50 rounded-xl px-4 py-3 text-xs text-white outline-none font-mono placeholder:text-slate-600"
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-bold tracking-wider font-mono text-cyan-400 uppercase flex items-center gap-1">
<Lock className="w-3 h-3" /> ACCESS PASSWORD
</label>
<input
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={ui.passwordPlaceholder}
className="w-full bg-[#05060b] border border-white/10 focus:border-cyan-500/50 rounded-xl px-4 py-3 text-xs text-white outline-none font-mono placeholder:text-slate-600"
/>
</div>
{mode === 'register' && (
<>
<div className="space-y-1.5">
<label className="text-[10px] font-bold tracking-wider font-mono text-cyan-400 uppercase flex items-center gap-1">
<Lock className="w-3 h-3" /> CONFIRM PASSWORD
</label>
<input
type="password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder={ui.confirmPasswordPlaceholder}
className="w-full bg-[#05060b] border border-white/10 focus:border-cyan-500/50 rounded-xl px-4 py-3 text-xs text-white outline-none font-mono placeholder:text-slate-600"
/>
</div>
{/* Agree to Rules / Rules Consent Checkbox */}
<div className="flex items-start gap-2.5 pt-1.5">
<input
type="checkbox"
id="terms-checkbox"
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
className="mt-0.5 rounded border-white/10 bg-[#05060b] text-cyan-500 focus:ring-cyan-500/30 cursor-pointer"
/>
<label htmlFor="terms-checkbox" className="text-[10px] text-slate-400 leading-normal select-none cursor-pointer hover:text-slate-300">
{ui.agreeTermsText}
</label>
</div>
</>
)}
<button
type="submit"
disabled={loading}
className="w-full py-3 px-4 bg-gradient-to-r from-cyan-500 to-purple-600 hover:brightness-110 text-white font-extrabold text-xs tracking-wider uppercase rounded-xl transition-all cursor-pointer shadow-lg active:scale-[0.98] disabled:opacity-50 disabled:pointer-events-none mt-2"
>
{loading ? ui.loadingText : (mode === 'login' ? ui.loginSubmit : ui.registerSubmit)}
</button>
</form>
{/* Elegant Or Divider */}
<div className="relative flex py-2 items-center">
<div className="flex-grow border-t border-white/5"></div>
<span className="flex-shrink mx-4 text-[9px] font-mono tracking-widest text-slate-500 uppercase">{ui.orLabel}</span>
<div className="flex-grow border-t border-white/5"></div>
</div>
{/* Compact Google login button - placed lower and styled smaller */}
<div className="flex justify-center">
<button
onClick={handleGoogleSignIn}
disabled={loading}
className="w-full max-w-xs py-2.5 px-4 bg-slate-900 border border-white/10 hover:border-cyan-500/30 text-slate-300 hover:text-white font-bold text-[11px] tracking-wide uppercase rounded-xl flex items-center justify-center gap-2 transition-all cursor-pointer shadow active:scale-95 disabled:opacity-50 disabled:pointer-events-none"
id="google-signin-btn-compact"
>
<Chrome className="w-3.5 h-3.5 text-cyan-400" />
{ui.googleBtnLabel}
</button>
</div>
{/* Footer security tag */}
<div className="flex items-center justify-center gap-1.5 text-[9px] text-slate-500 font-mono tracking-wider pt-2 border-t border-white/5">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-500 animate-pulse" />
<span>{ui.securitySecure}</span>
</div>
</div>
</div>
{/* Footer copyright */}
<div className="relative z-10 max-w-7xl mx-auto w-full px-6 py-4 text-center text-[9px] text-slate-600 font-mono tracking-wider">
{ui.footerDisclaimer}
</div>
</div>
);
};