import React, { useEffect, useRef } from "react";
import { Animated, StyleSheet, View } from "react-native";

export function AudioVisualizer({ active }: { active: boolean }) {
  const bars = useRef([0, 1, 2, 3, 4].map(() => new Animated.Value(0.3))).current;

  useEffect(() => {
    if (!active) {
      bars.forEach((b) => b.setValue(0.3));
      return;
    }
    const anims = bars.map((b, i) =>
      Animated.loop(
        Animated.sequence([
          Animated.timing(b, {
            toValue: 0.3 + Math.random() * 0.7,
            duration: 250 + i * 40,
            useNativeDriver: true,
          }),
          Animated.timing(b, {
            toValue: 0.25,
            duration: 250 + i * 40,
            useNativeDriver: true,
          }),
        ]),
      ),
    );
    anims.forEach((a) => a.start());
    return () => anims.forEach((a) => a.stop());
  }, [active, bars]);

  return (
    <View style={styles.row}>
      {bars.map((b, i) => (
        <Animated.View
          key={i}
          style={[styles.bar, { transform: [{ scaleY: b }] }]}
        />
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  row: { flexDirection: "row", gap: 6, height: 40, alignItems: "center" },
  bar: {
    width: 6,
    height: 36,
    borderRadius: 3,
    backgroundColor: "#C4A35A",
  },
});
