import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

declare const __APP_BUILD_ID__: string | undefined;

const AUTO_RELOAD_STORAGE_KEY = 'cuet_edge_reloaded_version';
const AUTO_RELOAD_AT_KEY = 'cuet_edge_last_reload_at';
const MIN_CHECK_GAP_MS = 5_000;
const POLL_INTERVAL_MS = 15_000;
const MIN_RELOAD_COOLDOWN_MS = 20_000;

async function cleanupDevServiceWorkers() {
  if (!import.meta.env.DEV || typeof navigator === 'undefined') return;
  try {
    if ('serviceWorker' in navigator) {
      const regs = await navigator.serviceWorker.getRegistrations();
      await Promise.all(regs.map((r) => r.unregister()));
    }
    if ('caches' in window) {
      const keys = await caches.keys();
      await Promise.all(
        keys
          .filter((k) => k.includes('workbox') || k.includes('vite-pwa') || k.includes('precache'))
          .map((k) => caches.delete(k))
      );
    }
  } catch {
    // ignore cleanup failures
  }
}

async function clearStaleAppCachesAndServiceWorkers() {
  try {
    if ('serviceWorker' in navigator) {
      const regs = await navigator.serviceWorker.getRegistrations();
      await Promise.all(
        regs.map(async (r) => {
          try {
            if (r.waiting) {
              r.waiting.postMessage({ type: 'SKIP_WAITING' });
            }
            await r.update().catch(() => {});
          } catch {
            // ignore SW update error
          }
        })
      );
    }
    if ('caches' in window) {
      const keys = await caches.keys();
      await Promise.all(
        keys
          .filter((k) => k.includes('workbox') || k.includes('vite-pwa') || k.includes('precache'))
          .map((k) => caches.delete(k))
      );
    }
  } catch {
    // ignore cleanup errors
  }
}

