import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { useAppStore } from './store/app'
import Layout from './components/Layout'
import SetupWizard from './pages/SetupWizard'
import Dashboard from './pages/Dashboard'
import Agents from './pages/Agents'
import AgentCreate from './pages/AgentCreate'
import AgentImport from './pages/AgentImport'
import AgentEdit from './pages/AgentEdit'
import Chat from './pages/Chat'
import Providers from './pages/Providers'
import Knowledge from './pages/Knowledge'
import KnowledgeDetail from './pages/KnowledgeDetail'
import AgentPacks from './pages/AgentPacks'
import AgentWorkspace from './pages/AgentWorkspace'
import Connections from './pages/Connections'

function RequireAuth({ children }: { children: React.ReactNode }) {
  const apiKey = useAppStore(s => s.apiKey)
  if (!apiKey) return <Navigate to="/setup" replace />
  return <>{children}</>
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/setup" element={<SetupWizard />} />
        <Route
          path="/"
          element={
            <RequireAuth>
              <Layout />
            </RequireAuth>
          }
        >
          <Route index element={<Navigate to="/dashboard" replace />} />
          <Route path="dashboard" element={<Dashboard />} />
          <Route path="agents" element={<Agents />} />
          <Route path="agents/new" element={<AgentCreate />} />
          <Route path="agents/import" element={<AgentImport />} />
          <Route path="agents/:agentId/edit" element={<AgentEdit />} />
          <Route path="agents/:agentId/workspace" element={<AgentWorkspace />} />
          <Route path="chat/:agentId" element={<Chat />} />
          <Route path="settings/providers" element={<Providers />} />
          <Route path="settings/connections" element={<Connections />} />
          <Route path="knowledge" element={<Knowledge />} />
          <Route path="knowledge/:kbId" element={<KnowledgeDetail />} />
          <Route path="agentpacks" element={<AgentPacks />} />
        </Route>
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </BrowserRouter>
  )
}
