'use client'

import React, { useEffect, useRef, useState } from 'react'
import { Section } from '@/components/ui/section'
import { FadeInText } from '@/components/shared/FadeInText'
import { StickyStackCards } from '@/components/shared/StickyStackCards'
import { ConditionsSection, Media, WhyChooseUsSection } from '@/payload-types'
import { useHasBeenVisible } from '@/lib/utils/hooks'
import ImageLoader from '@/lib/utils/ImageLoader'
import { AnimatePresence, motion } from 'framer-motion'
import GragientCard from '@/components/shared/cards/GragientCard'

interface Props extends ConditionsSection {}

export const Conditions: React.FC<Props> = (props) => {
  const sectionRef = useRef<HTMLDivElement>(null)
  const [activeIndex, setActiveIndex] = useState<number>(0)

  const hasBeenVisible = useHasBeenVisible(sectionRef)

  useEffect(() => {
    const cards = props.cards || []
    if (cards.length === 0 || !hasBeenVisible) return
  
    function isMobile() {
      return window.innerWidth < 744
    }
  
    let index = 0
    let interval: NodeJS.Timeout
  
    function startAnimation() {
      if (isMobile()) {
        setActiveIndex(0)
      } else {
        interval = setInterval(() => {
          setActiveIndex(index)
          index = (index + 1) % cards.length
        }, 1500)
      }
    }
  
    startAnimation()
    window.addEventListener('resize', handleResize)
  
    function handleResize() {
      clearInterval(interval)
      startAnimation()
    }
  
    return () => {
      window.removeEventListener('resize', handleResize)
      clearInterval(interval)
    }
  }, [hasBeenVisible]);
  

  return (
    <Section ref={sectionRef} sectionClass=" pb-[80px] md:pb-[100px] lg:pb-[120px]" boxClass="">
      <h2 className="h4 md:h3 lg:h2 mb-8 text-base-white">
        {/* <FadeInText text={props.title} canAnimate={hasBeenVisible} /> */}
        {props.title}
      </h2>
      <div className="hidden md:grid tablet:grid-cols-2 gap-4 ">
        {(props.cards || []).map((card, i) => (
          <GragientCard
            key={card.id}
            icon={card.icon}
            title={card.conditionalName}
            subtitle={card.conditional}
            type="medium"
            isActive={activeIndex === i}
          />
        ))} 
      </div>
      <div className="md:hidden ">
        <StickyStackCards className="mb-[100px]" onActiveIndexChange={setActiveIndex} cardGap={20}>
          {(props.cards || []).map((card, i) => (
            <GragientCard
              key={card.id}
              icon={card.icon}
              title={card.conditionalName}
              subtitle={card.conditional}
              type="medium"
              isActive={activeIndex === i}
            />
          ))}
        </StickyStackCards>
      </div>
    </Section>
  )
}