import { Stack, useRouter } from 'expo-router';
import { DatabaseProvider } from '@/hooks/useDatabase';
import { SettingsProvider } from '@/theme';
import { FriendsProvider } from '@/hooks/useFriends';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import { UpdateNotifier } from '@/components/UpdateNotifier';
import { Linking } from 'react-native';
import { useEffect } from 'react';
import { requestQuickAddFocus } from '@/utils/quickAddFocus';

function RootNavigator() {
  const router = useRouter();

  useEffect(() => {
    const handleUrl = (url: string | null) => {
      if (!url || !url.includes('://quick-add')) return;
      router.replace('/(tabs)');
      requestQuickAddFocus();
    };

    Linking.getInitialURL().then(handleUrl).catch(() => {});
    const subscription = Linking.addEventListener('url', ({ url }) => handleUrl(url));
    return () => {
      subscription.remove();
    };
  }, [router]);

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <StatusBar style="light" />
      <Stack screenOptions={{ headerShown: false }}>
        <Stack.Screen name="(tabs)" />
        <Stack.Screen name="add-task" />
        <Stack.Screen name="task-detail" />
        <Stack.Screen name="day-view" />
      </Stack>
    </GestureHandlerRootView>
  );
}

export default function RootLayout() {
  return (
    <SettingsProvider>
      <DatabaseProvider>
        <FriendsProvider>
          <UpdateNotifier />
          <RootNavigator />
        </FriendsProvider>
      </DatabaseProvider>
    </SettingsProvider>
  );
}
