/**
 * Web SPA entry point.
 *
 * Identical to the Electron entry (index.tsx) but uses:
 * - httpBatchLink instead of ipcLink (HTTP to FastAPI backend)
 * - webPlatform instead of electronPlatform
 * - No LanguageSync via electron-store (reads from backend profile instead)
 */
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 { createHttpLink } from './lib/httpLink';
import { router } from './router';
import { trpc } from './lib/trpc';
import { ThemeProvider } from './components/theme-provider';
import { PlatformProvider, webPlatform } from './lib/platform';
import { Toaster } from '@/components/ui/sonner';
import i18n from './i18n';
import './globals.css';

function LanguageSync() {
  const { data: profile } = trpc.auth.status.useQuery(undefined, {
    staleTime: Infinity,
  });
  useEffect(() => {
    const lang = profile?.profile?.memory?.language as string | undefined;
    if (lang && lang !== i18n.language) {
      void i18n.changeLanguage(lang);
    }
  }, [profile]);
  return null;
}

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

  return (
    <PlatformProvider value={webPlatform}>
      <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>,
);
