import { BrowserRouter } from 'react-router-dom';
import { useMemo } from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { useTLDraw } from './contexts/TLDrawContext';
import { theme } from './services/themeService';
import { AuthProvider } from './contexts/AuthContext';
import { TLDrawProvider } from './contexts/TLDrawContext';
import { UserProvider } from './contexts/UserContext';
import AppRoutes from './AppRoutes';
import { ErrorBoundary } from './components/ErrorBoundary';
import React from 'react';

const App = React.memo(() => {
  const { tldrawPreferences } = useTLDraw();

  const prefersDarkMode =
    typeof window !== 'undefined' &&
    window.matchMedia('(prefers-color-scheme: dark)').matches;

  const appTheme = useMemo(() => {
    let mode: 'light' | 'dark';

    if (tldrawPreferences?.colorScheme === 'system') {
      mode = prefersDarkMode ? 'dark' : 'light';
    } else {
      mode = tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light';
    }

    return createTheme({
      palette: { mode },
    });
  }, [tldrawPreferences?.colorScheme, prefersDarkMode]);

  return (
    <ErrorBoundary>
      <BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
        <AuthProvider>
          <UserProvider>
            <TLDrawProvider>
              <ThemeProvider theme={appTheme}>
                <AppRoutes />
              </ThemeProvider>
            </TLDrawProvider>
          </UserProvider>
        </AuthProvider>
      </BrowserRouter>
    </ErrorBoundary>
  );
});

App.displayName = import.meta.env.VITE_APP_NAME;

export default App;
