﻿import { Navigate, Route, Routes } from 'react-router-dom'
import { AppLayout } from './components/AppLayout'
import { AdminPage } from './pages/Admin'
import { AlertsPage } from './pages/Alerts'
import { DeviceDetailPage } from './pages/DeviceDetail'
import { HomePage } from './pages/Home'
import { HomeObjectDetailPage } from './pages/HomeObjectDetail'
import { HomeSettingsPage } from './pages/HomeSettings'
import { LoginPage } from './pages/Login'
import { ObjectsPage } from './pages/Objects'
import { SnapshotDashboardPage } from './pages/SnapshotDashboard'
import { SnapshotsPage } from './pages/Snapshots'
import { TaskDetailPage } from './pages/TaskDetail'
import { TasksPage } from './pages/Tasks'
import { ObjectDetailPage } from './pages/ObjectDetail'
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="/home" replace />} />
        <Route path="home" element={<HomePage />} />
        <Route path="home/settings" element={<HomeSettingsPage />} />
        <Route path="home/objects/:id" element={<HomeObjectDetailPage />} />

        {/* Inventory */}
        <Route path="inventory/objects" element={<ObjectsPage mode="inventory" />} />
        <Route path="inventory/objects/:id" element={<ObjectDetailPage defaultMode="inventory" />} />
        <Route path="inventory/objects/:id/devices/:deviceId" element={<DeviceDetailPage />} />
        <Route path="inventory/objects/:id/snapshots" element={<SnapshotsPage />} />

        {/* Work */}
        <Route path="work/objects" element={<ObjectsPage mode="work" />} />
        <Route path="work/objects/:id" element={<ObjectDetailPage defaultMode="work" />} />
        <Route path="work/devices" element={<WorkDevicesPage />} />
        <Route path="snapshots" element={<SnapshotDashboardPage />} />

        {/* Common */}
        <Route path="alerts" element={<AlertsPage />} />
        <Route path="tasks" element={<TasksPage />} />
        <Route path="tasks/:id" element={<TaskDetailPage />} />
        <Route path="admin" element={<AdminPage />} />

        {/* Legacy URLs for backward compatibility */}
        <Route path="objects" element={<Navigate to="/inventory/objects" replace />} />
        <Route path="objects/:id" element={<Navigate to="/inventory/objects" replace />} />
      </Route>
    </Routes>
  )
}
