import React, { useEffect, useState } from 'react';
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from 'react-router-dom';
import Lobby from './components/Lobby/Lobby';
import VotingTable from './components/VotingTable/VotingTable';
import UserSessionListener from './components/UserSessionListener/UserSessionListener';
import { signInAnonymously, onAuthStateChanged } from 'firebase/auth';
import { auth } from './services/firebase';

const App = () => {
  const [userId, setUserId] = useState('');
  const [loading, setLoading] = useState(true);

  const handleJoinSession = (userId) => {
    setUserId(userId);
    return true;
  };

  useEffect(() => {
    // Sign in the user anonymously
    signInAnonymously(auth).catch((error) => {
      console.error('Anonymous sign-in error:', error);
    });

    // Handle user state changes
    onAuthStateChanged(auth, (user) => {
      if (user) {
        console.log('User is signed in:', user);
      } else {
        console.log('User is signed out');
      }
      setLoading(false);
    });
  }, []);

  return (
    <Router>
      <UserSessionListener />
      <Routes>
        <Route
          path="/lobby/:sessionId?"
          element={<Lobby onJoinSession={handleJoinSession} />}
          loading={loading}
        />
        <Route
          path="/session/:sessionId"
          element={<VotingTable userId={userId} />}
        />
        <Route path="*" element={<Navigate to={`/lobby`} />} />
      </Routes>
    </Router>
  );
};

export default App;
