import { Navigate, Route, Routes } from 'react-router-dom'
import { AppLayout } from './components/AppLayout'
import { AdminPage } from './pages/Admin'
import { AlertsPage } from './pages/Alerts'
import { LoginPage } from './pages/Login'
import { ObjectsPage } from './pages/Objects'
import { SnapshotsPage } from './pages/Snapshots'
import { TaskDetailPage } from './pages/TaskDetail'
import { TasksPage } from './pages/Tasks'
import { InventoryObjectDetailPage } from './pages/InventoryObjectDetail'
import { WorkObjectDetailPage } from './pages/WorkObjectDetail'
import { WorkDevicesPage } from './pages/WorkDevices'
import { useAuthStore } from './store/auth'

function RequireAuth({ children }: { children: React.ReactNode }) {
  const token = useAuthStore((s) => s.accessToken)
  return token ? <>{children}</> : <Navigate to="/login" replace />
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        path="/"
        element={
          <RequireAuth>
            <AppLayout />
          </RequireAuth>
        }
      >
        <Route index element={<Navigate to="/inventory/objects" replace />} />

        {/* Инвентарь */}
        <Route path="inventory/objects" element={<ObjectsPage mode="inventory" />} />
        <Route path="inventory/objects/:id" element={<InventoryObjectDetailPage />} />
        <Route path="inventory/objects/:id/snapshots" element={<SnapshotsPage />} />

        {/* Работа */}
        <Route path="work/objects" element={<ObjectsPage mode="work" />} />
        <Route path="work/objects/:id" element={<WorkObjectDetailPage />} />
        <Route path="work/devices" element={<WorkDevicesPage />} />

        {/* Общие */}
        <Route path="alerts" element={<AlertsPage />} />
        <Route path="tasks" element={<TasksPage />} />
        <Route path="tasks/:id" element={<TaskDetailPage />} />
        <Route path="admin" element={<AdminPage />} />

        {/* Старые URL — редирект для совместимости */}
        <Route path="objects" element={<Navigate to="/inventory/objects" replace />} />
        <Route path="objects/:id" element={<Navigate to="/inventory/objects" replace />} />
      </Route>
    </Routes>
  )
}
