import { forwardRef, Children, cloneElement } from "react";

/**
 * Accordion
 *
 * variant:   "default" | "plus" | "ghost"
 * exclusive: string - shared name attribute on all child <details>, enforcing one-open-at-a-time
 */
export const Accordion = forwardRef(function Accordion(
  { variant = "default", exclusive, className = "", children, ...props },
  ref
) {
  const classes = [
    "prs-accordion",
    variant === "plus" && "prs-accordion-plus",
    variant === "ghost" && "prs-accordion-ghost",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <div ref={ref} className={classes} {...props}>
      {exclusive
        ? Children.map(children, (child) =>
            child ? cloneElement(child, { _exclusive: exclusive }) : child
          )
        : children}
    </div>
  );
});
 
/**
 * AccordionItem
 *
 * summary:    string | ReactNode - always-visible header
 * content:    string | ReactNode - collapsible body (also accepts children)
 * open:       boolean - start open
 * _exclusive: string - injected by <Accordion exclusive>; do not set manually
 */
export const AccordionItem = forwardRef(function AccordionItem(
  {
    summary,
    content,
    open = false,
    className = "",
    // internal - injected by <Accordion exclusive="…">
    _exclusive,
    children,
    ...props
  },
  ref
) {
  const detailsProps = {
    ref,
    className: className || undefined,
    ...(open ? { open: true } : {}),
    ...(_exclusive ? { name: _exclusive } : {}),
    ...props,
  };
 
  return (
    <details {...detailsProps}>
      <summary>{summary}</summary>
      <div className="prs-accordion-content">
        {content ?? children}
      </div>
    </details>
  );
});
