import { Routes, Route, Navigate } from "react-router-dom";
import { useAuth } from "@/store/auth";
import { useMeSync } from "@/hooks/useMeSync";
import Login from "@/pages/Login";
import ActionMenu from "@/pages/ActionMenu";
import Home from "@/pages/Home";
import VehicleCard from "@/pages/VehicleCard";
import InspectionEditor from "@/pages/InspectionEditor";
import InspectionReview from "@/pages/InspectionReview";
import TtStateDetail from "@/pages/TtStateDetail";
import RepairsFeedPage from "@/pages/repairs/RepairsFeedPage";
import RepairDetailPage from "@/pages/repairs/RepairDetailPage";
import EditRepairPage from "@/pages/repairs/EditRepairPage";
import CarSelectPage from "@/pages/repairs/CarSelectPage";
import CreateRepairPage from "@/pages/repairs/CreateRepairPage";

function RequireAuth({ children }: { children: React.ReactNode }) {
  const token = useAuth((s) => s.token);
  if (!token) return <Navigate to="/login" replace />;
  return <>{children}</>;
}

export default function App() {
  // У35: фоновая сверка прав механика раз в 5 минут — выкидывает на /login
  // с сообщением «Доступ отозван», если админ снял can_login_pwa или вывел
  // пользователя из отдела механиков.
  useMeSync();

  return (
    <Routes>
      <Route path="/login" element={<Login />} />
      <Route path="/" element={<RequireAuth><ActionMenu /></RequireAuth>} />
      <Route path="/vehicles" element={<RequireAuth><Home /></RequireAuth>} />
      <Route path="/vehicles/:id" element={<RequireAuth><VehicleCard /></RequireAuth>} />
      <Route path="/inspections/:id/edit" element={<RequireAuth><InspectionEditor /></RequireAuth>} />
      <Route path="/inspections/:id" element={<RequireAuth><InspectionReview /></RequireAuth>} />
      <Route path="/tt-states/:id" element={<RequireAuth><TtStateDetail /></RequireAuth>} />
      {/* Раздел «Ремонт» — активируется в PR-5 (Фича 1). */}
      <Route path="/repairs" element={<RequireAuth><RepairsFeedPage /></RequireAuth>} />
      <Route path="/repairs/new" element={<RequireAuth><CarSelectPage /></RequireAuth>} />
      <Route path="/repairs/new/:carId" element={<RequireAuth><CreateRepairPage /></RequireAuth>} />
      <Route path="/repairs/new-external" element={<RequireAuth><CreateRepairPage /></RequireAuth>} />
      <Route path="/repairs/:id" element={<RequireAuth><RepairDetailPage /></RequireAuth>} />
      <Route path="/repairs/:id/edit" element={<RequireAuth><EditRepairPage /></RequireAuth>} />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}
