import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useInternalComboboxContext } from "./combobox-context";

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

/** Optional toggle button for Combobox. Not in tab order; input is primary. */
export function ComboboxTrigger(props: ComboboxTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick"]);
  const ctx = useInternalComboboxContext();

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

  return (
    <button
      type="button"
      tabIndex={-1}
      aria-label="Toggle"
      aria-expanded={ctx.isOpen()}
      aria-controls={ctx.isOpen() ? ctx.contentId : undefined}
      data-state={ctx.isOpen() ? "open" : "closed"}
      disabled={ctx.disabled()}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </button>
  );
}
