"use client";

import { cn } from "../shared/utils";
import { motion, AnimatePresence } from "framer-motion";
import { useState, useEffect, useRef } from "react";

interface AnimatedListProps {
  children: React.ReactNode;
  className?: string;
  staggerDelay?: number;
  animationDuration?: number;
}

export const AnimatedList = ({
  children,
  className,
  staggerDelay = 0.1,
  animationDuration = 0.3,
}: AnimatedListProps) => {
  const [visibleItems, setVisibleItems] = useState<number[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const index = parseInt(entry.target.getAttribute('data-index') || '0');
            setVisibleItems(prev => [...new Set([...prev, index])]);
          }
        });
      },
      {
        threshold: 0.1,
        rootMargin: '50px',
      }
    );

    const items = containerRef.current?.querySelectorAll('[data-index]');
    items?.forEach((item) => observer.observe(item));

    return () => observer.disconnect();
  }, []);

  const childrenArray = Array.isArray(children) ? children : [children];

  return (
    <div ref={containerRef} className={cn("space-y-4", className)}>
      {childrenArray.map((child, index) => (
        <motion.div
          key={index}
          data-index={index}
          initial={{ opacity: 0, y: 20, scale: 0.95 }}
          animate={
            visibleItems.includes(index)
              ? { opacity: 1, y: 0, scale: 1 }
              : { opacity: 0, y: 20, scale: 0.95 }
          }
          transition={{
            duration: animationDuration,
            delay: visibleItems.includes(index) ? index * staggerDelay : 0,
            ease: "easeOut",
          }}
          className="w-full"
        >
          {child}
        </motion.div>
      ))}
    </div>
  );
};
