import { useEffect, useRef } from 'react';
import { gsap } from 'gsap';

const GridMotionMobile = ({ items = [], gradientColor = 'rgba(251,191,36,0.08)' }) => {
  const gridRef = useRef(null);
  const rowRefs = useRef([]);
  const touchXRef = useRef(window.innerWidth / 2);
  const scrollYRef = useRef(window.scrollY);

  // Вместо 4 рядов x 12 колонок:
  const rows = 3; // например, 10 рядов
  const cols = 3;  // например, 5 колонок
  const totalItems = rows * cols;
  const defaultItems = Array.from({ length: totalItems }, (_, index) => `Item ${index + 1}`);
  const combinedItems = items.length > 0 ? items.slice(0, totalItems) : defaultItems;

  useEffect(() => {
    gsap.ticker.lagSmoothing(0);

    const handleTouchMove = (e) => {
      if (e.touches && e.touches.length > 0) {
        touchXRef.current = e.touches[0].clientX;
      }
    };
    const handleMouseMove = (e) => {
      touchXRef.current = e.clientX;
    };
    const handleScroll = () => {
      scrollYRef.current = window.scrollY;
    };

    const updateMotion = () => {
      // Смещение по X зависит от прокрутки и от касания
      const maxMoveAmount = 80;
      const baseDuration = 0.2;
      const inertiaFactors = [0.5, 0.3, 0.2, 0.1];
      // scrollFactor: 0 (верх) → 1 (глубокий скролл)
      const scrollFactor = Math.min(1, scrollYRef.current / 400);
      rowRefs.current.forEach((row, index) => {
        if (row) {
          const direction = index % 2 === 0 ? 1 : -1;
          // mouse/touch + scrollY
          const moveAmount = (
            ((touchXRef.current / window.innerWidth) * maxMoveAmount - maxMoveAmount / 2) * direction +
            direction * scrollFactor * maxMoveAmount * 1.2
          );
          gsap.to(row, {
            x: moveAmount,
            duration: baseDuration + inertiaFactors[index % inertiaFactors.length],
            ease: 'power3.out',
            overwrite: 'auto',
          });
        }
      });
    };

    const removeAnimationLoop = gsap.ticker.add(updateMotion);
    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('touchmove', handleTouchMove);
    window.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('touchmove', handleTouchMove);
      window.removeEventListener('scroll', handleScroll);
      removeAnimationLoop();
    };
  }, []);

  return (
    <div ref={gridRef} className="h-full w-full overflow-hidden pointer-events-none select-none">
      <section
        className="w-full h-[800px] overflow-hidden relative flex items-center justify-center pt-16"
      >
        <div className="absolute inset-0 z-[1] bg-[url('../../../assets/noise.png')] bg-[length:180px] opacity-10"></div>
        <div className={`gap-2 flex-none relative w-[120vw] h-[800px] grid grid-rows-${rows} grid-cols-1 rotate-[-6deg] origin-center z-[2]`}>
          {[...Array(rows)].map((_, rowIndex) => (
            <div
              key={rowIndex}
              className={`grid gap-2 grid-cols-${cols}`}
              style={{ willChange: 'transform, filter' }}
              ref={(el) => (rowRefs.current[rowIndex] = el)}
            >
              {[...Array(cols)].map((_, itemIndex) => {
                const content = combinedItems[rowIndex * cols + itemIndex];
                return (
                  <div key={itemIndex} className="relative">
                    <div
                      className="relative w-full h-full overflow-hidden rounded-[8px] bg-[#181818] opacity-70 flex items-center justify-center text-white text-[1rem] shadow-sm"
                    >
                      {typeof content === 'string' && content.startsWith('http') ? (
                        <div
                          className="w-full h-full bg-cover bg-center absolute top-0 left-0"
                          style={{ backgroundImage: `url(${content})` }}
                        ></div>
                      ) : (
                        <div className="p-2 text-center z-[1] opacity-60">{content}</div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
        <div className="relative w-full h-full top-0 left-0 pointer-events-none"></div>
      </section>
    </div>
  );
};

export default GridMotionMobile; 