import { useEffect, useRef } from 'react';
import { Animated, Easing, Text, View } from 'react-native';
import { RiveAvatar, type Emotion } from '../RiveAvatar';
import { useColors } from '../../lib/theme';

/**
 * Lyra-Mascot (animiertes Rive-Avatar) links + Speech-Bubble rechts.
 * Fade+slide-in beim Mount und bei text-change (key-prop verwenden für Re-Animate).
 *
 * Layout entspricht Duolingo's Duo-Speech-Pattern: Avatar quadratisch links,
 * Bubble organisch rechts mit "Tail" zum Avatar zeigend.
 */
export function LyraBubble({
  text,
  emotion = 'idle',
}: {
  text: string;
  /** Lyra-Emotion fürs Rive (idle, happy, thinking, empathy). */
  emotion?: Emotion;
}) {
  const colors = useColors();
  const opacity = useRef(new Animated.Value(0)).current;
  const translateX = useRef(new Animated.Value(-12)).current;

  useEffect(() => {
    opacity.setValue(0);
    translateX.setValue(-12);
    Animated.parallel([
      Animated.timing(opacity, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
        easing: Easing.out(Easing.cubic),
      }),
      Animated.spring(translateX, {
        toValue: 0,
        useNativeDriver: true,
        friction: 7,
        tension: 80,
      }),
    ]).start();
  }, [text, opacity, translateX]);

  return (
    <View style={{ flexDirection: 'row', alignItems: 'flex-start', gap: 12 }}>
      <View style={{ marginTop: 4 }}>
        <RiveAvatar emotion={emotion} size="md" />
      </View>

      <Animated.View
        style={{
          flex: 1,
          opacity,
          transform: [{ translateX }],
        }}
      >
        {/* Speech-Bubble */}
        <View
          style={{
            backgroundColor: colors.surfaceElevated,
            borderRadius: 16,
            paddingVertical: 14,
            paddingHorizontal: 16,
            // Tail würde via custom-path gerendert — hier reicht der reine
            // Bubble-Look ohne Tail (cleaner auf RN, Duolingo macht's auf iOS
            // auch ohne harten Pixel-Tail).
          }}
        >
          <Text
            style={{
              fontFamily: 'Nunito_600SemiBold',
              fontSize: 16,
              lineHeight: 23,
              color: colors.text,
            }}
          >
            {text}
          </Text>
        </View>
      </Animated.View>
    </View>
  );
}
