import { useEffect } from 'react';
import { ActivityIndicator, StyleSheet, View } from 'react-native';
import { useRouter } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { getOnboardingCompleted, getConsentAccepted, setOnboardingCompleted, setConsentAccepted } from '@/src/storage/appStorage';

/**
 * 启动分发：根据 consent 和 onboarding 状态跳转
 */
export default function Index() {
  const router = useRouter();

  useEffect(() => {
    let cancelled = false;
    (async () => {
      // 注意：不要在启动时无条件清空存储，否则 Onboarding/画像等数据无法持久化。
      // 如需调试重置，请在开发期手动清空或自行加调试开关。

      // 1. 检查是否同意协议
      const consentAccepted = await getConsentAccepted();
      if (cancelled) return;

      if (!consentAccepted) {
        router.replace('/(splash)/splash');
        return;
      }

      // 2. 检查 Onboarding
      const completed = await getOnboardingCompleted();
      router.replace(completed ? '/(app)/home' : '/(onboarding)/onboarding');
    })();
    return () => {
      cancelled = true;
    };
  }, [router]);

  return (
    <View style={styles.container}>
      <ActivityIndicator />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center' },
});

