import { useState } from 'react'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { UserProvider, useUser } from './context/UserContext'
import Dashboard from './pages/Dashboard'
import ServerDetail from './pages/ServerDetail'
import LoginPage from './pages/LoginPage'
import AuthCallback from './pages/AuthCallback'

function ProtectedServerDetail({ onLogout }) {
  const { isGuest, loading } = useUser()

  if (loading) return null
  if (isGuest) return <Navigate to="/" replace />

  return <ServerDetail onLogout={onLogout} />
}

export default function App() {
  const [token, setToken] = useState(localStorage.getItem('gsm_token'))

  const handleLogin = (newToken) => {
    localStorage.setItem('gsm_token', newToken)
    setToken(newToken)
  }

  const handleLogout = () => {
    localStorage.removeItem('gsm_token')
    setToken(null)
  }

  return (
    <UserProvider token={token} onLogout={handleLogout}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={token ? <Dashboard onLogout={handleLogout} /> : <Navigate to="/login" replace />} />
          <Route path="/server/:serverId" element={token ? <ProtectedServerDetail onLogout={handleLogout} /> : <Navigate to="/login" replace />} />
          <Route path="/login" element={<LoginPage onLogin={handleLogin} />} />
          <Route path="/auth/callback" element={<AuthCallback onLogin={handleLogin} />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </BrowserRouter>
    </UserProvider>
  )
}
