"use client"; import { useCallback, useEffect, useState } from "react"; import Image from "next/image"; import useEmblaCarousel from "embla-carousel-react"; import { CaretLeftIcon, CaretRightIcon } from "@phosphor-icons/react/dist/ssr"; import styles from "./Slider.module.css"; type Slide = { heading: string; text: string; image: string; }; type SliderProps = { slides: Slide[]; imageAlt: string; }; export function Slider({ slides, imageAlt }: SliderProps) { const [emblaRef, emblaApi] = useEmblaCarousel({ align: "start", loop: false, duration: 28, }); const [selectedIndex, setSelectedIndex] = useState(0); const [scrollSnaps, setScrollSnaps] = useState([]); const [canScrollPrev, setCanScrollPrev] = useState(false); const [canScrollNext, setCanScrollNext] = useState(false); const scrollPrevious = useCallback(() => { emblaApi?.scrollPrev(); }, [emblaApi]); const scrollNext = useCallback(() => { emblaApi?.scrollNext(); }, [emblaApi]); const scrollTo = useCallback( (index: number) => { emblaApi?.scrollTo(index); }, [emblaApi], ); const updateSelectedSlide = useCallback(() => { if (!emblaApi) { return; } setSelectedIndex(emblaApi.selectedScrollSnap()); setCanScrollPrev(emblaApi.canScrollPrev()); setCanScrollNext(emblaApi.canScrollNext()); }, [emblaApi]); const initializeNavigation = useCallback(() => { if (!emblaApi) { return; } setScrollSnaps(emblaApi.scrollSnapList()); updateSelectedSlide(); }, [emblaApi, updateSelectedSlide]); useEffect(() => { if (!emblaApi) { return; } initializeNavigation(); emblaApi.on("reInit", initializeNavigation); emblaApi.on("select", updateSelectedSlide); return () => { emblaApi.off("reInit", initializeNavigation); emblaApi.off("select", updateSelectedSlide); }; }, [emblaApi, initializeNavigation, updateSelectedSlide]); if (slides.length === 0) { return null; } return (
{slides.map((slide, index) => (

{slide.heading}

{slide.text}

{imageAlt}
))}
{slides.length > 1 && (
{scrollSnaps.map((_, index) => (
)}
); }