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

const FourDotLoader: React.FC = () => {
  const dots = [
    useRef(new Animated.Value(0)).current,
    useRef(new Animated.Value(0)).current,
    useRef(new Animated.Value(0)).current,
    useRef(new Animated.Value(0)).current,
  ];

  useEffect(() => {
    const animations = dots.map((dot, index) => {
      const core = Animated.sequence([
        Animated.timing(dot, {
          toValue: -14,
          duration: 260,
          easing: Easing.inOut(Easing.quad),
          useNativeDriver: true,
        }),
        Animated.timing(dot, {
          toValue: 0,
          duration: 260,
          easing: Easing.inOut(Easing.quad),
          useNativeDriver: true,
        }),
      ]);

      // One-time staggered delay, then infinite loop
      const animation = Animated.sequence([
        Animated.delay(index * 120),
        Animated.loop(core),
      ]);

      animation.start();
      return animation;
    });

    return () => {
      animations.forEach((anim) => anim.stop());
    };
  }, []);

  return (
    <View
      style={{
        flexDirection: "row",
        alignItems: "flex-end",
        justifyContent: "center",
        marginTop: 16,
      }}
    >
      {dots.map((dot, index) => (
        <Animated.View
          key={index}
          style={{
            width: 16,
            height: 16,
            borderRadius: 8,
            marginHorizontal: 6,
            backgroundColor: "#16A34A",
            transform: [{ translateY: dot }],
          }}
        />
      ))}
    </View>
  );
};

export default FourDotLoader;
