import { StrictMode, useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from '@tanstack/react-router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ipcLink } from './lib/ipcLink';
import { router } from './router';
import { trpc } from './lib/trpc';
import { ThemeProvider } from './components/theme-provider';
import { PlatformProvider, electronPlatform } from './lib/platform';
import { Toaster } from '@/components/ui/sonner';
import i18n from './i18n';
import './globals.css';

function App() {
  const [queryClient] = useState(() => new QueryClient());
  const [trpcClient] = useState(() =>
    trpc.createClient({
      links: [ipcLink()],
    }),
  );

function LanguageSync() {
  const { data: lang } = trpc.settings.getUiLanguage.useQuery(undefined, { staleTime: Infinity });
  useEffect(() => {
    if (lang && lang !== i18n.language) {
      void i18n.changeLanguage(lang);
    }
  }, [lang]);
  return null;
}

  return (
    <PlatformProvider value={electronPlatform}>
      <ThemeProvider defaultTheme="system" storageKey="adiuvai-theme">
        <trpc.Provider client={trpcClient} queryClient={queryClient}>
          <QueryClientProvider client={queryClient}>
            <LanguageSync />
            <RouterProvider router={router} />
            <Toaster />
          </QueryClientProvider>
        </trpc.Provider>
      </ThemeProvider>
    </PlatformProvider>
  );
}

const rootElement = document.getElementById('root');
if (!rootElement) throw new Error('Root element not found');

createRoot(rootElement).render(
  <StrictMode>
    <App />
  </StrictMode>,
);
