// CRITICAL: Import early Firefox fix FIRST, before any other imports
// This ensures service worker interception happens before PWA registration
// TEMPORARILY DISABLED: Firefox fixes are causing authentication issues
// import './utils/earlyFirefoxInit';

import React, { useEffect } from 'react'
import { createRoot, hydrateRoot } from 'react-dom/client'
import AppRouter from './AppRouter'
import './index.css'
import 'katex/dist/katex.min.css'
import { StyledEngineProvider } from '@mui/material/styles';
import { AuthProvider } from './context/AuthContext';
import { DataProvider } from './context/DataContext';
import { LoadingProvider } from './context/LoadingContext';
import { AppThemeProvider } from './context/ThemeContext';
import { ResultsProvider } from './context/ResultsContext';
import { PaymentProvider } from './context/PaymentContext'; // Import PaymentProvider

import { checkAndDisplayCompatibilityWarnings } from './utils/compatibilityChecker';
import { HelmetProvider } from 'react-helmet-async';
import { BrowserRouter } from 'react-router-dom'; // Change to BrowserRouter
import { cacheManager, recoverFromCacheIssues } from './utils/cacheManager';
import { emergencyAuthCleanup } from './utils/emergencyAuthCleanup';
import { initializeEnhancedMapping } from './utils/geminiMappingUtils';
import './utils/quickMappingTest'; // Load test functions for console access
import PWAErrorBoundary from './components/PWA/PWAErrorBoundary';
// TEMPORARILY DISABLED: Firefox fixes are causing authentication issues
// import { productionFirefoxFix } from './utils/productionFirefoxFix';
// import { firefoxAuthRecovery } from './utils/firefoxAuthRecovery';

// Expose services to global window for testing
import { bookAccessService } from './services/bookAccessService';
import { supabase } from './lib/supabase';

// Make services available globally for testing
if (typeof window !== 'undefined') {
  (window as any).bookAccessService = bookAccessService;
  (window as any).supabase = supabase;
  console.log('🧪 Testing services exposed to window object');
}

