import { useEffect } from 'react';
import { router } from 'expo-router';
import { Image, Text, View, StyleSheet } from 'react-native';
import { useTranslation } from 'react-i18next';
import { color, typography } from '../../src/theme';
import { useAuth } from '../../src/state/auth';
import { useOnboarding } from '../../src/state/onboarding';
import { naviAssets } from '../../src/assets/naviAssets';

/**
 * The splash routes the user based on three pieces of state:
 *   - auth (signed-in user)        → tabs
 *   - onboarded (already seen)     → login
 *   - first launch                 → onboarding step 1
 *
 * We wait for both stores to hydrate so the first frame doesn't bounce.
 */
export default function Splash() {
  const { t } = useTranslation();
  const authHydrated = useAuth((s) => s.isHydrated);
  const user = useAuth((s) => s.user);
  const isGuest = useAuth((s) => s.isGuest);
  const onboardingHydrated = useOnboarding((s) => s.isHydrated);
  const hasOnboarded = useOnboarding((s) => s.hasOnboarded);

  useEffect(() => {
    if (!authHydrated || !onboardingHydrated) return;
    const t = setTimeout(() => {
      if (user || isGuest) router.replace('/(tabs)/home');
      else if (hasOnboarded) router.replace('/(auth)/login');
      else router.replace('/(auth)/onboarding/1');
    }, 600);
    return () => clearTimeout(t);
  }, [authHydrated, onboardingHydrated, user, isGuest, hasOnboarded]);

  return (
    <View style={styles.root}>
      <Image source={naviAssets.logos.appIcon} style={styles.logo} resizeMode="cover" />
      <Text style={styles.brand}>{t('app.name')}</Text>
      <Text style={styles.tag}>{t('app.tagline')}</Text>
      <Text style={styles.loading}>{t('states.loading')}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: color.bg[0] },
  logo: {
    borderRadius: 32,
    height: 112,
    marginBottom: 18,
    width: 112,
  },
  brand: { fontSize: 40, fontWeight: '800', color: color.blue[600] },
  tag: { fontSize: typography.scale.body.size, color: color.ink[500], marginTop: 8 },
  loading: { color: color.ink[500], fontSize: 13, fontWeight: '700', marginTop: 28 },
});
