import React, { useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAppSelector } from './store';
import MainLayout from './layouts/MainLayout';
import HomePage from './pages/HomePage';
import ChatPage from './pages/ChatPage';
import CallsPage from './pages/CallsPage';
import SettingsPage from './pages/SettingsPage';
import LoginPage from './pages/LoginPage';
import './styles/app.css';

export default function App() {
  const { user, loading } = useAppSelector(state => state.auth);

  useEffect(() => {
    // Restore auth state on app load
    const token = localStorage.getItem('authToken');
    if (token && !user) {
      // Token exists but user not loaded - this would be handled by Redux persist
      console.log('Auth token found, waiting for hydration...');
    }
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-900">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-purple-500"></div>
      </div>
    );
  }

  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        path="/*"
        element={
          user ? (
            <MainLayout>
              <Routes>
                <Route path="/" element={<HomePage />} />
                <Route path="/chat/*" element={<ChatPage />} />
                <Route path="/calls/*" element={<CallsPage />} />
                <Route path="/settings/*" element={<SettingsPage />} />
                <Route path="*" element={<Navigate to="/" replace />} />
              </Routes>
            </MainLayout>
          ) : (
            <Navigate to="/login" replace />
          )
        }
      />
    </Routes>
  );
}
