import { Link, Stack } from "expo-router";
import { StatusBar } from "expo-status-bar";
import { useEffect } from "react";
import { AppState } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { hydrate, sync } from "../lib/store";
import { C } from "../lib/theme";

export default function RootLayout() {
  useEffect(() => {
    void hydrate();
    // Re-sync whenever the app returns to the foreground.
    const sub = AppState.addEventListener("change", (s) => {
      if (s === "active") void sync();
    });
    return () => sub.remove();
  }, []);

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <StatusBar style="light" />
      <Stack
        screenOptions={{
          headerStyle: { backgroundColor: C.bg },
          headerTintColor: C.text,
          headerShadowVisible: false,
          contentStyle: { backgroundColor: C.bg },
        }}
      >
        <Stack.Screen
          name="index"
          options={{
            title: "GTD",
            headerRight: () => (
              <Link href="/settings" style={{ paddingHorizontal: 8, fontSize: 18 }}>
                ⚙️
              </Link>
            ),
          }}
        />
        <Stack.Screen name="list/[status]" />
        <Stack.Screen name="today" options={{ title: "Today" }} />
        <Stack.Screen name="add" options={{ title: "New task", presentation: "modal" }} />
        <Stack.Screen name="projects" options={{ title: "Projects" }} />
        <Stack.Screen name="task/[id]" options={{ title: "Clarify", presentation: "modal" }} />
        <Stack.Screen name="project/[id]" options={{ title: "Project" }} />
        <Stack.Screen name="settings" options={{ title: "Settings", presentation: "modal" }} />
      </Stack>
    </GestureHandlerRootView>
  );
}
