import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

const Home = () => {
  const navigate = useNavigate();
  const { user, loginAnonymous, isAuthenticated } = useAuth();

  useEffect(() => {
    const initAuth = async () => {
      if (!isAuthenticated) {
        try {
          await loginAnonymous('Гость');
        } catch (error) {
          console.error('Auto login failed:', error);
        }
      }
    };

    initAuth();
  }, [isAuthenticated, loginAnonymous]);

  const handleCreateRoom = () => {
    navigate('/create-room');
  };

  const handleJoinRoom = () => {
    navigate('/join-room');
  };

  const handleLocalGame = () => {
    navigate('/local-game');
  };

  return (
    <div className="home-page">
      <div className="home-container">
        <h1>100 к 1</h1>
        <p className="welcome-text">
          {user ? `Привет, ${user.name}!` : 'Добро пожаловать!'}
        </p>

        <div className="menu-buttons">
          <button onClick={handleCreateRoom} className="menu-button primary">
            Создать комнату
          </button>

          <button onClick={handleJoinRoom} className="menu-button">
            Присоединиться к комнате
          </button>

          <button onClick={handleLocalGame} className="menu-button">
            Локальная игра
          </button>
        </div>

        {user && (
          <div className="user-stats">
            <p>Игр сыграно: {user.gamesPlayed || 0}</p>
            <p>Побед: {user.gamesWon || 0}</p>
            <p>Очков: {user.totalPoints || 0}</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default Home;
