// packages/core/src/components/dialog/dialog-close.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 { DialogCloseProps } from "./dialog.props";

export type { DialogCloseProps };

/** Closes the dialog when clicked. Supports polymorphic rendering via `as`. */
export function DialogClose(props: DialogCloseProps): 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(false);
  };

  const closeProps = mergeProps(rest, { onClick: handleClick });
  return (
    <Dynamic component={local.as ?? "button"} {...closeProps}>
      {local.children}
    </Dynamic>
  );
}
