import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { initializeFirebaseCollections } from './lib/firebase-init';
import { auth } from './lib/firebase';
import { onAuthStateChanged } from 'firebase/auth';
import { toast } from 'sonner';

// Initialize the app with proper error handling
const initializeApp = async () => {
  let initializationAttempts = 0;
  const maxAttempts = 3;

  const attemptInitialization = async (): Promise<boolean> => {
    try {
      // Wait for Firebase Auth to initialize
      await new Promise<void>((resolve) => {
        const unsubscribe = onAuthStateChanged(auth, () => {
          unsubscribe();
          resolve();
        });
      });

      // Now initialize collections
      await initializeFirebaseCollections();
      console.log('Firebase collections initialized successfully');
      return true;
    } catch (error) {
      console.error('Failed to initialize Firebase collections:', error);
      initializationAttempts++;
      
      if (initializationAttempts < maxAttempts) {
        console.log(`Retrying initialization (attempt ${initializationAttempts + 1}/${maxAttempts})...`);
        // Wait 2 seconds before retrying
        await new Promise(resolve => setTimeout(resolve, 2000));
        return attemptInitialization();
      }
      
      // If all attempts failed, show error but continue loading the app
      toast.error('Failed to initialize some features - please check your internet connection');
      return false;
    }
  };

  // Start initialization attempts
  await attemptInitialization();

  // Render the app regardless of initialization result
  createRoot(document.getElementById('root')!).render(
    <StrictMode>
      <App />
    </StrictMode>
  );
};

// Start initialization
initializeApp();