import { useState, useEffect } from 'react'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { AuthContext } from './api'
import api from './api'
import Login from './components/Login'
import Dashboard from './components/Dashboard'
import CrawlDetail from './components/CrawlDetail'
import CasinoReport from './components/CasinoReport'
import Sidebar from './components/Sidebar'
import './App.css'

function PrivateRoute({ children }) {
  const token = localStorage.getItem('token')
  return token ? children : <Navigate to="/login" />
}

function App() {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      setUser(JSON.parse(storedUser))
    }
    setLoading(false)
  }, [])

  const handleLogin = async (data) => {
    setUser(data.user)
    localStorage.setItem('user', JSON.stringify(data.user))
  }

  const handleLogout = () => {
    api.logout()
    setUser(null)
  }

  if (loading) return <div className="loading">Loading...</div>

  return (
    <AuthContext.Provider value={{ user, logout: handleLogout }}>
      <BrowserRouter>
        <div className="app">
          <Sidebar onLogout={handleLogout} />
          <main className="content">
            <Routes>
              <Route path="/login" element={<Login onLogin={handleLogin} />} />
              <Route path="/" element={
                <PrivateRoute><Dashboard /></PrivateRoute>
              } />
              <Route path="/crawl/:id" element={
                <PrivateRoute><CrawlDetail /></PrivateRoute>
              } />
              <Route path="/report" element={
                <PrivateRoute><CasinoReport /></PrivateRoute>
              } />
            </Routes>
          </main>
        </div>
      </BrowserRouter>
    </AuthContext.Provider>
  )
}

export default App