function setupAutoUpdateWatcher() {
  if (typeof window === 'undefined') return;
  const win = window as unknown as { __cuetAutoUpdateInstalled?: boolean };
  if (win.__cuetAutoUpdateInstalled) return;
  win.__cuetAutoUpdateInstalled = true;

  let baselineVersion: string | null = null;
  let pendingUpdateVersion: string | null = null;
  let reloading = false;
  let checking = false;
  let lastCheckedAt = 0;

  const isActiveLiveExamRoute = () => {
    const { pathname, search } = window.location;
    return pathname.includes('/exam') && !search.includes('mode=review');
  };

  const performSilentUpdate = (nextVersion: string) => {
    if (reloading) return;
    if (isActiveLiveExamRoute()) {
      pendingUpdateVersion = nextVersion;
      return;
    }
    try {
      if (sessionStorage.getItem(AUTO_RELOAD_STORAGE_KEY) === nextVersion) {
        return;
      }
      const lastReloadAt = Number(sessionStorage.getItem(AUTO_RELOAD_AT_KEY) || '0');
      if (lastReloadAt > 0 && Date.now() - lastReloadAt < MIN_RELOAD_COOLDOWN_MS) {
        return;
      }
      sessionStorage.setItem(AUTO_RELOAD_STORAGE_KEY, nextVersion);
      sessionStorage.setItem(AUTO_RELOAD_AT_KEY, String(Date.now()));
    } catch {
      // ignore storage errors
    }

    reloading = true;
    pendingUpdateVersion = null;
    void clearStaleAppCachesAndServiceWorkers().finally(() => {
      window.location.replace(window.location.href);
    });
  };

  const tryFlushPendingUpdate = () => {
    if (pendingUpdateVersion && !isActiveLiveExamRoute()) {
      performSilentUpdate(pendingUpdateVersion);
    }
  };

  const checkVersion = async (force = false) => {
    if (reloading) return;
    if (pendingUpdateVersion && !isActiveLiveExamRoute()) {
      performSilentUpdate(pendingUpdateVersion);
      return;
    }
    if (checking) return;
    const now = Date.now();
    if (!force && now - lastCheckedAt < MIN_CHECK_GAP_MS) return;

    checking = true;
    lastCheckedAt = now;
    try {
      const res = await fetch(`/api/app-version?_t=${now}`, {
        cache: 'no-store',
        headers: { 'Cache-Control': 'no-cache' },
      });
      if (!res.ok) return;
      const data = (await res.json()) as { version?: string };
      const remoteVersion = data?.version;
      if (!remoteVersion) return;

      // Instant mismatch check in production: bundle baked SHA vs latest deployed server SHA
      const compiledId = typeof __APP_BUILD_ID__ === 'string' ? __APP_BUILD_ID__ : '';
      if (
        !import.meta.env.DEV &&
        compiledId &&
        remoteVersion.startsWith('deploy-') &&
        remoteVersion !== `deploy-${compiledId}`
      ) {
        performSilentUpdate(remoteVersion);
        return;
      }

      if (!baselineVersion) {
        baselineVersion = remoteVersion;
        return;
      }

      if (remoteVersion !== baselineVersion) {
        performSilentUpdate(remoteVersion);
      }
    } catch {
      // ignore offline or transient errors
    } finally {
      checking = false;
    }
  };

  // Service Worker live update hooks in production
  if (!import.meta.env.DEV && 'serviceWorker' in navigator) {
    let hadController = Boolean(navigator.serviceWorker.controller);
    const onControllerChange = () => {
      if (hadController) {
        performSilentUpdate(`sw-${Date.now()}`);
      } else {
        hadController = true;
      }
    };
    navigator.serviceWorker.addEventListener('controllerchange', onControllerChange);
    void navigator.serviceWorker.getRegistrations().then((regs) => {
      for (const reg of regs) {
        reg.addEventListener('updatefound', () => {
          const installing = reg.installing;
          if (!installing) return;
          installing.addEventListener('statechange', () => {
            if (installing.state === 'installed' && navigator.serviceWorker.controller) {
              installing.postMessage({ type: 'SKIP_WAITING' });
              performSilentUpdate(`sw-${Date.now()}`);
            }
          });
        });
        void reg.update().catch(() => {});
      }
    });
  }

  // Automatic recovery if lazy-loaded JS/CSS chunks became stale after a fresh deploy
  const onPreloadError = (event: Event) => {
    event.preventDefault();
    performSilentUpdate(`chunk-${Date.now()}`);
  };
  const onUnhandledRejection = (event: PromiseRejectionEvent) => {
    const msg = String(
      (event.reason as { message?: string } | null)?.message || event.reason || ''
    );
    if (
      msg.includes('Failed to fetch dynamically imported module') ||
      msg.includes('Importing a module script failed') ||
      msg.includes('Loading chunk') ||
      msg.includes('Unable to preload CSS')
    ) {
      performSilentUpdate(`chunk-${Date.now()}`);
    }
  };

  window.addEventListener('vite:preloadError', onPreloadError);
  window.addEventListener('unhandledrejection', onUnhandledRejection);

  const startupTimer = window.setTimeout(() => {
    void checkVersion(true);
  }, 400);

  const intervalId = window.setInterval(() => {
    tryFlushPendingUpdate();
    if (document.visibilityState === 'visible') {
      void checkVersion(false);
    }
  }, POLL_INTERVAL_MS);

  const onVisibilityOrFocus = () => {
    tryFlushPendingUpdate();
    if (document.visibilityState === 'visible') {
      void checkVersion(false);
    }
  };
  const onRouteChange = () => {
    tryFlushPendingUpdate();
  };

  document.addEventListener('visibilitychange', onVisibilityOrFocus);
  window.addEventListener('focus', onVisibilityOrFocus);
  window.addEventListener('online', onVisibilityOrFocus);
  window.addEventListener('popstate', onRouteChange);

  if (import.meta.hot) {
    import.meta.hot.on('vite:beforeFullReload', () => {
      window.clearTimeout(startupTimer);
      window.clearInterval(intervalId);
      document.removeEventListener('visibilitychange', onVisibilityOrFocus);
      window.removeEventListener('focus', onVisibilityOrFocus);
      window.removeEventListener('online', onVisibilityOrFocus);
      window.removeEventListener('popstate', onRouteChange);
      window.removeEventListener('vite:preloadError', onPreloadError);
      window.removeEventListener('unhandledrejection', onUnhandledRejection);
      win.__cuetAutoUpdateInstalled = false;
    });
  }
}

void cleanupDevServiceWorkers();
setupAutoUpdateWatcher();

createRoot(document.getElementById('root')!).render(<App />);
