'use client'

import { Section } from '@/components/ui/section'
import { cn } from '@/lib/utils/cn'
import ImageLoader from '@/lib/utils/ImageLoader'
import { AudienceCard } from '@/payload-types'
import { useHasBeenVisible } from '@/lib/utils/hooks'

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

export const Audience = ({
  title,
  audienceCards,
}: {
  title: string
  audienceCards: AudienceCard
}) => {
  const [activeIndex, setActiveIndex] = useState(0)
  const sectionRef = useRef<HTMLDivElement>(null)
  const hasBeenVisible = useHasBeenVisible(sectionRef)

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

  return (
    <Section ref={sectionRef} sectionClass="bg-base-white py-[80px] tablet:py-[100px] xl:py-[120px]">
      <h2 className="subheadline-semibold tablet:h3 xl:h2 mb-6 tablet:mb-8">{title}</h2>
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
        {(audienceCards || []).map((card, i) => (
          <div
            key={i}
            className={cn(
              'p-3 pr-6 flex items-center gap-4 tablet:gap-6 border border-grey-50 rounded-[12px] transition-shadow duration-400',
              i === activeIndex && 'shadow-[0px_8px_24px_rgba(34,29,26,0.18)]',
            )}
          >
            <div className="tablet:w-[180px] tablet:h-[140px] w-[106px] h-[88px] rounded-[8px] overflow-hidden flex-1">
              <ImageLoader
                media={card.icon}
                alt={card.title}
                className="w-full h-full object-cover"
              />
            </div>
            <p className="b1-semibold tablet:subheadline-semibold  text-grey-900 flex-1">{card.title}</p>
          </div>
        ))}
      </div>
    </Section>
  )
}
