import { StrictMode, useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import "./index.css";
import Layout from "./components/Layout";
import Home from "./pages/Home";
import ApartmentPage from "./pages/ApartmentPage";
import NotFound from "./pages/NotFound";
import { LangContext, detectBrowserLang } from "./i18n";
import { ThemeContext, detectSystemTheme } from "./useTheme";
import type { Lang } from "./translations";
import type { Theme } from "./useTheme";

function getStoredLang(): Lang | null {
  try {
    const stored = localStorage.getItem("villa-toscana-lang");
    if (stored === "de" || stored === "en" || stored === "hr" || stored === "fr" || stored === "ru") {
      return stored;
    }
  } catch {
    return null;
  }
  return null;
}

function getStoredTheme(): Theme | null {
  try {
    const stored = localStorage.getItem("villa-toscana-theme");
    if (stored === "light" || stored === "dark") return stored;
  } catch {
    return null;
  }
  return null;
}

function App() {
  const [lang, setLang] = useState<Lang>(getStoredLang() ?? detectBrowserLang());
  const [theme, setTheme] = useState<Theme>(getStoredTheme() ?? detectSystemTheme());

  useEffect(() => {
    document.documentElement.classList.toggle("dark", theme === "dark");
    document.documentElement.lang = lang;
    localStorage.setItem("villa-toscana-theme", theme);
    localStorage.setItem("villa-toscana-lang", lang);
  }, [theme, lang]);

  useEffect(() => {
    document.documentElement.lang = lang;
    localStorage.setItem("villa-toscana-lang", lang);
  }, [lang]);

  const toggleTheme = () =>
    setTheme((t) => (t === "dark" ? "light" : "dark"));

  return (
    <LangContext.Provider value={{ lang, setLang }}>
      <ThemeContext.Provider value={{ theme, toggleTheme }}>
        <BrowserRouter>
          <Routes>
            <Route element={<Layout />}>
              <Route path="/" element={<Home />} />
              <Route path="/:id" element={<ApartmentPage />} />
              <Route path="*" element={<NotFound />} />
            </Route>
          </Routes>
        </BrowserRouter>
      </ThemeContext.Provider>
    </LangContext.Provider>
  );
}

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>
);
