import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useCollapsibleContext } from "./collapsible-context";

export interface CollapsibleTriggerProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  children?: JSX.Element;
}

/** Button that toggles the Collapsible open/closed. */
export function CollapsibleTrigger(props: CollapsibleTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children"]);
  const ctx = useCollapsibleContext();

  return (
    <button
      type="button"
      aria-expanded={ctx.isOpen() ? "true" : "false"}
      aria-controls={ctx.contentId()}
      data-state={ctx.isOpen() ? "open" : "closed"}
      disabled={ctx.disabled()}
      {...rest}
      onClick={(e) => {
        if (typeof rest.onClick === "function") rest.onClick(e);
        if (!ctx.disabled()) ctx.setOpen(!ctx.isOpen());
      }}
    >
      {local.children}
    </button>
  );
}
