import { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useParams } from 'react-router-dom';
import { LanguageProvider } from './contexts/LanguageContext';
import Header from './components/Header';
import Home from './components/Home';
import Footer from './components/Footer';
import Policies from './components/Policies';
import TravelMate from './components/TravelMate';
import EraseData from './components/TravelMate/EraseData';
import ScrollToTop from './components/ScrollToTop';
import './styles/main.scss';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Navigate to="/fr" replace />} />
        <Route path="/:lang/*" element={
          <LanguageProvider>
            <AppContent />
          </LanguageProvider>
        } />
      </Routes>
    </BrowserRouter>
  );
}

function AppContent() {
  const [darkMode, setDarkMode] = useState(false);
  const useParamsLang = useParams();

  // Sync URL language with context if needed, or validate it
  useEffect(() => {
    // Optional: Check if useParamsLang.lang is valid, else redirect
  }, [useParamsLang]);

  useEffect(() => {
    const savedTheme = localStorage.getItem('darkMode');
    if (savedTheme) {
      setDarkMode(JSON.parse(savedTheme));
    } else {
      setDarkMode(window.matchMedia('(prefers-color-scheme: dark)').matches);
    }
  }, []);

  useEffect(() => {
    localStorage.setItem('darkMode', JSON.stringify(darkMode));
    document.documentElement.setAttribute('data-theme', darkMode ? 'dark' : 'light');
  }, [darkMode]);

  const toggleDarkMode = () => {
    setDarkMode(!darkMode);
  };

  return (
    <>
      <ScrollToTop />
      <div className={`app ${darkMode ? 'dark' : 'light'}`} style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
        <Header darkMode={darkMode} toggleDarkMode={toggleDarkMode} />
        <main style={{ flex: 1 }}>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/travelmate" element={<TravelMate />} >
              <Route path="policies" element={<Policies />} />
            </Route>
            <Route path="/travelmate/erasedata" element={<EraseData />} />
            <Route path="/policies" element={<Policies />} />
          </Routes>
        </main>
        <Footer />
      </div>
    </>
  );
}

export default App;
