import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import { reloadForStaleChunk } from './utils/lazyWithRetry'

// Initialize CSS optimizations immediately to reduce render blocking
import('./utils/cssLoader.ts').then((cssLoader) => {
  cssLoader.initializeCSSOptimizations();
});

// Initialize main thread optimizations ASAP
const initMainThreadOptimizations = () => {
  requestIdleCallback(() => {
    import('./utils/mainThreadOptimizer').then((optimizer) => {
      optimizer.initializeMainThreadOptimizations();
    });
  }, { timeout: 1000 });
};

// Defer non-critical imports with progressive loading and yielding
const deferredImports = () => {
  // Use more aggressive yielding strategy
  const scheduleTask = (fn: () => void, delay: number) => {
    if ('scheduler' in window && 'yield' in (window.scheduler as any)) {
      (window.scheduler as any).yield().then(() => setTimeout(fn, delay));
    } else {
      requestIdleCallback(() => setTimeout(fn, delay), { timeout: 10000 });
    }
  };

  // Load cache optimization first - deferred even more aggressively for TTI
  scheduleTask(() => {
    import('./utils/cacheOptimization.ts').then((cacheOpt) => {
      requestIdleCallback(() => cacheOpt.initializeCacheOptimizations(), { timeout: 10000 });
    });
  }, 500);

  // Then storage cleanup
  scheduleTask(() => {
    import('./utils/browserStorageCleanup.ts').then((storageCleanup) => {
      requestIdleCallback(() => storageCleanup.initializeBrowserStorageCleanup(), { timeout: 10000 });
    });
  }, 1000);

  // Then version manager
  scheduleTask(() => {
    import('./utils/versionManager').then((versionMgr) => {
      requestIdleCallback(() => versionMgr.initializeVersionManagement(), { timeout: 10000 });
    });
  }, 1500);

  // Finally cleanup service
  scheduleTask(() => {
    import('./utils/remoteCleanupService').then((cleanupSvc) => {
      requestIdleCallback(() => cleanupSvc.initializeCleanupCommandListener(), { timeout: 10000 });
    });
  }, 2000);

  // Defer JS optimizations
  scheduleTask(() => {
    import('./utils/jsOptimization').then((jsOpt) => {
      requestIdleCallback(() => jsOpt.initializeJSOptimizations(), { timeout: 10000 });
    });
  }, 2500);
};

// A tab opened before a new deploy may request chunks that no longer exist: reload once to get the fresh build.
window.addEventListener('vite:preloadError', (event) => {
  if (reloadForStaleChunk()) event.preventDefault();
});

// Mount app immediately for stability
const root = document.getElementById("root");
if (root) {
  createRoot(root).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
}

// Defer non-critical initialization until after app is mounted
requestIdleCallback(() => {
  initMainThreadOptimizations();
  deferredImports();
}, { timeout: 3000 });

// Service worker can cause stale JS/CSS in preview, breaking Router/React Query contexts.
// Only register SW on the production custom domain.
const shouldRegisterSW = window.location.hostname === "globalitacademy.am" ||
  window.location.hostname.endsWith(".globalitacademy.am");

if ("serviceWorker" in navigator) {
  if (shouldRegisterSW) {
    requestIdleCallback(() => {
      navigator.serviceWorker
        .register("/sw.js", { updateViaCache: "none" })
        .then((registration) => {
          console.log("SW registered: ", registration);
        })
        .catch((registrationError) => {
          console.log("SW registration failed: ", registrationError);
        });
    }, { timeout: 20000 });
  } else {
    // Preview/staging: ensure no SW controls the page (prevents old bundles)
    void navigator.serviceWorker.getRegistrations().then(async (regs) => {
      await Promise.all(regs.map((r) => r.unregister()));
      if ("caches" in window) {
        const keys = await caches.keys();
        await Promise.all(keys.map((k) => caches.delete(k)));
      }
      // If a SW was controlling the page, a reload is needed to fetch fresh assets
      if (navigator.serviceWorker.controller) {
        window.location.reload();
      }
    });
  }
}
