import React, { useEffect, useRef } from 'react';
import { View, Text, Image, StyleSheet, Animated, Easing } from 'react-native';
import StarField from '../components/StarField';
import useAuthStore from '../store/useAuthStore';
import useAppStore from '../store/useAppStore';
import { colors, fonts } from '../utils/theme';

const MIN_SPLASH_MS = 5000;

export default function SplashScreen({ navigation }) {
  const logoScale = useRef(new Animated.Value(0.5)).current;
  const logoOpacity = useRef(new Animated.Value(1)).current;
  const textOpacity = useRef(new Animated.Value(1)).current;
  const glowScale = useRef(new Animated.Value(0.8)).current;

  useEffect(() => {
    // Start animations
    Animated.parallel([
      Animated.timing(logoScale, {
        toValue: 1, duration: 2000, easing: Easing.out(Easing.cubic), useNativeDriver: true,
      }),
      Animated.loop(
        Animated.sequence([
          Animated.timing(glowScale, { toValue: 1.2, duration: 1500, useNativeDriver: true }),
          Animated.timing(glowScale, { toValue: 0.9, duration: 1500, useNativeDriver: true }),
        ])
      ),
    ]).start();

    // Run logic in parallel with animation
    const resolve = async () => {
      try {
        const start = Date.now();

        // Check onboarding + session in parallel (with timeout to prevent hang)
        const timeout = new Promise((r) => setTimeout(r, 5000));
        await Promise.race([
          Promise.all([
            useAppStore.getState().initApp(),
            useAuthStore.getState().fetchSession(),
          ]),
          timeout,
        ]);

        const onboardingDone = useAppStore.getState().onboardingDone;
        const session = useAuthStore.getState().session;

        // Wait for minimum splash duration
        const elapsed = Date.now() - start;
        if (elapsed < MIN_SPLASH_MS) {
          await new Promise((r) => setTimeout(r, MIN_SPLASH_MS - elapsed));
        }

        // Route decision
        if (!onboardingDone) {
          navigation.reset({ index: 0, routes: [{ name: 'Onboarding' }] });
        } else if (!session) {
          navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
        } else {
          navigation.reset({ index: 0, routes: [{ name: 'MainTabs' }] });
        }
      } catch (e) {
        console.warn('Splash resolve error:', e);
        // Fallback: go to Login
        navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
      }
    };

    resolve();
  }, []);

  return (
    <View style={styles.container}>
      <StarField count={40} />
      <View style={styles.content}>
        <Animated.View
          style={[
            styles.logoContainer,
            { opacity: logoOpacity, transform: [{ scale: logoScale }] },
          ]}
        >
          <Animated.View style={[styles.glow, { transform: [{ scale: glowScale }] }]} />
          <Image
            source={require('../../assets/icon.png')}
            style={styles.logo}
            resizeMode="contain"
          />
        </Animated.View>

        <Animated.Text style={[styles.title, { opacity: textOpacity }]}>
          NOVA40
        </Animated.Text>
        <Animated.Text style={[styles.subtitle, { opacity: textOpacity }]}>
          You are becoming someone new
        </Animated.Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.background },
  content: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 40 },
  logoContainer: { alignItems: 'center', justifyContent: 'center', marginBottom: 40 },
  glow: {
    width: 200, height: 200, borderRadius: 100,
    backgroundColor: colors.planetGlow, opacity: 0.4, position: 'absolute',
  },
  logo: { width: 140, height: 140 },
  title: {
    color: colors.text, fontSize: fonts.sizes.hero,
    fontWeight: fonts.weights.bold, letterSpacing: 8, marginBottom: 16,
  },
  subtitle: {
    color: colors.textSecondary, fontSize: fonts.sizes.md,
    textAlign: 'center', fontStyle: 'italic',
  },
});
