import React, { useEffect } from 'react';
import {
  Image,
  ImageBackground,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  useWindowDimensions,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { router } from 'expo-router';
import { useApp } from '../context/AppContext';
import { useSafeAnalytics } from '../services/analytics';
import { Language } from '../types';

const getWelcomeCopy = (language: Language) => {
  if (language === 'de') {
    return {
      headline: 'Willkommen bei GreenLens!',
      subline: 'Pflanzen erkennen, verstehen und pflegen — ganz einfach.',
      testimonial: '„Endlich überleben meine Pflanzen! Absolute Empfehlung."',
      testimonialAuthor: 'Anna M.',
      cta: "Los geht's",
      login: 'Anmelden',
      demoScan: 'Oder direkt eine Pflanze scannen',
      legal: 'Mit dem Fortfahren akzeptierst du unsere Datenschutzerklärung und AGB.',
      rating: '4,8',
    };
  }
  if (language === 'es') {
    return {
      headline: '¡Bienvenido a GreenLens!',
      subline: 'Identifica, entiende y cuida tus plantas — sin esfuerzo.',
      testimonial: '"¡Por fin mis plantas sobreviven! Muy recomendable."',
      testimonialAuthor: 'Anna M.',
      cta: 'Empezar',
      login: 'Iniciar sesión',
      demoScan: 'O escanea una planta ahora',
      legal: 'Al continuar aceptas nuestra Política de privacidad y Términos.',
      rating: '4.8',
    };
  }
  return {
    headline: 'Welcome to GreenLens!',
    subline: 'Identify, understand and care for your plants — effortlessly.',
    testimonial: '"Finally my plants stay alive! Highly recommend."',
    testimonialAuthor: 'Anna M.',
    cta: "Let's Go",
    login: 'Log in',
    demoScan: 'Or scan a plant right now',
    legal: 'By continuing you agree to our Privacy Policy and Terms.',
    rating: '4.8',
  };
};

export default function OnboardingScreen() {
  const { language } = useApp();
  const { height } = useWindowDimensions();
  const compact = height < 700;
  const posthog = useSafeAnalytics();
  const copy = getWelcomeCopy(language);
  const insets = useSafeAreaInsets();

  useEffect(() => {
    posthog.capture('onboarding_welcome_viewed');
  }, [posthog]);

  return (
    <View style={styles.container}>
      <Image
        source={require('../assets/welcome_hero_vertical.png')}
        style={[{ position: 'absolute', top: 0, left: 0, right: 0, width: '100%' }, { height: compact ? '65%' : '70%' }]}
        resizeMode="cover"
      />
      <View style={[{ width: '100%' }, { height: compact ? '48%' : '52%' }]}>
        <View style={[styles.heroSafe, { paddingTop: Math.max(insets.top, 16) }]}>
          <View style={styles.heroTopRow}>
            <View style={styles.brandRow}>
              <Image
                source={require('../assets/icon.png')}
                style={styles.logo}
                resizeMode="cover"
              />
              <Text style={styles.brandName}>
                Green<Text style={styles.brandAccent}>Lens</Text>
              </Text>
            </View>
            <View style={styles.ratingPill}>
              <Ionicons name="star" size={13} color="#f5c04e" />
              <Text style={styles.ratingText}>{copy.rating}</Text>
            </View>
          </View>

          <View style={[styles.testimonialCard, compact && styles.testimonialCardCompact]}>
            <Text style={styles.testimonialText}>{copy.testimonial}</Text>
            <View style={styles.testimonialMeta}>
              <Text style={styles.testimonialAuthor}>{copy.testimonialAuthor}</Text>
              <View style={styles.starsRow}>
                {[0, 1, 2, 3, 4].map((i) => (
                  <Ionicons key={i} name="star" size={14} color="#f5c04e" />
                ))}
              </View>
            </View>
          </View>
        </View>
      </View>

      <View style={styles.sheet}>
        <View style={styles.sheetHandle} />
        <View style={styles.sheetContent}>
          <View style={styles.topSpacer} />
          <Text style={[styles.headline, compact && styles.headlineCompact]}>{copy.headline}</Text>
          <Text style={styles.subline}>{copy.subline}</Text>

          <View style={styles.spacer} />

          <TouchableOpacity
            style={styles.cta}
            onPress={() => {
              posthog.capture('onboarding_started');
              router.push('/onboarding/slides');
            }}
            activeOpacity={0.86}
          >
            <Text style={styles.ctaText}>{copy.cta}</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={() => router.push('/auth/login')} style={styles.loginLink}>
            <Text style={styles.loginText}>{copy.login}</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={() => router.push('/scanner')} style={styles.demoLink}>
            <Ionicons name="scan-outline" size={18} color="#a6d66f" />
            <Text style={styles.demoText}>{copy.demoScan}</Text>
          </TouchableOpacity>

          <Text style={styles.legal}>{copy.legal}</Text>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0a110b',
  },
  hero: {
    width: '100%',
  },
  heroImageContent: {
    backgroundColor: '#0a110b',
  },
  heroShadeTop: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    height: 120,
    backgroundColor: 'rgba(10,17,11,0.4)',
  },
  heroSafe: {
    flex: 1,
    justifyContent: 'space-between',
    paddingHorizontal: 24,
    paddingBottom: 32,
  },
  heroTopRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    width: '100%',
  },
  brandRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
  },
  logo: {
    width: 36,
    height: 36,
    borderRadius: 10,
    backgroundColor: '#fff',
  },
  brandName: {
    color: '#ffffff',
    fontSize: 24,
    fontWeight: '900',
  },
  brandAccent: {
    color: '#8ba885',
  },
  ratingPill: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    backgroundColor: 'rgba(0, 0, 0, 0.55)',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.25)',
    borderRadius: 999,
    paddingHorizontal: 14,
    paddingVertical: 8,
  },
  ratingText: {
    color: '#ffffff',
    fontSize: 12,
    fontWeight: '700',
  },
  testimonialCard: {
    backgroundColor: 'rgba(16, 26, 18, 0.75)',
    borderRadius: 16,
    padding: 16,
    borderWidth: 1,
    borderColor: 'rgba(255, 255, 255, 0.08)',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.25,
    shadowRadius: 14,
    elevation: 4,
    marginBottom: 8,
  },
  testimonialCardCompact: {
    padding: 12,
  },
  testimonialText: {
    color: '#ffffff',
    fontSize: 14.5,
    lineHeight: 20,
    fontStyle: 'italic',
    marginBottom: 10,
  },
  testimonialMeta: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  testimonialAuthor: {
    color: '#a6d66f',
    fontSize: 13,
    fontWeight: '700',
  },
  starsRow: {
    flexDirection: 'row',
    gap: 1,
  },
  sheet: {
    flex: 1,
    backgroundColor: '#0c160d',
    borderTopLeftRadius: 28,
    borderTopRightRadius: 28,
    marginTop: -20,
    borderWidth: 1,
    borderColor: 'rgba(255, 255, 255, 0.05)',
  },
  sheetHandle: {
    alignSelf: 'center',
    width: 44,
    height: 5,
    borderRadius: 3,
    backgroundColor: 'rgba(255,255,255,0.2)',
    marginTop: 12,
    marginBottom: 8,
  },
  sheetContent: {
    flex: 1,
    paddingHorizontal: 24,
    paddingTop: 8,
    paddingBottom: 12,
  },
  topSpacer: {
    height: 12,
  },
  headline: {
    color: '#ffffff',
    fontSize: 28,
    lineHeight: 34,
    fontWeight: '900',
    textAlign: 'center',
    marginBottom: 10,
  },
  headlineCompact: {
    fontSize: 24,
    lineHeight: 29,
  },
  subline: {
    color: '#dae6d6',
    fontSize: 16,
    lineHeight: 22,
    fontWeight: '500',
    textAlign: 'center',
  },
  spacer: {
    height: 18,
  },
  cta: {
    height: 60,
    borderRadius: 16,
    backgroundColor: '#437824',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 6,
  },
  ctaText: {
    color: '#f8f7ef',
    fontSize: 18,
    fontWeight: '800',
  },
  loginLink: {
    alignItems: 'center',
    paddingVertical: 10,
  },
  loginText: {
    color: '#a6d66f',
    fontSize: 15,
    fontWeight: '800',
  },
  demoLink: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
    height: 52,
    borderRadius: 14,
    borderWidth: 1.5,
    borderColor: '#a6d66f',
    backgroundColor: 'rgba(166, 214, 111, 0.05)',
    marginVertical: 8,
    marginBottom: 12,
  },
  demoText: {
    color: '#a6d66f',
    fontSize: 15,
    fontWeight: '700',
  },
  legal: {
    color: '#8d9382',
    fontSize: 11,
    lineHeight: 14,
    fontWeight: '500',
    textAlign: 'center',
  },
});
