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 SettingsPage from "@/features/settings-page";
import NetworkSelector from "@/features/network-selector";
import NetworkRoot from "@/features/network-root";
import ParticleViewResolver from "@/features/particles/particle-view-resolver";
import Layout from "@/features/layout";

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() {
  return (
    <HashRouter>
      <Routes>
        <Route path="settings" element={<SettingsPage />} />

        <Route path="/" element={<Layout />}>
          <Route index element={<NetworkSelector />} />
          <Route path=":networkId">
            <Route index element={<NetworkRoot />} />
            <Route path="*" element={<ParticleViewResolver />} />
          </Route>
        </Route>
      </Routes>
    </HashRouter>
  );
}

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

export default AppWithProviders;
