import { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route, 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 Support from './components/TravelMate/Support';
import HomeSync from './components/HomeSync';
import HomeSyncPolicies from './components/HomeSyncPolicies';
import ScrollToTop from './components/ScrollToTop';
import RootRedirect from './components/RootRedirect';
import Login from './components/Login';
import VerifyAuthCode from './components/VerifyAuthCode';
import ProtectedRoute from './components/ProtectedRoute';
import ProfileSetup from './components/ProfileSetup';
import './styles/main.scss';
import { CookieProvider, useCookie } from './contexts/CookieContext';
import CookieBanner from './components/CookieBanner/CookieBanner';
import { AuthProvider } from './contexts/AuthContext';
import { initFirebaseAnalytics } from './lib/firebase';

function App() {
  return (
    <BrowserRouter>
      <CookieProvider>
        <Routes>
          <Route path="/" element={<RootRedirect />} />
          <Route path="/:lang/*" element={
            <AuthProvider>
              <LanguageProvider>
                <AppContent />
              </LanguageProvider>
            </AuthProvider>
          } />
        </Routes>
      </CookieProvider>
    </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]);

  const { consent } = useCookie();

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

  useEffect(() => {
    // Only save if preferences are allowed
    if (consent.preferences || consent.essential) {
      localStorage.setItem('darkMode', JSON.stringify(darkMode));
    }
    document.documentElement.setAttribute('data-theme', darkMode ? 'dark' : 'light');
  }, [darkMode, consent]);

  useEffect(() => {
    if (!consent.analytics) return;
    void initFirebaseAnalytics();
  }, [consent.analytics]);

  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="/travelmate/policies" element={<Policies />} />
            <Route path="/travelmate/erasedata" element={<ProtectedRoute><EraseData /></ProtectedRoute>} />
            <Route path="/homesync" element={<HomeSync />} />
            <Route path="/homesync/policies" element={<HomeSyncPolicies />} />
            <Route path="/policies" element={<Policies />} />
            <Route path="/travelmate/support" element={<ProtectedRoute><Support /></ProtectedRoute>} />
            <Route path="/login" element={<Login />} />
            <Route path="/verify-auth" element={<VerifyAuthCode />} />
            <Route path="/profile-setup" element={<ProfileSetup />} />
          </Routes>
        </main>
        <Footer />
        <CookieBanner />
      </div>
    </>
  );
}

export default App;
