// Survey engine chooser. v1 and v2 are fully separate bootstraps — each owns
// its own Sentry init, analytics setup, GrowthBook attribute hydration, and
// React root render. Only one is loaded at runtime; the other tree-shakes out.
//
// Flip DEFAULT_ENGINE to roll the whole site between engines. For per-session
// QA overrides, set `localStorage.rise_survey_engine = 'v1' | 'v2'` in devtools.

type SurveyEngine = 'v1' | 'v2';

const DEFAULT_ENGINE: SurveyEngine = 'v1';

function resolveEngine(): SurveyEngine {
  try {
    const override = localStorage.getItem('rise_survey_engine');
    if (override === 'v1' || override === 'v2') return override;
  } catch {
    // localStorage unavailable (private mode, etc.) — fall back to default.
  }
  return DEFAULT_ENGINE;
}

const engine = resolveEngine();
console.log(`[Rise] Survey engine: ${engine}`);

// Recover from a failed entry-chunk fetch (stale HTML during deploy, CDN edge
// race, network blip). Reload exactly once per session; if the reload also
// fails, stop trying and let the failure surface so we don't loop. Matches
// the pre-archive behavior for v1/v2 lazy imports — the entries register their
// own equivalent handler for sub-chunks loaded after they boot.
const CHUNK_RELOAD_KEY = 'chunk_load_reload';
const handleEntryChunkError = (err: Error): never => {
  if (!sessionStorage.getItem(CHUNK_RELOAD_KEY)) {
    sessionStorage.setItem(CHUNK_RELOAD_KEY, 'true');
    window.location.reload();
  }
  throw err;
};

if (engine === 'v1') {
  import('./v1/entry').catch(handleEntryChunkError);
} else {
  import('./v2/src/entry').catch(handleEntryChunkError);
}
