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

// Auto-recover from stale chunks / dynamic import 404s after rebuilds or server restarts
if (typeof window !== 'undefined') {
  window.addEventListener('vite:preloadError', (event) => {
    console.warn('[Vite] Preload error detected. Reloading page to fetch updated chunks...', event);
    window.location.reload();
  });

  window.addEventListener('error', (event) => {
    const message = event?.message || '';
    if (
      message.includes('Failed to fetch dynamically imported module') ||
      message.includes('Loading chunk') ||
      message.includes('chunk-')
    ) {
      const storageKey = 'app_chunk_reload_ts';
      const lastReload = Number(sessionStorage.getItem(storageKey) || '0');
      const now = Date.now();
      if (now - lastReload > 6000) {
        sessionStorage.setItem(storageKey, String(now));
        console.warn('[App] Dynamic chunk load failure. Auto-reloading to synchronize...', message);
        window.location.reload();
      }
    }
  });

  window.addEventListener('unhandledrejection', (event) => {
    const reason = event?.reason?.message || String(event?.reason || '');
    if (
      reason.includes('Failed to fetch dynamically imported module') ||
      reason.includes('Loading chunk') ||
      reason.includes('chunk-')
    ) {
      const storageKey = 'app_chunk_reload_ts';
      const lastReload = Number(sessionStorage.getItem(storageKey) || '0');
      const now = Date.now();
      if (now - lastReload > 6000) {
        sessionStorage.setItem(storageKey, String(now));
        console.warn('[App] Unhandled dynamic import rejection. Auto-reloading to synchronize...', reason);
        window.location.reload();
      }
    }
  });
}

initDisableTextSuggestions();

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

