import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
import { AppWrapper } from "./components/common/PageMeta.tsx";
import { initWebVitals } from "./utils/webVitals";
import { registerServiceWorker } from "./utils/serviceWorkerRegistration";

// MOBILE FIX: Add mobile detection
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

// SECURITY FIX: Only log diagnostic info in development
if (import.meta.env.DEV) {
  console.log('[STARTUP] BestSpaceFinder initializing...', {
    timestamp: new Date().toISOString(),
    userAgent: navigator.userAgent,
    connection: (navigator as any).connection?.effectiveType || 'unknown',
    isMobile,
    platform: navigator.platform,
    language: navigator.language,
  });
}

// MOBILE FIX: Initialize Web Vitals monitoring (production only)
if (import.meta.env.PROD) {
  try {
    initWebVitals();
    if (import.meta.env.DEV) {
      console.log('[STARTUP] ✅ Web Vitals initialized');
    }
  } catch (error) {
    if (import.meta.env.DEV) {
      console.error('[STARTUP] ❌ Web Vitals initialization failed:', error);
    }
  }
  
  // MOBILE FIX: Register service worker with better error handling
  registerServiceWorker()
    .then(() => {
      if (import.meta.env.DEV) {
        console.log('[STARTUP] ✅ Service worker registration complete');
      }
    })
    .catch((error) => {
      if (import.meta.env.DEV) {
        console.error('[STARTUP] ❌ Service worker registration failed:', error);
      }
      // Continue without service worker - don't block app
    });
}

// MOBILE FIX: Run diagnostics on mobile in development
if (isMobile && import.meta.env.DEV) {
  import('./utils/mobileDiagnostics').then(({ runMobileDiagnostics }) => {
    setTimeout(() => {
      runMobileDiagnostics().then((results) => {
        console.log('[MOBILE DIAGNOSTICS] Results:', results);
      });
    }, 3000);
  });
}

// Check critical environment variables
const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = import.meta.env.VITE_SUPABASE_ANON_KEY;

// SECURITY FIX: Only log environment details in development
if (import.meta.env.DEV) {
  console.log('[STARTUP] Environment check:', {
    supabaseUrl: SUPABASE_URL ? `${SUPABASE_URL.substring(0, 30)}...` : '❌ MISSING',
    anonKeyPresent: !!SUPABASE_ANON_KEY,
    anonKeyLength: SUPABASE_ANON_KEY?.length || 0,
    mode: import.meta.env.MODE,
    dev: import.meta.env.DEV,
    prod: import.meta.env.PROD,
  });
}

// Add loading timeout detector
let startupTimeout: ReturnType<typeof setTimeout> | null = null;

if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
  const missingVar = !SUPABASE_URL ? 'SUPABASE_URL' : 'SUPABASE_ANON_KEY';
  console.error(`[FATAL] ${missingVar} not set in environment variables`);
  
  // SECURITY FIX: Clear timeout before throwing
  if (startupTimeout) {
    clearTimeout(startupTimeout);
  }
  
  // SECURITY FIX: Render error UI safely without innerHTML injection
  const rootElement = document.getElementById("root");
  if (rootElement) {
    // Clear existing content
    rootElement.innerHTML = '';
    
    // Create elements safely
    const container = document.createElement('div');
    container.style.cssText = 'display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; font-family: system-ui, -apple-system, sans-serif; background: #f9fafb;';
    
    const card = document.createElement('div');
    card.style.cssText = 'max-width: 500px; text-align: center; background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);';
    
    const icon = document.createElement('div');
    icon.style.cssText = 'font-size: 48px; margin-bottom: 16px;';
    icon.textContent = '⚙️';
    
    const title = document.createElement('h1');
    title.style.cssText = 'color: #dc2626; margin-bottom: 16px; font-size: 24px; font-weight: 600;';
    title.textContent = 'Configuration Error';
    
    const message = document.createElement('p');
    message.style.cssText = 'color: #6b7280; margin-bottom: 24px; font-size: 16px; line-height: 1.5;';
    message.textContent = 'The application is not properly configured. Please contact support.';
    
    const errorDetail = document.createElement('p');
    errorDetail.style.cssText = 'font-size: 14px; color: #9ca3af; margin-bottom: 24px;';
    // SECURITY FIX: Use textContent instead of innerHTML
    errorDetail.textContent = `Error: ${missingVar} not set`;
    
    const button = document.createElement('button');
    button.style.cssText = 'padding: 12px 24px; background: #2563eb; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 500;';
    button.textContent = 'Retry';
    button.onclick = () => location.reload();
    
    card.appendChild(icon);
    card.appendChild(title);
    card.appendChild(message);
    card.appendChild(errorDetail);
    card.appendChild(button);
    container.appendChild(card);
    rootElement.appendChild(container);
  }
  
  // BUG FIX #1: Stop execution gracefully without throwing
  // Throwing here would propagate to outer catch and replace the error UI
  // Just use a type assertion to satisfy TypeScript's control flow analysis
  if (import.meta.env.DEV) {
    console.error(`[FATAL] Stopping execution due to missing ${missingVar}`);
  }
  // Exit early - don't continue to render the app
  (window as any).__APP_INIT_FAILED__ = true;
} else {
  if (import.meta.env.DEV) {
    console.log('[STARTUP] ✅ Environment variables validated');
  }
}

