import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useState, useEffect } from 'react';
import Daily from './pages/Daily';
import AddEntry from './pages/AddEntry';
import EntryDetail from './pages/EntryDetail';
import Login from './pages/Login';
import Admin from './pages/Admin';
import Weekly from './pages/Weekly';
import Leaderboard from './pages/Leaderboard';
import Photos from './pages/Photos';
import Goals from './pages/Goals';

function PrivateRoute({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) setUser(JSON.parse(storedUser));
    setLoading(false);
  }, []);
  
  if (loading) return <div>Loading...</div>;
  return user ? children : <Navigate to="/login" />;
}

function AdminRoute() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) setUser(JSON.parse(storedUser));
    setLoading(false);
  }, []);
  
  if (loading) return <div>Loading...</div>;
  if (!user || user.username !== 'admin') return <Navigate to="/" />;
  return <Admin />;
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/" element={<PrivateRoute><Daily /></PrivateRoute>} />
        <Route path="/add" element={<PrivateRoute><AddEntry /></PrivateRoute>} />
        <Route path="/entry/:id" element={<PrivateRoute><EntryDetail /></PrivateRoute>} />
        <Route path="/admin" element={<AdminRoute />} />
        <Route path="/weekly" element={<PrivateRoute><Weekly /></PrivateRoute>} />
        <Route path="/leaderboard" element={<PrivateRoute><Leaderboard /></PrivateRoute>} />
        <Route path="/photos" element={<PrivateRoute><Photos /></PrivateRoute>} />
        <Route path="/goals" element={<PrivateRoute><Goals /></PrivateRoute>} />
      </Routes>
    </BrowserRouter>
  );
}
