import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import AppNavigator from './src/navigation/AppNavigator';
import { AuthProvider } from './src/contexts/AuthContext';
import * as WebBrowser from 'expo-web-browser';
import { handleInitialAuthUrl, subscribeToAuthRedirects } from './src/auth/authRedirect';
import { supabase } from './src/services/supabase';

WebBrowser.maybeCompleteAuthSession();

export default function App() {
  const [isBootstrapped, setIsBootstrapped] = useState(false);

  useEffect(() => {
    const bootstrapAuth = async () => {
      console.log('[App] Bootstrapping auth...');
      await handleInitialAuthUrl();
      await supabase.auth.getSession();
      
      const sub = subscribeToAuthRedirects();
      
      setIsBootstrapped(true);
      console.log('[App] Bootstrapped auth!');
      
      return () => {
        sub.remove();
      };
    };

    bootstrapAuth();
  }, []);

  if (!isBootstrapped) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#ffffff' }}>
        <ActivityIndicator size="large" color="#0000ff" />
      </View>
    );
  }

  return (
    <SafeAreaProvider>
      <AuthProvider>
        <NavigationContainer>
          <AppNavigator />
        </NavigationContainer>
        <StatusBar style="dark" translucent={false} backgroundColor="#ffffff" hidden={false} />
      </AuthProvider>
    </SafeAreaProvider>
  );
}