// Only continue if initialization succeeded
if (!(window as any).__APP_INIT_FAILED__) {

// Add global error handler
window.addEventListener('error', (event) => {
  if (import.meta.env.DEV) {
    console.error('[GLOBAL ERROR]', {
      message: event.message,
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
      error: event.error?.stack,
      timestamp: new Date().toISOString(),
    });
  }
});

window.addEventListener('unhandledrejection', (event) => {
  if (import.meta.env.DEV) {
    console.error('[UNHANDLED REJECTION]', {
      reason: event.reason,
      promise: event.promise,
      timestamp: new Date().toISOString(),
    });
  }
});

if (import.meta.env.DEV) {
  console.log('[STARTUP] ✅ Global error handlers registered');
}

// LOGIC FIX: Initialize timeout after validation
startupTimeout = setTimeout(() => {
  if (import.meta.env.DEV) {
    console.error('[STARTUP TIMEOUT] Application taking too long to load (>15 seconds)');
    console.error('[STARTUP TIMEOUT] This may indicate a network issue or slow connection');
  }
}, 15000);

// Clear timeout when app loads
window.addEventListener('load', () => {
  if (startupTimeout) {
    clearTimeout(startupTimeout);
  }
  if (import.meta.env.DEV) {
    console.log('[STARTUP] ✅ Application loaded successfully', {
      loadTime: performance.now(),
      timestamp: new Date().toISOString(),
    });
  }
});

if (import.meta.env.DEV) {
  console.log('[STARTUP] Rendering React app...');
}

// BUG FIX #14: Add startup connectivity check
// Test if Supabase is reachable before rendering the app
// This prevents blank screens on networks that block Supabase
async function checkConnectivity() {
  if (import.meta.env.DEV) {
    console.log('[STARTUP] Testing Supabase connectivity...');
  }
  
  try {
    const { testSupabaseConnectivity } = await import('./utils/fetchWithTimeout');
    const result = await testSupabaseConnectivity(SUPABASE_URL, 5000);
    
    if (!result.reachable) {
      if (import.meta.env.DEV) {
        console.error('[STARTUP] ❌ Supabase not reachable:', result.error);
      }
      
      // Show network error UI
      const rootEl = document.getElementById("root");
      if (rootEl) {
        // Dynamically import React and render error component
        const { createRoot } = await import('react-dom/client');
        const { StrictMode } = await import('react');
        const { NetworkErrorBanner } = await import('./components/common/NetworkErrorBanner');
        
        createRoot(rootEl).render(
          <StrictMode>
            <NetworkErrorBanner
              error={result.error || 'Cannot reach server'}
              onRetry={() => window.location.reload()}
              showDetails={import.meta.env.DEV}
            />
          </StrictMode>
        );
      }
      
      return false;
    }
    
    if (import.meta.env.DEV) {
      console.log('[STARTUP] ✅ Supabase connectivity test passed');
    }
    return true;
  } catch (error: any) {
    // If connectivity test itself fails, continue anyway
    // (better to try and fail than block the app)
    if (import.meta.env.DEV) {
      console.warn('[STARTUP] ⚠️ Connectivity test failed, continuing anyway:', error);
    }
    return true;
  }
}

// Run connectivity check and render app
checkConnectivity().then((canContinue) => {
  if (!canContinue) {
    // Network error UI is already shown
    if (startupTimeout) {
      clearTimeout(startupTimeout);
    }
    return;
  }

try {
  // LOGIC FIX: Check for root element existence before using non-null assertion
  const rootEl = document.getElementById("root");
  if (!rootEl) {
    throw new Error("Root element #root not found in DOM");
  }
  
  createRoot(rootEl).render(
    <StrictMode>
      <AppWrapper>
        <App />
      </AppWrapper>
    </StrictMode>
  );
  
  if (import.meta.env.DEV) {
    console.log('[STARTUP] ✅ React app rendered');
  }
} catch (error: any) {
  if (import.meta.env.DEV) {
    console.error('[STARTUP] ❌ Failed to render React app:', {
      error: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString(),
    });
  }
  
  // SECURITY FIX: Render error UI safely without innerHTML injection
  document.body.innerHTML = ''; // Clear body first
  
  const container = document.createElement('div');
  container.style.cssText = 'display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; font-family: system-ui, -apple-system, sans-serif;';
  
  const card = document.createElement('div');
  card.style.cssText = 'max-width: 500px; text-align: center;';
  
  const title = document.createElement('h1');
  title.style.cssText = 'color: #dc2626; margin-bottom: 16px;';
  title.textContent = 'Application Error';
  
  const message = document.createElement('p');
  message.style.cssText = 'color: #6b7280; margin-bottom: 24px;';
  message.textContent = 'Failed to start the application. Please try refreshing the page.';
  
  const errorDetail = document.createElement('p');
  errorDetail.style.cssText = 'font-size: 14px; color: #9ca3af;';
  // SECURITY FIX: Use textContent to prevent XSS
  errorDetail.textContent = `Error: ${error.message}`;
  
  const button = document.createElement('button');
  button.style.cssText = 'margin-top: 24px; padding: 12px 24px; background: #2563eb; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px;';
  button.textContent = 'Refresh Page';
  button.onclick = () => location.reload();
  
  card.appendChild(title);
  card.appendChild(message);
  card.appendChild(errorDetail);
  card.appendChild(button);
  container.appendChild(card);
  document.body.appendChild(container);
  
  throw error;
}

}); // End of checkConnectivity().then()

} // End of if (!(window as any).__APP_INIT_FAILED__)
