// packages/core/src/components/popover/popover-close.tsx
import type { Component, JSX } from "solid-js";
import { mergeProps, splitProps } from "solid-js";
import { Dynamic } from "solid-js/web";
import { useInternalPopoverContext } from "./popover-context";

export interface PopoverCloseProps extends JSX.HTMLAttributes<HTMLButtonElement> {
  /** Render as a different element or component. */
  as?: string | Component;
  children?: JSX.Element;
}

/** Closes the popover when clicked. Supports polymorphic rendering via `as`. */
export function PopoverClose(props: PopoverCloseProps): JSX.Element {
  const [local, rest] = splitProps(props, ["as", "children", "onClick"]);
  const ctx = useInternalPopoverContext();

  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>
  );
}
