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 = 'remove-stale-app-shell-2026-09-29';
  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 */
    }
    // Nur alte App-Shell-Caches entfernen. Fremde Worker-Caches (z. B. Push)
    // dürfen nicht pauschal gelöscht werden.
    const cleanup = async () => {
      try {
        if ('caches' in window) {
          const keys = await caches.keys();
          const appShellKeys = keys.filter(isLegacyAppShellCache);
          await Promise.all(appShellKeys.map((k) => caches.delete(k)));
        }
        if ('serviceWorker' in navigator) {
          const regs = await navigator.serviceWorker.getRegistrations();
          const appShellRegs = regs.filter(isLegacyAppShellRegistration);
          await Promise.all(appShellRegs.map((r) => r.unregister()));
        }
      } catch {
        /* ignore */
      }
      window.location.reload();
    };
    void cleanup();
  };

  const isLegacyAppShellCache = (name: string): boolean =>
    /(^|-)precache-v\d+-|(^|-)runtime-|(^|-)googleAnalytics-|^workbox-|^html-cache$|^aws-resources$|^map-tiles-cache$/.test(name);

  const isLegacyAppShellRegistration = (registration: ServiceWorkerRegistration): boolean => {
    const scriptUrl = registration.active?.scriptURL ?? registration.waiting?.scriptURL ?? registration.installing?.scriptURL ?? '';
    return scriptUrl.endsWith('/sw.js') || scriptUrl.endsWith('/service-worker.js');
  };

  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();
        const appShellKeys = keys.filter(isLegacyAppShellCache);
        await Promise.all(appShellKeys.map((key) => caches.delete(key)));
      }
      if ('serviceWorker' in navigator) {
        const registrations = await navigator.serviceWorker.getRegistrations();
        const appShellRegistrations = registrations.filter(isLegacyAppShellRegistration);
        await Promise.all(appShellRegistrations.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-primary 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());

}

// 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);
}

