import { useEffect } from "react";
import {
  BrowserRouter,
  Routes,
  Route,
  Navigate,
  useLocation,
} from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useAuthStore } from "@/stores/authStore";
import { useUiSettingsStore } from "@/stores/uiSettingsStore";
import { Navbar } from "@/components/ui/Navbar";
import { ToastViewport } from "@/components/ui/Toast";
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
import { LoginPage } from "@/pages/LoginPage";
import { RegisterPage } from "@/pages/RegisterPage";
import { AdminRegisterPage } from "@/pages/AdminRegisterPage";
import { WorldsListPage } from "@/pages/WorldsListPage";
import { WorldBuilderPage } from "@/pages/WorldBuilderPage";
import { WorldEditPage } from "@/pages/WorldEditPage";
import { PlayPage } from "@/pages/PlayPage";
import { AdminPage } from "@/pages/AdminPage";

function Layout({ children }: { children: React.ReactNode }) {
  return (
    <div className="min-h-screen bg-bg text-fg">
      <Navbar />
      {children}
      <ToastViewport />
    </div>
  );
}

function RootRedirect() {
  const status = useAuthStore((s) => s.status);
  const user = useAuthStore((s) => s.user);
  if (status === "authenticated" && user) return <Navigate to="/worlds" replace />;
  return <Navigate to="/login" replace />;
}

function PublicOnly({ children }: { children: React.ReactNode }) {
  const status = useAuthStore((s) => s.status);
  const user = useAuthStore((s) => s.user);
  const location = useLocation();
  if (status === "authenticated" && user) {
    const from = (location.state as { from?: string } | null)?.from;
    return <Navigate to={from || "/worlds"} replace />;
  }
  return <>{children}</>;
}

function ScrollToTop() {
  const { pathname } = useLocation();
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);
  return null;
}

export default function App() {
  const { t } = useTranslation();
  const uiSettings = useUiSettingsStore((s) => s.settings);
  // On mount, fetch public UI settings (page title, favicon, logo).
  const fetchUiSettings = useUiSettingsStore((s) => s.fetch);
  useEffect(() => {
    void fetchUiSettings();
  }, [fetchUiSettings]);

  // Keep document.title in sync with public settings (or default to app name).
  useEffect(() => {
    if (uiSettings?.page_title) document.title = uiSettings.page_title;
    else document.title = t("common.app_name");
  }, [uiSettings?.page_title, t]);

  return (
    <BrowserRouter>
      <ScrollToTop />
      <Routes>
        <Route path="/" element={<RootRedirect />} />

        {/* Public auth routes — full layout but no navbar redirect */}
        <Route
          path="/login"
          element={
            <PublicOnly>
              <Layout>
                <LoginPage />
              </Layout>
            </PublicOnly>
          }
        />
        <Route
          path="/register"
          element={
            <PublicOnly>
              <Layout>
                <RegisterPage />
              </Layout>
            </PublicOnly>
          }
        />
        <Route
          path="/register/admin"
          element={
            <PublicOnly>
              <Layout>
                <AdminRegisterPage />
              </Layout>
            </PublicOnly>
          }
        />

        {/* Protected routes */}
        <Route
          path="/worlds"
          element={
            <ProtectedRoute>
              <Layout>
                <WorldsListPage />
              </Layout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/worlds/new"
          element={
            <ProtectedRoute>
              <Layout>
                <WorldBuilderPage />
              </Layout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/worlds/:id/edit"
          element={
            <ProtectedRoute>
              <Layout>
                <WorldEditPage />
              </Layout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/worlds/:id/play"
          element={
            <ProtectedRoute>
              <Layout>
                <PlayPage />
              </Layout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/admin"
          element={
            <ProtectedRoute requireAdmin>
              <Layout>
                <AdminPage />
              </Layout>
            </ProtectedRoute>
          }
        />

        {/* Fallback */}
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </BrowserRouter>
  );
}
