import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { loadRuntimeConfig } from './lib/config.ts';
import { installAuthGuard } from './lib/auth-guard.ts';

// Install auth guard BEFORE the web-sdk registers its own message listeners,
// so we can intercept and swallow `mgx-token-saved` events coming from the
// parent Atoms frame that would otherwise overwrite our standalone JWT and
// bounce the user to the Atoms OIDC login.
installAuthGuard();

/**
 * Purge every persistent client-side cache as soon as the app boots.
 *
 * Why: the Atoms platform proxy occasionally serves stale 503 HTML for
 * `/api/v1/whmcs/*` during backend cold-starts. If a Service Worker
 * or the browser's Cache Storage has cached that HTML, the user keeps
 * seeing "Temporarily Unavailable" long after the backend is healthy.
 *
 * This wipes:
 *   1. Every registered Service Worker.
 *   2. Every entry in window.caches.* (CacheStorage API).
 *
 * We swallow all errors — a cache purge failure must never block boot.
 */
async function disableClientSideCaches(): Promise<void> {
  try {
    if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {
      const regs = await navigator.serviceWorker.getRegistrations();
      await Promise.all(regs.map((r) => r.unregister().catch(() => false)));
    }
  } catch {
    /* noop */
  }
  try {
    if (typeof window !== 'undefined' && 'caches' in window) {
      const keys = await window.caches.keys();
      await Promise.all(keys.map((k) => window.caches.delete(k).catch(() => false)));
    }
  } catch {
    /* noop */
  }
}

// Load runtime configuration before rendering the app
async function initializeApp() {
  // Prerendered blog pages are served as pure static HTML for SEO.
  // Intentionally skip React mounting so the crawler-facing markup stays
  // lightweight and self-contained — no client-side hydration needed.
  if (
    document
      .querySelector('meta[name="prerender-static-page"]')
      ?.getAttribute('content') === 'blog'
  ) {
    return;
  }

  // Fire-and-forget cache purge — do this before first render so no stale
  // Service Worker intercepts upcoming WHMCS API calls.
  await disableClientSideCaches();

  try {
    await loadRuntimeConfig();
    console.log('Runtime configuration loaded successfully');
  } catch (error) {
    console.warn(
      'Failed to load runtime configuration, using defaults:',
      error
    );
  }

  // Render the app
  createRoot(document.getElementById('root')!).render(<App />);
}

// Initialize the app
initializeApp();
