import { PermissionProvider } from '@/context/PermissionContext';
import { useColorScheme } from '@/hooks/useColorScheme';
import { registerBackgroundUploadTask } from '@/lib/background-uploader/automatic';
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import * as MediaLibrary from 'expo-media-library';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { useEffect } from 'react';
import 'react-native-reanimated';
import '../global.css';
import { Provider } from "../provider";

export default function RootLayout() {
  const colorScheme = useColorScheme();

  useEffect(() => {
    const setupBackgroundUpload = async () => {
      const { status } = await MediaLibrary.getPermissionsAsync();
      if (status !== 'granted') {
        console.log('Media library permission not granted. Background task registered but will wait for permission.');
      }
      const registered = await registerBackgroundUploadTask();
      if (registered) {
        console.log('Background upload task setup finished in RootLayout.');
      } else {
        console.error('Failed to register background upload task in RootLayout.');
      }
    };
    setupBackgroundUpload();
  }, []);

  return (
    <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
      <PermissionProvider>
        <Provider>
          <Stack>
            <Stack.Screen name="(auth)" options={{ headerShown: false }} />
            <Stack.Screen name="(main)" options={{ headerShown: false }} />
            <Stack.Screen name="(settings)" options={{ headerShown: false }} />
            <Stack.Screen name="+not-found" />
          </Stack>
        </Provider>
      </PermissionProvider>
      <StatusBar style="auto" />
    </ThemeProvider>
  );
}
