import React, { useContext, useEffect, useState } from "react";
import { ActivityIndicator } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import ScreenLayout from "../components/layout/ScreenLayout";
import { AuthContext } from "../context/AuthContext";
import LoginScreen from "../screens/LoginScreen";
import RegisterScreen from "../screens/RegisterScreen";
import WelcomeScreen from "../screens/WelcomeScreen";
import BottomTabs from "./BottomTabs";

const Stack = createNativeStackNavigator();
const WELCOME_SEEN_KEY = "@rnskit_has_seen_welcome";

export default function ProtectedStack() {
  const { token, isHydrated } = useContext(AuthContext);
  const [showWelcome, setShowWelcome] = useState(false);
  const [isCheckingWelcome, setIsCheckingWelcome] = useState(true);

  useEffect(() => {
    const readWelcomeState = async () => {
      try {
        const seen = await AsyncStorage.getItem(WELCOME_SEEN_KEY);
        setShowWelcome(seen !== "true");
      } finally {
        setIsCheckingWelcome(false);
      }
    };

    void readWelcomeState();
  }, []);

  const handleWelcomeContinue = async () => {
    await AsyncStorage.setItem(WELCOME_SEEN_KEY, "true");
    setShowWelcome(false);
  };

  if (!isHydrated || isCheckingWelcome) {
    return (
      <ScreenLayout centered padded={false}>
        <ActivityIndicator />
      </ScreenLayout>
    );
  }

  if (showWelcome) {
    return <WelcomeScreen onContinue={() => void handleWelcomeContinue()} />;
  }

  return (
    <Stack.Navigator>
      {token ? (
        <Stack.Screen
          name="Main"
          component={BottomTabs}
          options={{ headerShown: false }}
        />
      ) : (
        <>
          <Stack.Screen name="Login" component={LoginScreen} />
          <Stack.Screen name="Register" component={RegisterScreen} />
        </>
      )}
    </Stack.Navigator>
  );
}
