import Footer from './components/Footer/Footer';
import React, { useState, useEffect } from 'react';
import { Routes, Route, useNavigate } from 'react-router-dom';

import Navbar from './components/Navbar/Navbar';
import Home from './components/Home/Home';
import Profile from './components/Profile/Profile';
import Login from './components/Login/Login';
import CreatePost from './components/Create Post/CreatePost';
import UserProfile from './components/Profile/UserProfile';

import './App.css';

const App = () => {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    // On page load, restore the logged-in user from localStorage if a session exists
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      setCurrentUser(JSON.parse(storedUser));
    }
    setLoading(false);
  }, []);

  const handleLogin = (user) => {
    setCurrentUser(user);
    navigate('/');
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setCurrentUser(null);
    navigate('/login');
  };

  if (loading) {
    return (
      <div className="loading">
        <div className="spinner"></div>
      </div>
    );
  }

  if (!currentUser) {
    return <Login onLogin={handleLogin} />;
  }

 return (
  <div className="app-container">

    <Navbar onLogout={handleLogout} currentUser={currentUser} />

    <div className="page-content">
      <Routes>
        <Route path="/" element={<Home currentUser={currentUser} />} />
        <Route
          path="/profile"
          element={
            <Profile
              currentUser={currentUser}
              onUserUpdate={setCurrentUser}
            />
          }
        />
        <Route
          path="/create-post"
          element={<CreatePost currentUser={currentUser} />}
        />
        <Route
          path="/profile/:uid"
          element={<UserProfile currentUser={currentUser} />}
        />
      </Routes>
    </div>

    <Footer />

  </div>
);
};

export default App;
