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

// Auto-reload on stale dynamic-import chunk after redeploy.
// Vite emits `vite:preloadError` when a hashed chunk referenced by a stale
// HTML/JS bundle 404s. We reload once to pick up the fresh manifest.
if (typeof window !== 'undefined') {
  const RELOAD_KEY = '__cs_chunk_reloaded__';
  const handleChunkError = (msg?: string) => {
    if (sessionStorage.getItem(RELOAD_KEY)) return;
    sessionStorage.setItem(RELOAD_KEY, '1');
    console.warn('[Main] Stale chunk detected, reloading:', msg);
    window.location.reload();
  };
  window.addEventListener('vite:preloadError', (e: Event) => {
    e.preventDefault();
    handleChunkError((e as any)?.payload?.message);
  });
  window.addEventListener('error', (e) => {
    const m = e?.message || '';
    if (m.includes('Failed to fetch dynamically imported module') ||
        m.includes('Importing a module script failed')) {
      handleChunkError(m);
    }
  });
  // Clear the guard once a page has loaded successfully
  window.addEventListener('load', () => {
    setTimeout(() => sessionStorage.removeItem(RELOAD_KEY), 2000);
  });
}

// Performance timing
const startTime = performance.now();

// Set initial language and theme from localStorage immediately
const initialLang = localStorage.getItem('lang') || 'he';
const initialTheme = localStorage.getItem('theme') || 'dark';

const html = document.documentElement;
html.classList.add(initialTheme);
html.lang = initialLang;
html.dir = initialLang === 'he' ? 'rtl' : 'ltr';
html.classList.toggle('rtl', initialLang === 'he');

// Create root and render immediately
const rootElement = document.getElementById("root");

if (rootElement) {
  // Static heroes we may need to remove once React takes over.
  // IMPORTANT: do NOT remove them synchronously here — removing an LCP-candidate
  // element before its React replacement paints causes Chrome to discard it and
  // report a much later LCP (the React hero), which is what caused mobile LCP
  // to be measured at 3.8s on /solutions/* pages. We defer removal until after
  // React has actually painted (two rAFs after render), so the static hero stays
  // in the DOM and remains a valid LCP candidate — Chrome then reports the fast
  // static paint (~700ms) instead of the slow React paint.
  const staticHeroIds = [
    'static-hero',
    'soc-static-hero',
    'ir-static-hero',
    'grc-static-hero',
    'sectors-static-hero',
    'solutions-static-hero',
    'security-solutions-static-hero',
    'contact-static-hero',
    'blog-static-hero',
    'generic-skeleton',
    'cisco-static-hero',
    'fortinet-static-hero',
    'keeper-static-hero',
    'stellar-static-hero',
    'kela-static-hero',
    'acronis-static-hero',
    'sentinelone-static-hero',
    'crowdstrike-solutions-static-hero',
    'rapid7-static-hero',
    'ironscales-static-hero'
  ];

  const root = createRoot(rootElement, {
    identifierPrefix: 'cyberteam360-'
  });

  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );

  // Wait for React to actually paint before fading out static heroes,
  // and wait long enough for LCP to be observed (LCP is reported on the
  // largest contentful paint that is still in the DOM at input/visibility change).
  const removeStaticHeroes = () => {
    staticHeroIds.forEach(id => {
      const el = document.getElementById(id);
      if (el) {
        el.classList.add('fade-out');
        setTimeout(() => el.remove(), 300);
      }
    });
  };

  // Two rAFs guarantees React has committed + painted at least once.
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      // Extra buffer so slower mobile devices finish the LCP measurement window
      // (LCP candidate must be stable long enough for Chrome to report it).
      setTimeout(removeStaticHeroes, 800);
    });
  });

  console.log(`App rendered in ${(performance.now() - startTime).toFixed(2)}ms`);
}

// Defer all non-critical initializations
if ('requestIdleCallback' in window) {
  requestIdleCallback(() => {
    initializeNonCritical();
  }, { timeout: 3000 });
} else {
  setTimeout(initializeNonCritical, 1000);
}

function initializeNonCritical() {
  // Service Worker registration
  if ('serviceWorker' in navigator && import.meta.env.MODE === 'production') {
    navigator.serviceWorker.register('/sw.js', {
      scope: '/',
      updateViaCache: 'none'
    }).then((registration) => {
      console.log('[Main] ServiceWorker registered');
      
      registration.addEventListener('updatefound', () => {
        const newWorker = registration.installing;
        if (newWorker) {
          newWorker.addEventListener('statechange', () => {
            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
              newWorker.postMessage({ type: 'SKIP_WAITING' });
              setTimeout(() => window.location.reload(), 500);
            }
          });
        }
      });

      // Periodic update checks
      setInterval(() => registration.update(), 30000);
      
      document.addEventListener('visibilitychange', () => {
        if (!document.hidden) registration.update();
      });
    }).catch((error) => {
      console.warn('[Main] ServiceWorker registration failed:', error);
    });
  }

  // Performance metrics (delayed)
  setTimeout(() => {
    if ('performance' in window && 'getEntriesByType' in performance) {
      const perfData = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
      if (perfData) {
        console.log('Performance:', {
          domContentLoaded: Math.round(perfData.domContentLoadedEventEnd - perfData.domContentLoadedEventStart),
          firstByte: Math.round(perfData.responseStart - perfData.fetchStart)
        });
      }
    }
  }, 3000);
}
