import React, { useEffect } from "react";
import { HashRouter as Router, Routes, Route } 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 App() {
  const { mode, toggleTheme } = useThemeMode();
  const theme = getTheme(mode);

  // Clean up any theme-related localStorage entries on initial load
  useEffect(() => {
    localStorage.removeItem("theme-mode");
  }, []);

  // Apply theme to document as early as possible
  useEffect(() => {
    // Apply theme class to document elements
    document.documentElement.setAttribute("data-theme", mode);
    document.documentElement.classList.remove("light-mode", "dark-mode");
    document.documentElement.classList.add(`${mode}-mode`);

    // Apply theme class to body
    document.body.classList.remove("light-mode", "dark-mode");
    document.body.classList.add(`${mode}-mode`);

    // Apply to root element as well
    const rootElement = document.getElementById("root");

    // Update meta theme-color for mobile browsers
    let metaThemeColor = document.querySelector("meta[name=theme-color]");
    if (!metaThemeColor) {
      metaThemeColor = document.createElement("meta");
      metaThemeColor.name = "theme-color";
      document.head.appendChild(metaThemeColor);
    }
  }, [mode]);

  return (
    <div
      className={`App ${mode}-mode`}
      style={{
        height: "100%",
        width: "100%",
        WebkitOverflowScrolling: "touch",
        overflow: "auto",
      }}
    >
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Router>
          <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;
