import { useEffect } from 'react';
import { ActivityIndicator, StyleSheet, View, useWindowDimensions } from 'react-native';
import { useRouter } from 'expo-router';

import { getOnboardingCompleted, getConsentAccepted } from '@/src/storage/appStorage';
import { clampContentWidth, isIPadLike } from '@/src/utils/device';

/**
 * 启动分发：根据 consent 和 onboarding 状态跳转
 */
export default function Index() {
  const router = useRouter();
  const { width, height } = useWindowDimensions();
  const isTablet = isIPadLike(width, height);
  const loaderWidth = isTablet ? clampContentWidth(width, 680, 24) : undefined;

  useEffect(() => {
    let cancelled = false;
    (async () => {
      // 1. 检查是否同意协议
      const consentAccepted = await getConsentAccepted();
      if (cancelled) return;

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

      // 2. 检查 Onboarding 是否已完成
      const completed = await getOnboardingCompleted();
      if (cancelled) return;

      if (completed) {
        // 如果已经完成过流程，直接进 Home
        router.replace('/(app)/home');
      } else {
        // 如果是首次进入（或未完成流程），进入 Onboarding
        router.replace('/(onboarding)/onboarding');
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [router]);

  return (
    <View style={styles.container}>
      <View style={[styles.loaderWrap, loaderWidth ? { width: loaderWidth } : null]}>
        <ActivityIndicator />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    height: '100%',
    alignSelf: 'stretch',
    alignItems: 'center',
    justifyContent: 'center',
  },
  loaderWrap: {
    alignItems: 'center',
    justifyContent: 'center',
  },
});
