import * as React from "react";

export interface AccordionProps {
  title: React.ReactNode;
  /** Right-aligned header value shown next to the title. */
  summary?: React.ReactNode;
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** 2 = nested, indented sub-accordion with smaller header font. */
  level?: 1 | 2;
  children: React.ReactNode;
  className?: string;
}

export function Accordion({
  title,
  summary,
  open,
  defaultOpen = false,
  onOpenChange,
  level = 1,
  children,
  className,
}: AccordionProps) {
  const [internalOpen, setInternalOpen] = React.useState(defaultOpen);
  const isControlled = open !== undefined;
  const isOpen = isControlled ? open : internalOpen;

  const toggle = () => {
    const next = !isOpen;
    if (!isControlled) setInternalOpen(next);
    onOpenChange?.(next);
  };

  const classes = ["ads-accordion"];
  if (level === 2) classes.push("ads-accordion--lvl2");
  if (className) classes.push(className);

  return (
    <div className={classes.join(" ")}>
      <button type="button" className="ads-acc-h" onClick={toggle} aria-expanded={isOpen}>
        <span className="ads-acc-h__k">{title}</span>
        {summary !== undefined && <span className="ads-acc-h__v">{summary}</span>}
        <span className="ads-mark" aria-hidden />
      </button>
      <div className={isOpen ? "ads-acc-b ads-acc-b--on" : "ads-acc-b"}>{children}</div>
    </div>
  );
}
