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";
import * as Sentry from '@sentry/react-native';

Sentry.init({
  dsn: 'https://147afc4a6fba23f819ecfdf2c35f02f9@o4509785157795840.ingest.us.sentry.io/4509785160548352',

  // Adds more context data to events (IP address, cookies, user, etc.)
  // For more information, visit: https://docs.sentry.io/platforms/react-native/data-management/data-collected/
  sendDefaultPii: true,

  // Configure Session Replay
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1,
  integrations: [Sentry.mobileReplayIntegration(), Sentry.feedbackIntegration()],

  // uncomment the line below to enable Spotlight (https://spotlightjs.com)
  // spotlight: __DEV__,
});

export default Sentry.wrap(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="(tabs)" options={{ headerShown: false }} />
            <Stack.Screen
              name="login"
              options={{
                headerShown: false,
                animation: 'fade'
              }}
            />
            <Stack.Screen name="+not-found" />
          </Stack>
        </Provider>
      </PermissionProvider>
      <StatusBar style="auto" />
    </ThemeProvider>
  );
});