import { useEffect } from 'react';
import { DarkTheme, DefaultTheme, Stack, ThemeProvider } from 'expo-router';
import { useColorScheme } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';

import { Colors } from '@/constants/theme';
import { startConvexSync } from '@/data/sync';
import { useGlideWidgetSync } from '@/widget';

/**
 * Keeps the home-screen widget in sync with the local task board. Renders
 * nothing; reads the store directly. No-op off iOS.
 */
function WidgetSync() {
  useGlideWidgetSync();
  return null;
}

/**
 * Runs the Convex sync engine for the app's lifetime — mirrors the local store to the
 * account's server rows when online. A no-op when no Convex URL is configured, so the app
 * stays fully local. Renders nothing.
 */
function ConvexSync() {
  useEffect(() => startConvexSync(), []);
  return null;
}

export default function RootLayout() {
  const scheme = useColorScheme() === 'dark' ? 'dark' : 'light';
  const palette = Colors[scheme];
  const base = scheme === 'dark' ? DarkTheme : DefaultTheme;
  const navTheme = {
    ...base,
    colors: {
      ...base.colors,
      background: palette.background,
      card: palette.surface,
      text: palette.text,
      border: palette.border,
      primary: palette.accent,
      notification: palette.resistance,
    },
  };

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <WidgetSync />
      <ConvexSync />
      <ThemeProvider value={navTheme}>
        <Stack
          screenOptions={{
            headerShown: false,
            contentStyle: { backgroundColor: palette.background },
          }}>
          <Stack.Screen name="index" />
          {/* Planning is a focused session — full screen, explicit exit. */}
          <Stack.Screen name="plan" options={{ presentation: 'fullScreenModal', animation: 'fade' }} />
          {/* Capture is a quick sheet. */}
          <Stack.Screen name="new" options={{ presentation: 'modal' }} />
        </Stack>
      </ThemeProvider>
    </GestureHandlerRootView>
  );
}
