import {QueryClient, QueryClientProvider} from '@tanstack/react-query';
import {createRoot} from 'react-dom/client';
import {BrowserRouter} from 'react-router-dom';
import {Toaster} from 'sonner';
import {UserProvider} from '@/contexts';
import {ThemeProvider} from '@/contexts/theme-context';
import './index.css';
import App from './App.tsx';
import {applyPaletteToDOM, loadActivePresetId} from '@/components/room/design-system';

// Restore custom palette on page load (before first render)
const activePreset = loadActivePresetId();
if (activePreset === 'custom') {
    const customPalette = localStorage.getItem('theme-custom-palette');
    if (customPalette) {
        try {
            applyPaletteToDOM(JSON.parse(customPalette));
        } catch {
            // ignore malformed stored palette
        }
    }
}

const queryClient = new QueryClient();

createRoot(document.getElementById('root')!).render(
    <>
        <QueryClientProvider client={queryClient}>
            <BrowserRouter>
                <UserProvider>
                    <ThemeProvider>
                        <App/>
                        <Toaster richColors position="bottom-right"/>
                    </ThemeProvider>
                </UserProvider>
            </BrowserRouter>
        </QueryClientProvider>
    </>,
);
