"use client";

import { useRef, useState, useEffect, ReactNode } from "react";

export function Carousel({ children }: { children: ReactNode }) {
  const parentRef = useRef<HTMLDivElement>(null);
  const carouselRef = useRef<HTMLDivElement>(null);
  const [parentWidth, setParentWidth] = useState<number>(0);
  const [carouselWidth, setCarouselWidth] = useState<number>(0);
  const [move, setMove] = useState<number>(0);

  useEffect(() => {
    setParentWidth(parentRef.current?.clientWidth || 0);
    setCarouselWidth(carouselRef.current?.scrollWidth || 0);

    const id = setInterval(() => {
      setMove((prev) => {
        if (prev <= -carouselWidth) return parentWidth;
        else return prev - 1;
      });
    }, 10);

    return () => clearInterval(id);
  }, [carouselRef.current, parentRef.current]);

  return (
    <div ref={parentRef} className="overflow-hidden">
      <div style={{ transform: `translateX(${move}px)` }} ref={carouselRef}>
        {children}
      </div>
    </div>
  );
}
