import './lib/console-buffer';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import { seedAppRegistry, seedWidgetRegistry } from 'officerdev';
import { plugins } from './Plugins.gen';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ColorModeProvider } from '@/components/ui/ThemeProvider';
import { I18nBridge } from '@/lib/I18nBridge';
import { Toaster as Sonner } from 'sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
import './styles/index.css';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
    },
  },
});

// Before the first render, not from a component inside it: a panel that renders before its registry is
// populated draws an empty box, and `useGlobal`'s initialData gives no second chance to fill it.
// Panels contributed by installed plugins, from the generated module. See servers/plugins/generate.ts.
seedAppRegistry(
  queryClient,
  plugins.flatMap((p) => p.panels),
);
seedWidgetRegistry(queryClient);

const elem = document.getElementById('root')!;
const app = (
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <ColorModeProvider>
        <I18nBridge>
          <TooltipProvider>
            <Sonner position="top-center" toastOptions={{ style: { padding: '16px 20px', fontSize: '16px' } }} />
            <App />
          </TooltipProvider>
        </I18nBridge>
      </ColorModeProvider>
    </QueryClientProvider>
  </StrictMode>
);

if (import.meta.hot) {
  const root = (import.meta.hot.data.root ??= createRoot(elem));
  root.render(app);
} else {
  createRoot(elem).render(app);
}
