import React, { useEffect } from 'react';
import {
  Image,
  ImageBackground,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  useWindowDimensions,
} from 'react-native';
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);

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

  return (
    <View style={styles.container}>
      <ImageBackground
        source={require('../assets/welcome_botanical_hero.png')}
        style={[styles.hero, { height: compact ? '48%' : '55%' }]}
        imageStyle={styles.heroImageContent}
        resizeMode="cover"
      >
        <View style={styles.heroShadeTop} />
        <SafeAreaView style={styles.heroSafe}>
          <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>
        </SafeAreaView>
      </ImageBackground>

      <View style={styles.sheet}>
        <View style={styles.sheetHandle} />
        <View style={styles.sheetContent}>
          <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={16} color="#4b7c31" />
            <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: 20,
    paddingTop: 8,
    paddingBottom: 24,
  },
  heroTopRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  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: '#a6d66f',
  },
  ratingPill: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 5,
    backgroundColor: 'rgba(255,255,255,0.18)',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.3)',
    borderRadius: 999,
    paddingHorizontal: 12,
    paddingVertical: 6,
  },
  ratingText: {
    color: '#ffffff',
    fontSize: 12,
    fontWeight: '700',
  },
  testimonialCard: {
    backgroundColor: 'rgba(255,255,255,0.97)',
    borderRadius: 16,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.18,
    shadowRadius: 14,
    elevation: 4,
  },
  testimonialCardCompact: {
    padding: 12,
  },
  testimonialText: {
    color: '#191d16',
    fontSize: 14.5,
    lineHeight: 20,
    fontStyle: 'italic',
    marginBottom: 10,
  },
  testimonialMeta: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  testimonialAuthor: {
    color: '#42493c',
    fontSize: 13,
    fontWeight: '700',
  },
  starsRow: {
    flexDirection: 'row',
    gap: 1,
  },
  sheet: {
    flex: 1,
    backgroundColor: '#fbfaf3',
    borderTopLeftRadius: 28,
    borderTopRightRadius: 28,
    marginTop: -20,
  },
  sheetHandle: {
    alignSelf: 'center',
    width: 44,
    height: 5,
    borderRadius: 3,
    backgroundColor: 'rgba(16,28,18,0.15)',
    marginTop: 12,
    marginBottom: 8,
  },
  sheetContent: {
    flex: 1,
    paddingHorizontal: 24,
    paddingTop: 8,
    paddingBottom: 12,
  },
  headline: {
    color: '#101c12',
    fontSize: 28,
    lineHeight: 34,
    fontWeight: '900',
    textAlign: 'center',
    marginBottom: 10,
  },
  headlineCompact: {
    fontSize: 24,
    lineHeight: 29,
  },
  subline: {
    color: '#5f625d',
    fontSize: 16,
    lineHeight: 22,
    fontWeight: '500',
    textAlign: 'center',
  },
  spacer: {
    flex: 1,
    minHeight: 12,
  },
  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: '#437824',
    fontSize: 15,
    fontWeight: '800',
  },
  demoLink: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 7,
    paddingVertical: 6,
    marginBottom: 8,
  },
  demoText: {
    color: '#4b7c31',
    fontSize: 13.5,
    fontWeight: '700',
  },
  legal: {
    color: '#6b6d68',
    fontSize: 11,
    lineHeight: 14,
    fontWeight: '500',
    textAlign: 'center',
  },
});
