import { VlogPage } from "./pages/VlogPage";
import { VideoPage } from "./pages/VideoPage";
import { KidsPage } from "./pages/KidsPage";
import { KidsGamePage } from "./pages/KidsGamePage";
import { SearchPage } from "./pages/SearchPage";
import { VideoManager } from "./components/admin/VideoManager";
import { VideoForm } from "./components/admin/VideoForm";
import React, { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import {
  BrowserRouter,
  Routes,
  Route,
  Outlet,
  useLocation,
  Link,
} from "react-router-dom";
import { CheckCircle2, X } from "lucide-react";
import { AppContext, useData } from "./lib";
import {
  Header,
  Footer,
  Home,
  GamesPage,
  CategoryPage,
  RecentPage,
  GamePage,
  Empty,
} from "./components/Public";
import {
  AdminLayout,
  Dashboard,
  ManageGames,
  GameForm,
  CategoryManager,
  AdminSettings,
} from "./components/Admin";
import "./styles.css";
import "./styles/discovery.css";
function ScrollReset() {
  const { pathname } = useLocation();
  useEffect(() => {
    window.scrollTo(0, 0);
    if (!pathname.startsWith("/games/"))
      document.title = pathname.startsWith("/admin")
        ? "Owner workspace | EverydayPlayedGames"
        : "EverydayPlayedGames — A little play. A better day.";
  }, [pathname]);
  return null;
}
function PublicLayout() {
  return (
    <>
      <Header />
      <Outlet />
      <Footer />
    </>
  );
}
class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { failed: boolean }
> {
  state = { failed: false };
  static getDerivedStateFromError() {
    return { failed: true };
  }
  render() {
    return this.state.failed ? (
      <div className="loading-page">
        <h1>A little pause in the play.</h1>
        <p>Something unexpected happened. Your games are safe.</p>
        <button
          className="button primary"
          onClick={() => window.location.reload()}
        >
          Refresh the playground
        </button>
      </div>
    ) : (
      this.props.children
    );
  }
}
function App() {
  const cats = useData("/api/categories"),
    settings = useData("/api/settings");
  const [toast, setToast] = useState("");
  useEffect(() => {
    if (toast) {
      const t = setTimeout(() => setToast(""), 5000);
      return () => clearTimeout(t);
    }
  }, [toast]);
  return (
    <AppContext.Provider
      value={{
        categories: cats.data || [],
        settings: settings.data || {},
        refresh: () => {
          cats.reload();
          settings.reload();
        },
        notify: setToast,
      }}
    >
      <BrowserRouter>
        <ScrollReset />
        <a className="skip-link" href="#main-content">
          Skip to content
        </a>
        <div id="main-content">
          <Routes>
            <Route element={<PublicLayout />}>
              <Route index element={<Home />} />
              <Route path="games" element={<GamesPage />} />
              <Route path="vlog" element={<VlogPage />} />
              <Route path="vlog/:slug" element={<VideoPage />} />
              <Route path="kids" element={<KidsPage />} />
              <Route path="kids/games/:slug" element={<KidsGamePage />} />
              <Route path="search" element={<SearchPage />} />
              <Route path="games/:slug" element={<GamePage />} />
              <Route path="categories/:slug" element={<CategoryPage />} />
              <Route path="recently-played" element={<RecentPage />} />
              <Route
                path="*"
                element={
                  <main className="public-main">
                    <Empty
                      title="You’ve wandered off the playground"
                      text="Let’s find you something fun instead."
                      action={
                        <Link to="/games" className="button primary">
                          Back to games
                        </Link>
                      }
                    />
                  </main>
                }
              />
            </Route>
            <Route path="admin" element={<AdminLayout />}>
              <Route index element={<Dashboard />} />
              <Route path="games" element={<ManageGames />} />
              <Route path="games/new" element={<GameForm />} />
              <Route path="games/:id/edit" element={<GameForm />} />
              <Route path="categories" element={<CategoryManager />} />
              <Route path="settings" element={<AdminSettings />} />
              <Route path="videos" element={<VideoManager />} />
              <Route path="videos/new" element={<VideoForm />} />
              <Route path="videos/:id/edit" element={<VideoForm />} />
              <Route
                path="*"
                element={
                  <Empty
                    title="Page not found"
                    text="Choose a page from the workspace navigation."
                  />
                }
              />
            </Route>
          </Routes>
        </div>
        {toast && (
          <div className="toast" role="status">
            <CheckCircle2 size={19} />
            <span>{toast}</span>
            <button
              className="icon-button"
              onClick={() => setToast("")}
              aria-label="Dismiss message"
            >
              <X size={15} />
            </button>
          </div>
        )}
      </BrowserRouter>
    </AppContext.Provider>
  );
}
createRoot(document.getElementById("root")!).render(
  <ErrorBoundary>
    <App />
  </ErrorBoundary>,
);
