"use client"

import { cx } from "class-variance-authority"
import { useEffect, useState } from "react"

import { useCarousel } from "./CarouselContext"

import styles from "./carousel.module.css"

export function CarouselDots({ className }: { className?: string }) {
  const { selectedIndex, api } = useCarousel()
  const [scrollSnaps, setScrollSnaps] = useState<number[]>([])

  // Update scroll snaps when the carousel is initialized or viewport changes
  useEffect(() => {
    if (!api) return

    const onInit = () => {
      setScrollSnaps(api.scrollSnapList())
    }

    onInit()
    api.on("reInit", onInit)

    return () => {
      api.off("reInit", onInit)
    }
  }, [api])

  // Don't render dots if we have 1 or fewer scroll positions
  if (scrollSnaps.length <= 1) return null

  return (
    <div className={cx(styles.dots, className)}>
      {scrollSnaps.map((_, index) => (
        <div
          key={index}
          className={styles.dot}
          data-active={index === selectedIndex}
          aria-hidden="true"
        />
      ))}
    </div>
  )
}
