import React from 'react'
import {createRoot} from 'react-dom/client'
import './style.css'
import App from './App'
import { syncPortablePrefs } from './lib/uiPref'
import { I18nProvider } from './lib/i18n'
import { ThemeProvider, initTheme } from './lib/theme'
import { ErrorBoundary, installGlobalErrorLogging } from './components/ErrorBoundary'
import { reloadDateFormat } from './lib/dateFormat'

const container = document.getElementById('root')

const root = createRoot(container!)

// Pull portable UI prefs (DB → localStorage) before the first render so the
// app's synchronous reads see the values copied along with the data/ folder.
// Render regardless of the outcome so a backend hiccup never blocks startup.
syncPortablePrefs().finally(() => {
    // Stamp the persisted theme onto <html> before render so the correct
    // palette is applied immediately (portable pref hydrated just above).
    initTheme()
    // The date format module read localStorage at import time, which is BEFORE
    // the portable prefs were pulled from the database. Re-read it now, or a
    // copied data/ folder would show ISO until the next launch.
    reloadDateFormat()
    // Catch what a boundary cannot: errors thrown from timers, event handlers and
    // rejected promises. Installed before the first render so a fault during
    // startup is reported too.
    installGlobalErrorLogging()
    root.render(
        <React.StrictMode>
            <ErrorBoundary>
                <I18nProvider>
                    <ThemeProvider>
                        <App/>
                    </ThemeProvider>
                </I18nProvider>
            </ErrorBoundary>
        </React.StrictMode>
    )
})
