import { router } from 'expo-router';
import { useEffect } from 'react';
import {
  ActivityIndicator,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { PrimaryButton } from '../src/components/PrimaryButton';
import { useApp } from '../src/context/AppContext';
import { colors } from '../src/theme/colors';

export default function WelcomeScreen() {
  const insets = useSafeAreaInsets();
  const app = useApp();

  useEffect(() => {
    if (!app.ready) return;
    if (app.user) {
      router.replace('/(tabs)');
    }
  }, [app.ready, app.user]);

  if (!app.ready) {
    return (
      <View style={[styles.center, { paddingTop: insets.top }]}>
        <ActivityIndicator size="large" color={colors.accent} />
        <Text style={styles.muted}>Chargement…</Text>
      </View>
    );
  }

  if (app.user) {
    return (
      <View style={[styles.center, { paddingTop: insets.top }]}>
        <ActivityIndicator size="large" color={colors.accent} />
      </View>
    );
  }

  return (
    <ScrollView
      contentContainerStyle={[
        styles.scroll,
        { paddingTop: insets.top + 24, paddingBottom: insets.bottom + 24 },
      ]}
    >
      <Text style={styles.brand}>MDB-Turbo</Text>
      <Text style={styles.tagline}>
        Prospection marchand de biens : marge, visite, investisseurs — sur le
        terrain.
      </Text>
      <PrimaryButton
        title="Continuer hors-ligne (données sur l’appareil)"
        onPress={() => {
          void app.enterLocalMode().then(() => router.replace('/(tabs)'));
        }}
        containerStyle={styles.btn}
      />
      <PrimaryButton
        title="Se connecter (Supabase)"
        variant="ghost"
        onPress={() => router.push('/auth/login')}
        containerStyle={styles.btn}
      />
      <PrimaryButton
        title="Configurer Supabase"
        variant="ghost"
        onPress={() => router.push('/(tabs)/reglages')}
        containerStyle={styles.btn}
      />
      <Text style={styles.hint}>
        Le mode hors-ligne fonctionne sans compte. Pour synchroniser plusieurs
        appareils, renseignez votre projet Supabase dans Réglages puis
        connectez-vous.
      </Text>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  center: {
    flex: 1,
    backgroundColor: colors.bg,
    alignItems: 'center',
    justifyContent: 'center',
    gap: 12,
  },
  muted: { color: colors.textMuted },
  scroll: { paddingHorizontal: 22, backgroundColor: colors.bg },
  brand: {
    fontSize: 34,
    fontWeight: '800',
    color: colors.text,
    marginBottom: 8,
  },
  tagline: {
    fontSize: 16,
    color: colors.textMuted,
    lineHeight: 24,
    marginBottom: 28,
  },
  btn: { marginBottom: 12, width: '100%' },
  hint: {
    marginTop: 20,
    fontSize: 13,
    color: colors.textMuted,
    lineHeight: 20,
  },
});
