// packages/core/src/components/dialog/dialog-trigger.tsx
import type { JSX } from "solid-js";
import { mergeProps, splitProps } from "solid-js";
import { Dynamic } from "solid-js/web";
import { useInternalDialogContext } from "./dialog-context";
import type { DialogTriggerProps } from "./dialog.props";

export type { DialogTriggerProps };

/** Opens the dialog when clicked. Supports polymorphic rendering via `as` and children-as-function. */
export function DialogTrigger(props: DialogTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["as", "children", "onClick"]);
  const ctx = useInternalDialogContext();

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

  const triggerProps = mergeProps(rest, {
    "aria-haspopup": "dialog" as const,
    "aria-expanded": ctx.isOpen(),
    "aria-controls": ctx.contentId(),
    "data-state": ctx.isOpen() ? "open" : "closed",
    onClick: handleClick,
  });

  if (typeof local.children === "function") {
    return <>{local.children(triggerProps as JSX.HTMLAttributes<HTMLElement>)}</>;
  }

  return (
    <Dynamic component={local.as ?? "button"} {...triggerProps}>
      {local.children}
    </Dynamic>
  );
}
