import React, { useEffect } from "react";
import {
  HashRouter as Router,
  Routes,
  Route,
  useSearchParams,
  useLocation,
} from "react-router-dom";
import { ThemeProvider } from "@mui/material/styles";
import { Box, CssBaseline } from "@mui/material";
import Navigation from "./components/Navigation/Navigation";
import LeaderboardPage from "./pages/LeaderboardPage/LeaderboardPage";
import HowToSubmitPage from "./pages/HowToSubmitPage/HowToSubmitPage";
import Footer from "./components/Footer/Footer";
import getTheme from "./config/theme";
import { useThemeMode } from "./hooks/useThemeMode";

function UrlHandler() {
  const location = useLocation();
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const isHFSpace = window.location !== window.parent.location;
    if (!isHFSpace) return;

    const queryString = window.location.search;
    const hash = window.location.hash;

    window.parent.postMessage(
      {
        queryString,
        hash,
      },
      "https://huggingface.co"
    );
  }, [location, searchParams]);

  useEffect(() => {
    const handleHashChange = (event) => {
      console.log("hash change event", event);
    };

    window.addEventListener("hashchange", handleHashChange);
    return () => window.removeEventListener("hashchange", handleHashChange);
  }, []);

  return null;
}

function App() {
  const { mode, toggleTheme } = useThemeMode();
  const theme = getTheme(mode);

  return (
    <div
      className="App"
      style={{
        height: "100%",
        width: "100%",
        WebkitOverflowScrolling: "touch",
        overflow: "auto",
      }}
    >
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Router>
          <UrlHandler />
          <Box
            sx={{
              minHeight: "100vh",
              display: "flex",
              flexDirection: "column",
              bgcolor: "background.default",
              color: "text.primary",
            }}
          >
            <Navigation onToggleTheme={toggleTheme} mode={mode} />
            <Box
              sx={{
                flex: 1,
                display: "flex",
                flexDirection: "column",
                width: "100%",
                px: 4,
                pb: 4,
              }}
            >
              <Routes>
                <Route path="/" element={<LeaderboardPage />} />
                <Route path="/submit" element={<HowToSubmitPage />} />
              </Routes>
            </Box>
            <Footer />
          </Box>
        </Router>
      </ThemeProvider>
    </div>
  );
}

export default App;
