import { useEffect } from "react";
import { HashRouter, Routes, Route } from "react-router-dom";
import { TooltipProvider } from "@/components/ui/tooltip";
import { useAppStore } from "@/stores/app-store";
import { useAuthStore } from "@/stores/auth-store";
import { LoginPage } from "@/features/auth/login-page";
import { StreamsPage } from "@/pages/streams-page";
import { StreamPlayerPage } from "@/pages/stream-player-page";

function AuthenticatedApp() {
  const fetchStartup = useAppStore((s) => s.fetchStartup);
  const isLoading = useAppStore((s) => s.isLoading);

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

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

  return (
    <TooltipProvider>
      <HashRouter>
        <Routes>
          <Route path="/" element={<StreamsPage />} />
          <Route path="/streams/:streamId" element={<StreamPlayerPage />} />
        </Routes>
      </HashRouter>
    </TooltipProvider>
  );
}

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 />;
};

export default App;
