import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import './i18n/rtl.css'
import App from './App.jsx'
import { AuthProvider } from './context/AuthContext.jsx'
import { ConfigProvider } from './context/ConfigContext.jsx'
import { LanguageProvider } from './i18n/index.jsx'
import { GlobalErrorBoundary } from './components/GlobalErrorBoundary.jsx'
import { isOAuthPopup, finishOAuthPopup } from './services/oauthPopup.js'
import { supabase } from './lib/supabaseClient'

/* The OAuth popup lands back here carrying the provider's tokens.
 *
 * It must NOT mount the app — booting a second copy of Taybex inside a 500px
 * window would run the intro, the schedulers and the data fetches for a window
 * that exists only to hand over a session. Read the session, tell the opener,
 * close.
 *
 * The opener picks the session up from shared storage, not from a message, so
 * nothing here has to succeed for sign-in to work — the close is a courtesy
 * and the ping just stops the opener waiting.
 */
if (isOAuthPopup()) {
  supabase.auth.getSession()
    .catch(() => {})
    .finally(finishOAuthPopup);
} else {

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <GlobalErrorBoundary>
      {/* Outermost of the three providers on purpose: auth screens, config
          errors and the boot sequence are all things a visitor reads, so the
          language has to be settled before any of them render. */}
      <LanguageProvider>
        <AuthProvider>
          <ConfigProvider>
            <App />
          </ConfigProvider>
        </AuthProvider>
      </LanguageProvider>
    </GlobalErrorBoundary>
  </React.StrictMode>,
);
}

