import { useEffect } from "react";
import { HashRouter, Routes, Route } from "react-router-dom";
import { TooltipProvider } from "@/components/ui/tooltip";
import { useAuthStore } from "@/stores/auth-store";
import { LoginPage } from "@/features/auth/login-page";
import { } from "@/firebase";
import {
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query'
import PathResolver from "./pages/path-resolver";

const queryClient = new QueryClient();

const App = () => {
  const status = useAuthStore((s) => s.status);
  const restoreSession = useAuthStore((s) => s.restoreSession);

  useEffect(() => {
    restoreSession();
  }, [restoreSession]);

  if (status === "idle" || status === "restoring") {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <p className="text-muted-foreground text-sm">Loading...</p>
      </div>
    );
  }

  if (status !== "authenticated") {
    return <LoginPage />;
  }

  return <AuthenticatedApp />;
};

function AuthenticatedApp() {
  // NOTE: Hash router provides history, despite using catch-all
  return (
    <HashRouter>
      <Routes>
        <Route path="*" element={<PathResolver />} />
      </Routes>
    </HashRouter>
  );
}

const AppWithProviders = () => (
  <TooltipProvider>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </TooltipProvider>
);

export default AppWithProviders;
