import { Switch, Route, Router as WouterRouter } from "wouter";
import { useEffect } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nextProvider } from "react-i18next";
import i18n from "@/i18n";
import { loadCsrfToken } from "@/lib/csrf";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";

// Pages
import Home from "@/pages/home";
import ToolsBrowse from "@/pages/tools-browse";
import ToolDetail from "@/pages/tool-detail";
import ToolNew from "@/pages/tool-new";
import ToolEdit from "@/pages/tool-edit";
import Analytics from "@/pages/analytics";
import Admin from "@/pages/admin";
import Redundancy from "@/pages/redundancy";
import Trash from "@/pages/trash";
import Compare from "@/pages/compare";
import Watchlist from "@/pages/watchlist";
import Login from "@/pages/login";
import Docs from "@/pages/docs";
import NotFound from "@/pages/not-found";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      staleTime: 1000 * 60 * 5, // 5 minutes
    },
  },
});

function Router() {
  return (
    <Switch>
      <Route path="/" component={Home} />
      <Route path="/login" component={Login} />
      <Route path="/tools" component={ToolsBrowse} />
      <Route path="/tools/new" component={ToolNew} />
      <Route path="/tools/:id/edit" component={ToolEdit} />
      <Route path="/tools/:id" component={ToolDetail} />
      <Route path="/compare" component={Compare} />
      <Route path="/watchlist" component={Watchlist} />
      <Route path="/analytics" component={Analytics} />
      <Route path="/admin" component={Admin} />
      <Route path="/admin/redundancy" component={Redundancy} />
      <Route path="/trash" component={Trash} />
      <Route path="/docs/*?" component={Docs} />
      <Route component={NotFound} />
    </Switch>
  );
}

function App() {
  useEffect(() => {
    void loadCsrfToken();
  }, []);
  return (
    <I18nextProvider i18n={i18n}>
      <QueryClientProvider client={queryClient}>
        <TooltipProvider>
          <WouterRouter base={import.meta.env.BASE_URL.replace(/\/$/, "")}>
            <Router />
          </WouterRouter>
          <Toaster />
        </TooltipProvider>
      </QueryClientProvider>
    </I18nextProvider>
  );
}

export default App;
