'use client' import { useEffect, useRef, useState } from 'react' import { SerperSearchResultItem } from '@/lib/types' import { Carousel, type CarouselApi, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from '@/components/ui/carousel' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' interface VideoCarouselDialogProps { children: React.ReactNode videos: SerperSearchResultItem[] query: string initialIndex?: number // Add initialIndex prop } export function VideoCarouselDialog({ children, videos, query, initialIndex = 0 // Default to 0 }: VideoCarouselDialogProps) { const [api, setApi] = useState() const [current, setCurrent] = useState(initialIndex + 1) const videoRefs = useRef<(HTMLIFrameElement | null)[]>([]) const previousIndexRef = useRef(initialIndex) useEffect(() => { if (!api) { return } const handleSelect = () => { const newIndex = api.selectedScrollSnap() const prevVideo = videoRefs.current[previousIndexRef.current] prevVideo?.contentWindow?.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ) previousIndexRef.current = newIndex setCurrent(newIndex + 1) } api.on('select', handleSelect) return () => { api.off('select', handleSelect) } }, [api]) // Scroll to the initial index when the dialog opens and API is ready useEffect(() => { if (api) { previousIndexRef.current = initialIndex api.scrollTo(initialIndex, false) // Scroll instantly } }, [api, initialIndex]) return ( {children} Search Videos {query}
{ previousIndexRef.current = initialIndex setCurrent((nextApi?.selectedScrollSnap() ?? initialIndex) + 1) setApi(nextApi) }} className="w-full bg-muted max-h-[60vh]" opts={{ startIndex: initialIndex // Set initial slide }} > {videos.map((video, idx) => { const videoId = video.link.split('v=')[1] return (