import { Children, cloneElement, isValidElement } from 'react'

import type { VariantProps } from 'class-variance-authority'

import type { AccordionItemProps } from './AccordionItem'
import { accordionVariants } from './variants'

interface AccordionProps
  extends React.HtmlHTMLAttributes<HTMLUListElement>,
    VariantProps<typeof accordionVariants> {}

export default function Accordion({
  children,
  className,
  type,
}: AccordionProps) {
  return (
    <ul className={accordionVariants({ className, type })}>
      {Children.map(children, (child) => {
        if (isValidElement<AccordionItemProps>(child)) {
          return cloneElement(child, { type })
        } else {
          return child
        }
      })}
    </ul>
  )
}