// Wrapper component to handle browser compatibility check
const AppWithCompatibilityCheck: React.FC = () => {
  useEffect(() => {
    // Initialize app with cache validation and recovery
    const initializeApp = async () => {
      try {
        // Check for browser compatibility issues
        checkAndDisplayCompatibilityWarnings();

        // TEMPORARILY DISABLED: Firefox fixes are causing authentication issues
        // Initialize production Firefox fixes
        // productionFirefoxFix.initialize();

        // Initialize Firefox authentication recovery system
        // firefoxAuthRecovery.initialize();

        // Proactive cache validation and recovery
        if (cacheManager.shouldForceRefresh()) {
          console.log('🔧 Cache corruption detected, performing recovery...');
          localStorage.setItem('datastatpro-cache-corruption-detected', 'false');
          await recoverFromCacheIssues();
          cacheManager.markForceRefresh();
        }

        // Initialize cache management and recovery
        const initializeCacheManagement = async () => {
          try {
            // Clear stale caches on startup
            const clearedCount = await cacheManager.clearStaleCaches();
            console.log(`🧹 Cleared ${clearedCount} stale caches during app initialization`);
            
            // Attempt cache recovery if needed
            await recoverFromCacheIssues();
          } catch (error) {
            console.warn('Cache management initialization failed:', error);
          }
        };

        // Initialize emergency authentication cleanup monitoring
        const initializeEmergencyAuth = () => {
          try {
            emergencyAuthCleanup.initializeMonitoring();
            console.log('🚨 Emergency authentication cleanup monitoring initialized');
          } catch (error) {
            console.warn('Emergency auth cleanup initialization failed:', error);
          }
        };

        // Initialize enhanced Gemini mapping system
        const initializeGeminiMapping = () => {
          try {
            initializeEnhancedMapping();
            console.log('🤖 Enhanced Gemini mapping system initialized');
          } catch (error) {
            console.warn('Enhanced Gemini mapping initialization failed:', error);
          }
        };

        // Initialize real-time service - disabled to prevent global_gemini_learning_data errors
        const initializeRealtimeService = async () => {
          try {
            // Temporarily disabled to prevent database table errors
            // const { realtimeService } = await import('./services/realtimeService');
            // await realtimeService.initialize();
            console.log('🔄 Real-time service initialization skipped (disabled)');
          } catch (error) {
            console.warn('Real-time service initialization failed:', error);
          }
        };

        // Perform routine cache maintenance and service initialization
        try {
          await initializeCacheManagement();
          initializeEmergencyAuth();
          initializeGeminiMapping();
          // await initializeRealtimeService(); // Disabled to prevent global_gemini_learning_data errors
        } catch (error) {
          console.warn('Service initialization failed:', error);
        }

        // Add viewport adjustment for iOS (avoid issues with viewport heights)
        const handleResize = () => {
          // Set CSS variable for viewport height that works on iOS
          document.documentElement.style.setProperty('--vh', `${window.innerHeight * 0.01}px`);
        };

        // Initial call
        handleResize();

        // Add event listener for resize
        window.addEventListener('resize', handleResize);

        // Track successful app initialization
        localStorage.removeItem('datastatpro-loading-failures');

        // Add global error handlers for cache corruption detection
        const handleUnhandledError = (event: ErrorEvent) => {
          const err = event.error;
          const msg = err?.message || event.message || '';
          // Swallow Supabase refresh token noise and recover gracefully
          if (/Invalid Refresh Token/i.test(msg) || /Refresh Token Not Found/i.test(msg)) {
            console.warn('Supabase auth refresh error detected, performing cleanup');
            supabase.auth.signOut().catch(() => {});
            return;
          }
          console.error('Unhandled error:', err);

          // Check if error indicates cache corruption
          const errorMessage = msg;
          const cacheCorruptionPatterns = [
            /loading chunk \d+ failed/i,
            /failed to fetch/i,
            /networkerror/i,
            /cache/i,
            /service worker/i,
            /auth.*timeout/i,
            /session.*failed/i
          ];

          if (cacheCorruptionPatterns.some(pattern => pattern.test(errorMessage))) {
            console.warn('Cache corruption detected from unhandled error');
            localStorage.setItem('datastatpro-cache-corruption-detected', 'true');
          }

          // Check for authentication-related errors
          const authErrorPatterns = [
            /auth.*failed/i,
            /session.*expired/i,
            /token.*invalid/i,
            /supabase.*error/i
          ];

          if (authErrorPatterns.some(pattern => pattern.test(errorMessage))) {
            console.warn('Authentication error detected');
            localStorage.setItem('datastatpro-auth-loading-stuck', 'true');
          }
        };

        const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
          console.error('Unhandled promise rejection:', event.reason);

          // Similar check for promise rejections
          const reason = event.reason?.message || event.reason || '';
          if (typeof reason === 'string' && reason.includes('fetch')) {
            localStorage.setItem('datastatpro-cache-corruption-detected', 'true');
          }
        };

        window.addEventListener('error', handleUnhandledError);
        window.addEventListener('unhandledrejection', handleUnhandledRejection);

        // Cleanup function
        return () => {
          window.removeEventListener('resize', handleResize);
          window.removeEventListener('error', handleUnhandledError);
          window.removeEventListener('unhandledrejection', handleUnhandledRejection);
        };
      } catch (error) {
        console.error('App initialization failed:', error);

        // Track loading failures
        const failures = parseInt(localStorage.getItem('datastatpro-loading-failures') || '0') + 1;
        localStorage.setItem('datastatpro-loading-failures', failures.toString());

        // If multiple failures, mark for cache recovery
        if (failures > 2) {
          localStorage.setItem('datastatpro-cache-corruption-detected', 'true');
        }
      }
    };

    const cleanup = initializeApp();

    // Return cleanup function
    return () => {
      cleanup.then(cleanupFn => {
        if (typeof cleanupFn === 'function') {
          cleanupFn();
        }
      });
    };
  }, []);
  
  return (
    <PWAErrorBoundary>
      <StyledEngineProvider injectFirst>
        <AppThemeProvider>
          <BrowserRouter> {/* Change to BrowserRouter */}
            <LoadingProvider>
              <PaymentProvider>
                <AuthProvider>
                  <DataProvider>
                    <ResultsProvider>
                        <AppRouter />
                    </ResultsProvider>
                  </DataProvider>
                </AuthProvider>
              </PaymentProvider>
            </LoadingProvider>
          </BrowserRouter>
        </AppThemeProvider>
      </StyledEngineProvider>
    </PWAErrorBoundary>
  );
};

const rootElement = document.getElementById('root')!;
if (rootElement.hasChildNodes()) {
  hydrateRoot(
    rootElement,
    <React.StrictMode>
      <HelmetProvider>
        <AppWithCompatibilityCheck />
      </HelmetProvider>
    </React.StrictMode>
  );
} else {
  createRoot(rootElement).render(
    <React.StrictMode>
      <HelmetProvider>
        <AppWithCompatibilityCheck />
      </HelmetProvider>
    </React.StrictMode>
  );
}
