import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, HashRouter } from 'react-router-dom';
import { App } from '@/App';
import { ThemeProvider } from '@/lib/theme';
import { ProgressProvider } from '@/lib/progress';
import { AccountProvider } from '@/lib/account';
import { StagingBanner } from '@/components/StagingBanner';
import { migrateLegacyStorageKeys } from '@/lib/storage';
import { registerServiceWorker } from '@/lib/offline';
import '@/styles/base.css';
import '@/styles/components.css';

/**
 * STATIC mode is for hosting the built app somewhere that cannot rewrite unknown
 * paths to index.html (a preview host, a plain file server). It uses hash routes
 * so every link resolves without server support, and skips the service worker,
 * which would otherwise persist on a shared origin after the preview is gone.
 */
// Before any provider reads a key. Carries theme, progress, an in-flight
// review draft and the admin credential across the rename from the former
// brand's storage prefix. src/lib/storage.ts holds that prefix -- the only place
// it is spelled -- and explains why the migration copies rather than moves.
migrateLegacyStorageKeys();

const STATIC_HOST = import.meta.env.VITE_STATIC_HOST === 'true';
const Router = STATIC_HOST ? HashRouter : BrowserRouter;

if (!STATIC_HOST) registerServiceWorker();

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ThemeProvider>
      <ProgressProvider>
        <Router {...(STATIC_HOST ? {} : { basename: import.meta.env.BASE_URL })}>
          {/*
            Inside the router, because the account screens navigate. The
            provider reports "not configured" and gates nothing when no backend
            is set, so a build without one behaves exactly as it did before.
          */}
          <AccountProvider>
            {/* Above everything, so it is seen before anything is trusted. */}
            <StagingBanner />
            <App />
          </AccountProvider>
        </Router>
      </ProgressProvider>
    </ThemeProvider>
  </StrictMode>,
);
