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 = ({ onLoginSuccess, currentLanguage, setLanguage }) => { const [mode, setMode] = useState('login'); const [loading, setLoading] = useState(false); const [error, setError] = useState(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 (
{/* Abstract Glowing Background Orbs */}
{/* Language Bar Top Right */}
{(['UZ', 'RU', 'EN'] as const).map((lang) => ( ))}
{/* Center authentication Box */}
{/* Logo element matches style precisely */}
NE
{ui.welcome}

{ui.prompt}

{/* Toggle Tabs between Sign In and Create Account */}
{error && (
{error}
)} {/* Email and Password authentication form */}
{mode === 'register' && (
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" />
)}
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" />
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" />
{mode === 'register' && ( <>
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" />
{/* Agree to Rules / Rules Consent Checkbox */}
setAgreedToTerms(e.target.checked)} className="mt-0.5 rounded border-white/10 bg-[#05060b] text-cyan-500 focus:ring-cyan-500/30 cursor-pointer" />
)}
{/* Elegant Or Divider */}
{ui.orLabel}
{/* Compact Google login button - placed lower and styled smaller */}
{/* Footer security tag */}
{ui.securitySecure}
{/* Footer copyright */}
{ui.footerDisclaimer}
); };