import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { KindeProvider } from '@kinde-oss/kinde-auth-react'
import App from './App'
import './styles.css'
import { t } from './lib/i18n'

const domain = import.meta.env.VITE_KINDE_DOMAIN
const clientId = import.meta.env.VITE_KINDE_CLIENT_ID
const redirectUri = import.meta.env.VITE_KINDE_REDIRECT_URI ?? window.location.origin
const logoutUri = import.meta.env.VITE_KINDE_LOGOUT_URI ?? window.location.origin

/**
 * A missing client id is a configuration mistake, and the symptom without this
 * check is a blank page and a console error nobody reads. Say it out loud.
 */
function ConfigError({ missing }: { missing: string[] }) {
  return (
    <main className="shell">
      <div className="card error-card">
        <h1>{t.configMissingTitle}</h1>
        <p>{t.configMissingBody}</p>
        <ul>{missing.map((key) => <li key={key}><code>{key}</code></li>)}</ul>
        <p className="muted">{t.configMissingHint}</p>
      </div>
    </main>
  )
}

const missing = [
  !domain && 'VITE_KINDE_DOMAIN',
  !clientId && 'VITE_KINDE_CLIENT_ID',
].filter(Boolean) as string[]

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    {missing.length > 0 ? (
      <ConfigError missing={missing} />
    ) : (
      <KindeProvider
        domain={domain}
        clientId={clientId}
        redirectUri={redirectUri}
        logoutUri={logoutUri}
        // Matches the Flutter app, which is the client this backend is known to
        // accept. `offline` is what gets a refresh token, without which the
        // session dies on the first silent renewal; the rest are what put the
        // identity claims in the token. Left to the SDK default these differ,
        // and the symptom is a 401 the backend cannot explain.
        scope="openid profile email offline"
      >
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </KindeProvider>
    )}
  </React.StrictMode>,
)
