import { Stack } from 'expo-router';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import * as BackgroundFetch from 'expo-background-fetch';
import { useEffect } from 'react';
import { View, ActivityIndicator } from 'react-native';
import LoginScreen from '../components/LoginScreen';
import { AuthProvider, useAuth } from '../components/AuthContext';

// Import syncManager to ensure TaskManager.defineTask is called in the global scope
import { BACKGROUND_SYNC_TASK } from './utils/syncManager';

function AppContent() {
  const { isAuthenticated, login } = useAuth();

  useEffect(() => {
    const registerTask = async () => {
      try {
        await BackgroundFetch.registerTaskAsync(BACKGROUND_SYNC_TASK, {
          minimumInterval: 60 * 15,
          stopOnTerminate: false,
          startOnBoot: true,
        });
      } catch (err) {
        console.warn('Background fetch failed to register:', err);
      }
    };
    registerTask();
  }, []);

  if (isAuthenticated === null) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F6EAE1' }}>
        <ActivityIndicator size="large" color="#1a73e8" />
      </View>
    );
  }

  if (!isAuthenticated) {
    return <LoginScreen onLoginSuccess={(token: string) => login(token)} />;
  }

  return (
    <SafeAreaProvider>
      <Stack>
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
      </Stack>
    </SafeAreaProvider>
  );
}

export default function Layout() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <AuthProvider>
        <AppContent />
      </AuthProvider>
    </GestureHandlerRootView>
  );
}