import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { useState, useEffect } from 'react'
import LoginPage from './pages/Login'
import RegisterPage from './pages/Register'
import HomePage from './pages/Home'
import AdminPage from './pages/Admin'
import InstallPage from './pages/Install'

function App() {
  const [isInstalled, setIsInstalled] = useState<boolean | null>(null)
  const [token, setToken] = useState<string | null>(localStorage.getItem('token'))

  useEffect(() => {
    // 检查是否已安装
    fetch('/api/install/check')
      .then(res => res.json())
      .then(data => setIsInstalled(data.installed))
      .catch(() => setIsInstalled(false))
  }, [])

  if (isInstalled === null) {
    return <div className="container text-center">加载中...</div>
  }

  if (!isInstalled) {
    return (
      <BrowserRouter>
        <Routes>
          <Route path="/install" element={<InstallPage onInstall={() => setIsInstalled(true)} />} />
          <Route path="*" element={<Navigate to="/install" replace />} />
        </Routes>
      </BrowserRouter>
    )
  }

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<LoginPage onLogin={setToken} />} />
        <Route path="/register" element={<RegisterPage />} />
        <Route path="/" element={token ? <HomePage token={token} /> : <Navigate to="/login" />} />
        <Route path="/admin" element={token ? <AdminPage token={token} /> : <Navigate to="/login" />} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </BrowserRouter>
  )
}

export default App