import React, { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAuth } from '../context/AuthContext'; import ThemeSwitcher from '../components/ThemeSwitcher'; const Home = () => { const navigate = useNavigate(); const { user, loginAnonymous, isAuthenticated, updateUserName } = useAuth(); const [editingName, setEditingName] = useState(false); const [nameValue, setNameValue] = useState(''); const [isUpdating, setIsUpdating] = useState(false); useEffect(() => { const initAuth = async () => { if (!isAuthenticated) { try { await loginAnonymous('Гость'); } catch (error) { console.error('Auto login failed:', error); } } }; initAuth(); }, [isAuthenticated, loginAnonymous]); useEffect(() => { if (user) { setNameValue(user.name || ''); } }, [user]); const handleNameClick = () => { setEditingName(true); }; const handleNameChange = (e) => { setNameValue(e.target.value); }; const handleNameBlur = async () => { setEditingName(false); if (nameValue.trim() && nameValue.trim() !== user?.name) { setIsUpdating(true); try { await updateUserName(nameValue.trim()); } catch (error) { console.error('Failed to update name:', error); setNameValue(user?.name || ''); } finally { setIsUpdating(false); } } else { setNameValue(user?.name || ''); } }; const handleNameKeyPress = (e) => { if (e.key === 'Enter') { e.target.blur(); } }; const handleCreateRoom = () => { navigate('/create-room'); }; const handleJoinRoom = () => { navigate('/join-room'); }; return (
Игр сыграно: {user.gamesPlayed || 0}
Побед: {user.gamesWon || 0}
Очков: {user.totalPoints || 0}