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

// ===== GLOBAL CHUNK LOADING ERROR HANDLER =====
// Nach einem Deploy können offene Tabs / der Service-Worker-Cache auf alte
// Asset-Hashes zeigen. Dann schlägt das Nachladen eines Chunks fehl oder es
// werden zwei React-Versionen gemischt ("dispatcher.useEffect is null").
// -> genau EIN harter Reload pro Session, danach nur noch loggen.
if (typeof window !== 'undefined') {
  const RELOAD_FLAG = 'sb_chunk_reload_at';
  const CACHE_SCHEMA_VERSION = 'wolf-silo-visibility-react-dedupe-2026-08-26';
  const CACHE_SCHEMA_KEY = 'sb_cache_schema_version';

  const isChunkError = (message: string): boolean => {
    return (
      message.includes('Loading chunk') ||
      message.includes('Failed to fetch dynamically imported module') ||
      message.includes('error loading dynamically imported module') ||
      message.includes('dynamically imported module') ||
      message.includes('Importing a module script failed') ||
      message.includes("dispatcher.useEffect") ||
      message.includes('Invalid hook call')
    );
  };

  const recoverOnce = (message: string) => {
    console.warn('[Global] Chunk/React-Mismatch erkannt:', message);
    let last = 0;
    try {
      last = Number(sessionStorage.getItem(RELOAD_FLAG) || 0);
    } catch {
      /* Storage nicht verfügbar */
    }
    // Reload-Schleifen verhindern: maximal einmal pro 60 Sekunden
    if (Date.now() - last < 60_000) return;
    try {
      sessionStorage.setItem(RELOAD_FLAG, String(Date.now()));
    } catch {
      /* ignore */
    }
    // Caches + Service Worker leeren, damit der neue Build wirklich geladen wird
    const cleanup = async () => {
      try {
        if ('caches' in window) {
          const keys = await caches.keys();
          await Promise.all(keys.map((k) => caches.delete(k)));
        }
        if ('serviceWorker' in navigator) {
          const regs = await navigator.serviceWorker.getRegistrations();
          await Promise.all(regs.map((r) => r.unregister()));
        }
      } catch {
        /* ignore */
      }
      window.location.reload();
    };
    void cleanup();
  };

  window.addEventListener('error', (event) => {
    const message = event.message || '';
    if (isChunkError(message)) recoverOnce(message);
  });

  window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason;
    const message = reason?.message || String(reason) || '';
    if (isChunkError(message)) recoverOnce(message);
  });

  const clearStaleAppShellCache = async () => {
    let current = '';
    try {
      current = localStorage.getItem(CACHE_SCHEMA_KEY) || '';
    } catch {
      return;
    }

    if (current === CACHE_SCHEMA_VERSION) return;

    try {
      if ('caches' in window) {
        const keys = await caches.keys();
        await Promise.all(keys.map((key) => caches.delete(key)));
      }
      if ('serviceWorker' in navigator) {
        const registrations = await navigator.serviceWorker.getRegistrations();
        await Promise.all(registrations.map((registration) => registration.unregister()));
      }
      localStorage.setItem(CACHE_SCHEMA_KEY, CACHE_SCHEMA_VERSION);
    } catch {
      /* ignore cache cleanup errors */
    }
  };

  void clearStaleAppShellCache();
}


// Use a simpler loading indicator that creates fewer DOM nodes
const OptimizedLoadingIndicator = () => (
  <div className="min-h-screen flex items-center justify-center">
    <div className="w-8 h-8 border-2 border-smartbase-pink rounded-full border-b-transparent animate-spin"></div>
  </div>
);

// Prioritize critical application loading
const prioritizeNavigation = () => {
  if (typeof window !== 'undefined') {
    // Add Google Fonts link for Inter instead of local font files
    const fontLink = document.createElement('link');
    fontLink.rel = 'preconnect';
    fontLink.href = 'https://fonts.googleapis.com';
    document.head.appendChild(fontLink);
    
    const fontDisplayLink = document.createElement('link');
    fontDisplayLink.rel = 'preconnect';
    fontDisplayLink.href = 'https://fonts.gstatic.com';
    fontDisplayLink.crossOrigin = 'anonymous';
    document.head.appendChild(fontDisplayLink);
    
    const fontStyleLink = document.createElement('link');
    fontStyleLink.rel = 'stylesheet';
    fontStyleLink.href = 'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap';
    document.head.appendChild(fontStyleLink);
  }
};

// Initialize performance tracking
if (!import.meta.env.SSR) {
  prioritizeNavigation();
  console.log('✅ Main initialization completed - Build:', import.meta.env.VITE_BUILD_ID || new Date().toISOString());

  if ('serviceWorker' in navigator && !import.meta.env.DEV) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.getRegistrations()
        .then((registrations) => {
          registrations.forEach((registration) => registration.update().catch(() => undefined));
        })
        .catch(() => undefined);
    });
  }
}

// Direct DOM access for faster initial rendering
const rootElement = document.getElementById('root');
if (!rootElement) throw new Error('Root element not found');

const root = createRoot(rootElement);

// Render with simplified setup - providers are now in App.tsx
root.render(
  import.meta.env.DEV ? (
    <StrictMode>
      <App />
    </StrictMode>
  ) : (
    <App />
  )
);

// App wurde erfolgreich gemountet -> Reload-Sperre wieder freigeben, damit ein
// späterer Chunk-Mismatch sofort erneut automatisch bereinigt werden kann.
if (typeof window !== 'undefined') {
  window.setTimeout(() => {
    try {
      sessionStorage.removeItem('sb_chunk_reload_at');
    } catch {
      /* ignore */
    }
  }, 5000);
}

