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

/**
 * Duolingo-style schmaler Progress-Bar oben.
 * Smooth animiert wenn `current` sich ändert.
 */
export function SlideProgress({
  current,
  total,
}: {
  /** 1-basiert: aktuelle Slide-Nummer */
  current: number;
  /** Total Slide-Anzahl */
  total: number;
}) {
  const colors = useColors();
  const widthPct = useRef(new Animated.Value(clamp01(current / total))).current;

  useEffect(() => {
    Animated.timing(widthPct, {
      toValue: clamp01(current / total),
      duration: 350,
      useNativeDriver: false,
      easing: Easing.out(Easing.cubic),
    }).start();
  }, [current, total, widthPct]);

  const widthInterpolated = widthPct.interpolate({
    inputRange: [0, 1],
    outputRange: ['0%', '100%'],
  });

  return (
    <View
      style={{
        height: 8,
        borderRadius: 4,
        backgroundColor: colors.surfaceElevated,
        overflow: 'hidden',
      }}
    >
      <Animated.View
        style={{
          height: '100%',
          width: widthInterpolated,
          backgroundColor: colors.success,
          borderRadius: 4,
        }}
      />
    </View>
  );
}

function clamp01(v: number): number {
  return Math.max(0, Math.min(1, v));
}
