'use client' import { useCallback, useEffect, useMemo, useState } from 'react' import ContentCard from './ui/content-cards' import './content-card-carousel.css' interface ContentCardItem { src?: string button_link?: string heading?: string button_text?: string card_text?: string } interface ContentCardCarouselProps { cards: ContentCardItem[] } // correctly works function getVisibleCardCount() { if (typeof window === 'undefined') return 1 if (window.matchMedia('(min-width: 1024px)').matches) return 3 if (window.matchMedia('(min-width: 640px)').matches) return 2 return 1 } export default function ContentCardCarousel({ cards }: ContentCardCarouselProps) { const [visibleCards, setVisibleCards] = useState(1) const [currentIndex, setCurrentIndex] = useState(0) const syncVisibleCards = useCallback(() => { setVisibleCards(getVisibleCardCount()) }, []) useEffect(() => { syncVisibleCards() const mediaQueries = [ window.matchMedia('(min-width: 640px)'), window.matchMedia('(min-width: 1024px)'), ] const onBreakpointChange = () => syncVisibleCards() mediaQueries.forEach((mq) => mq.addEventListener('change', onBreakpointChange)) window.addEventListener('resize', onBreakpointChange) return () => { mediaQueries.forEach((mq) => mq.removeEventListener('change', onBreakpointChange)) window.removeEventListener('resize', onBreakpointChange) } }, [syncVisibleCards]) const maxIndex = useMemo(() => Math.max(cards.length - visibleCards, 0), [cards.length, visibleCards]) // custom mod function because JS does not have working modulus function mod(n: number, m: number) { return ((n % m) + m) % m; } useEffect(() => { setCurrentIndex((previous) => Math.min(previous, maxIndex)) }, [maxIndex]) // % of track width — matches flex slide sizes (100% / 50% / 33.333% per breakpoint) const trackOffsetPercent = cards.length > 0 ? ((currentIndex) * -100) / visibleCards : 0 const next = () => { if (maxIndex === 0) return setCurrentIndex(mod(Math.abs((currentIndex + 1)), (cards.length))) } const previous = () => { if (maxIndex === 0) return setCurrentIndex(mod((currentIndex - 1), (cards.length))) } return (