import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useInternalDrawerContext } from "./drawer-context";

/** Props for Drawer.Trigger. */
export interface DrawerTriggerProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  children?: JSX.Element;
}

/**
 * Opens the Drawer when clicked.
 */
export function DrawerTrigger(props: DrawerTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick"]);
  const ctx = useInternalDrawerContext();

  const handleClick: JSX.EventHandler<HTMLButtonElement, MouseEvent> = (e) => {
    if (typeof local.onClick === "function") local.onClick(e);
    ctx.setOpen(!ctx.isOpen());
  };

  return (
    <button
      type="button"
      aria-haspopup="dialog"
      aria-expanded={ctx.isOpen() ? "true" : "false"}
      aria-controls={ctx.contentId()}
      data-state={ctx.isOpen() ? "open" : "closed"}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </button>
  );
}
