'use client'

import { RequirementCard } from '@/components/shared/cards/RequirementCard'
import FadeInText from '@/components/shared/FadeInText'
import StickyStackCards from '@/components/shared/StickyStackCards';
import { Section } from '@/components/ui/section'
import { useHasBeenVisible } from '@/lib/utils/hooks';
import { RequirementsSection } from '@/payload-types'

interface Props extends RequirementsSection {}


import React, { useEffect, useRef, useState } from 'react'

export const Requirements: React.FC<Props> = (props) => {
  const sectionRef = useRef<HTMLDivElement>(null);
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [isAnimating, setIsAnimating] = useState(false);
  
  const hasBeenVisible = useHasBeenVisible(sectionRef);


  useEffect(() => {
    if (!hasBeenVisible || !props.cards?.length) return;
    let idx = 0;
    let timeout1: NodeJS.Timeout;
    let timeout2: NodeJS.Timeout;
    
    let isUnmounted = false;

    const animate = () => {
      if (isUnmounted) return;
      setActiveIndex(idx);
      setIsAnimating(true);
      timeout1 = setTimeout(() => {
        setIsAnimating(false);
        timeout2 = setTimeout(() => {
          idx = (idx + 1) % (props.cards?.length || 1);
          animate();
        }, 700); // пауза между карточками
      }, 700); // длительность анимации
    };

    const startDelayTimeout: NodeJS.Timeout = setTimeout(animate, 1200);

    return () => {
      isUnmounted = true;
      clearTimeout(timeout1);
      clearTimeout(timeout2);
      clearTimeout(startDelayTimeout);
    };
  }, [hasBeenVisible]);

  return (
    <Section ref={sectionRef} sectionClass="bg-base-white py-[80px] md:py-[100px] lg:py-[120px]" boxClass="">
      <h2 className='h2 mb-8'>
        <FadeInText text={props.title} />
      </h2>
      <div className='hidden md:grid tablet:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-x-5 md:gap-y-4 lg:gap-4'>
        {(props.cards || []).map((card, i) => (
          <RequirementCard key={card.id} caption={card.caption} photo={card.photo} isActive={i === activeIndex && isAnimating} />
        ))}

      </div>
      <div className='md:hidden md:gap-x-5 md:gap-y-4 lg:gap-4'>
      <StickyStackCards className='mb-[48px]'>
          {(props.cards || []).map((card, i) => (
            <RequirementCard key={card.id} caption={card.caption} photo={card.photo} isActive={false}  />
          ))}
        </StickyStackCards>
        
      </div>

    </Section>
  )
}
