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

export type TCardsGridProps = {
  children: ReactNode;
  cardsWidth: number;
  gap: number;
};

export function CardsGrid({ children, gap, cardsWidth }: TCardsGridProps): React.ReactElement {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [cardsAmount, setCardsAmount] = useState(1);

  const handleCardsAmount = () => {
    if (!containerRef || !containerRef.current) {
      return;
    }

    let count = containerRef.current?.clientWidth / (cardsWidth + gap);

    count =
      containerRef.current?.clientWidth - Math.floor(count) * (cardsWidth + gap) >= cardsWidth ? count + 1 : count;

    setCardsAmount(Math.floor(count));
  };

  useEffect(() => {
    const resizeObserver = new ResizeObserver(() => {
      handleCardsAmount();
    });

    if (containerRef?.current) {
      resizeObserver.observe(containerRef.current);
    }
  }, [containerRef]);

  return (
    <div
      className="grid"
      ref={containerRef}
      style={{
        gridTemplateColumns: `repeat(${cardsAmount}, ${cardsWidth}px)`,
        gap: `${gap}px`,
      }}
    >
      {children}
    </div>
  );
}
