import { StatusBar } from 'expo-status-bar';
import React, { useEffect } from 'react';
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 Linking from 'expo-linking';
import * as QueryParams from 'expo-auth-session/build/QueryParams';
import { supabase } from './src/services/supabase';

export default function App() {
  useEffect(() => {
    const catchTokenOnLoad = async () => {
      const url = await Linking.getInitialURL();
      if (!url) return;
      
      // Supabase sends tokens after a '#' which Expo might ignore, replace it with '?'
      const cleanUrl = url.replace('#', '?');
      const { params, errorCode } = QueryParams.getQueryParams(cleanUrl);
      
      if (params?.access_token) {
        console.log('🔥 TOKEN APANHADO NO ARRANQUE!');
        await supabase.auth.setSession({
          access_token: params.access_token,
          refresh_token: params.refresh_token || '',
        });
      }
    };
    catchTokenOnLoad();
  }, []);

  return (
    <SafeAreaProvider>
      <AuthProvider>
        <NavigationContainer>
          <AppNavigator />
        </NavigationContainer>
        <StatusBar style="auto" hidden={false} />
      </AuthProvider>
    </SafeAreaProvider>
  );
}
