import "react-native-gesture-handler";
import React from "react";
import { useEffect, useState } from "react";
import { userApi } from "./app/services/api/userApi";
import useUserStore from "./app/store/user";
import useBurialPointStore from "./app/store/burialPoint";
import { AuthProvider, useAuth } from "./app/contexts/AuthContext";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { AppNavigator } from "./app/navigation/AppNavigator";
import { View, ActivityIndicator } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import "./app/i18n";

function AppContent() {
  const { setUser } = useUserStore();
  const { login, logout } = useAuth();
  const { logAppLaunch } = useBurialPointStore();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const initApp = async () => {
      try {
        const token = await AsyncStorage.getItem("token");
        if (token) {
          try {
            const user = await userApi.getProfile();        
            setUser(user);
            login();
          } catch (error) {
            console.error('Failed to get user profile:', error);
            logout();
          }
        }
        // 记录应用启动成功埋点
        logAppLaunch(true);
      } catch (error) {
        console.error('App initialization error:', error);
        // 记录应用启动失败埋点
        logAppLaunch(false);
      } finally {
        setIsLoading(false);
      }
    };

    initApp();
  }, []);

  if (isLoading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" color="#0066FF" />
      </View>
    );
  }

  return <AppNavigator />;
}

export default function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <AuthProvider>
        <AppContent />
      </AuthProvider>
    </GestureHandlerRootView>
  );
}
