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

// TypeScript declarations for performance tracking
declare global {
  interface Window {
    __PERF_START__?: number;
    gtag?: (...args: any[]) => void;
  }
}

// Preload critical modules
const criticalModules = [
  () => import('./components/Navigation.tsx'),
  () => import('./components/Calculator.tsx'),
  () => import('./components/ThemeProvider.tsx'),
  () => import('./components/SEOHead.tsx'),
  () => import('./components/LazyImage.tsx')
];

// Preload critical CSS and resources
const preloadResources = () => {
  // Preload critical fonts
  const fontLink = document.createElement('link');
  fontLink.rel = 'preload';
  fontLink.href = 'https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap';
  fontLink.as = 'style';
  fontLink.onload = () => {
    fontLink.rel = 'stylesheet';
  };
  document.head.appendChild(fontLink);
  
  // Preconnect to external domains
  const preconnectDomains = [
    'https://fonts.googleapis.com',
    'https://fonts.gstatic.com'
  ];
  
  preconnectDomains.forEach(domain => {
    const link = document.createElement('link');
    link.rel = 'preconnect';
    link.href = domain;
    if (domain.includes('gstatic')) {
      link.crossOrigin = 'anonymous';
    }
    document.head.appendChild(link);
  });
};

// Preload critical modules and resources in the background
if ('requestIdleCallback' in window) {
  window.requestIdleCallback(() => {
    preloadResources();
    criticalModules.forEach(moduleLoader => {
      moduleLoader().catch(() => {
        // Silently handle preload errors
      });
    });
  });
} else {
  // Fallback for browsers without requestIdleCallback
  setTimeout(() => {
    preloadResources();
    criticalModules.forEach(moduleLoader => {
      moduleLoader().catch(() => {
        // Silently handle preload errors
      });
    });
  }, 1);
}

// Initialize i18n asynchronously with performance monitoring
import('./i18n/config').then(() => {
  const root = createRoot(document.getElementById("root")!);
  
  // Mark DOM ready for performance tracking
  if (window.__PERF_START__) {
    const domReadyTime = performance.now() - window.__PERF_START__;
    console.log(`🚀 DOM Ready: ${domReadyTime.toFixed(2)}ms`);
  }
  
  root.render(
    <Suspense fallback={
      <div className="flex items-center justify-center min-h-screen bg-background">
        <div className="loading-spinner" />
        <span className="ml-2 text-sm text-muted-foreground">Loading Quick Subnet Calculator...</span>
      </div>
    }>
      <App />
    </Suspense>
  );
  
  // Performance metrics
  window.addEventListener('load', () => {
    if (window.__PERF_START__) {
      const totalLoadTime = performance.now() - window.__PERF_START__;
      console.log(`⚡ Total Load Time: ${totalLoadTime.toFixed(2)}ms`);
      
      // Report to analytics if available
      if (typeof window.gtag !== 'undefined') {
        window.gtag('event', 'page_load_time', {
          event_category: 'Performance',
          value: Math.round(totalLoadTime),
          custom_map: { load_time: totalLoadTime }
        });
      }
    }
  });
}).catch((error) => {
  console.error('Failed to load i18n:', error);
  // Fallback without i18n but with error boundary
  const root = createRoot(document.getElementById("root")!)
  
  try {
    root.render(
      <Suspense fallback={<div className="loading-spinner" />}>
        <App />
      </Suspense>
    );
  } catch (renderError) {
    // Last resort fallback
    const container = document.getElementById("root");
    if (container) {
      container.innerHTML = `
        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; text-align: center;">
          <h1 style="color: #dc2626; margin-bottom: 16px;">Application Error</h1>
          <p style="color: #6b7280; margin-bottom: 16px;">Subnet Calculator failed to load. Please refresh the page.</p>
          <button onclick="window.location.reload()" style="background: #3b82f6; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">
            Refresh Page
          </button>
        </div>
      `;
    }
    console.error('Critical render error:', renderError);
  }
});
