import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { createAdminApi } from './api'
import { App } from './App'
import { createSupabaseAuth } from './auth'
import { createStubAdminApi, createStubAuth } from './stub'
import './styles.css'

/**
 * Real wiring by default; `VITE_ADMIN_STUB=1` runs the whole portal on the
 * in-memory stub (dev/e2e — zero network). Constructed ONCE here, outside
 * render (the #74 lesson: a default-param platform re-fires boot forever).
 *
 * The anon key is public-by-design; ADMIN_EMAILS enforcement is server-side
 * and Cloudflare Access fronts the domain. Nothing privileged is baked.
 */
const env = import.meta.env
const useStub = env.VITE_ADMIN_STUB === '1' || !env.VITE_SUPABASE_ANON_KEY

const auth = useStub
  ? createStubAuth()
  : createSupabaseAuth(env.VITE_SUPABASE_URL ?? 'https://lazjlofcnmzrjzyfgecp.supabase.co', env.VITE_SUPABASE_ANON_KEY)

const api = useStub
  ? createStubAdminApi()
  : createAdminApi(env.VITE_ADMIN_API_URL ?? 'https://api-staging.beady.nz', () => auth.token())

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App auth={auth} api={api} />
  </StrictMode>
)
