'use client'

import GragientCard from '@/components/shared/cards/GragientCard'
import StickyStackCards from '@/components/shared/StickyStackCards'
import { Section } from '@/components/ui/section'
import { useHasBeenVisible } from '@/lib/utils/hooks'
import ImageLoader from '@/lib/utils/ImageLoader'
import { BenefitsItems, Media } from '@/payload-types'
import { useEffect, useRef, useState } from 'react'

export const AboutUsBenefits = ({
  title,
  photo,
  items,
}: {
  title: string
  photo: string | Media
  items: BenefitsItems
}) => {
  const [activeIndex, setActiveIndex] = useState(0)
  const sectionRef = useRef<HTMLDivElement>(null)
  const hasBeenVisible = useHasBeenVisible(sectionRef)

  const cardsOnly = items

  // useEffect(() => {
  //   if (!hasBeenVisible) return
  //   const interval = setInterval(() => {
  //     setActiveIndex((prev) => (prev + 1) % cardsOnly.length)
  //   }, 2000)
  //   return () => clearInterval(interval)
  // }, [hasBeenVisible])

  useEffect(() => {
      const cards = cardsOnly || []
      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="py-[80px] tablet:py-[100px] xl:py-[120px]">
      <h2 className="text-base-white mb-6 tablet:mb-8 subheadline-semibold tablet:h3 xl:h2">
        {title}
      </h2>
      <div className="hidden tablet:grid grid-cols-2 xl:grid-cols-3 rounded-[12px] overflow-hidden border border-grey-900">
        {[
          ...(items || []).slice(0, (items || []).length - 1),
          'image-placeholder', // вставка картинки
          (items || [])[( items || []).length - 1],
        ].map((item, i) => {
          if (typeof item === 'string' && item === 'image-placeholder') {
            return (
              <div key="image" className="w-full h-[320px] relative overflow-hidden">
                <div className="absolute inset-0 bg-[#00000080] z-10" />
                <ImageLoader className="w-full h-full object-cover" media={photo} alt="" />
              </div>
            )
          }

          if (typeof item !== 'object' || item === null) return null

          const safeItems = items || []
          const realIndex = safeItems
            .slice(0, safeItems.length - 1)
            .concat(safeItems[safeItems.length - 1])
            .filter((el) => typeof el === 'object')
            .indexOf(item)

          return (
            <GragientCard
              key={i}
              title={item.title}
              icon={item.icon}
              subtitle={item.subtitle}
              type="large"
              isActive={activeIndex === realIndex}
            />
          )
        })}
      </div>

      <div className="tablet:hidden ">
        <StickyStackCards className="mb-[100px]" onActiveIndexChange={setActiveIndex} cardGap={20}>
          {(items || []).map((item, i) => (
            <GragientCard
              key={item.id}
              icon={item.icon}
              title={item.title}
              subtitle={item.subtitle}
              type="large"
              isActive={activeIndex === i}
            />
          ))}
        </StickyStackCards>
      </div>
    </Section>
  )
}
