import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useInternalContextMenuContext } from "./context-menu-context";

export interface ContextMenuTriggerProps extends JSX.HTMLAttributes<HTMLDivElement> {
  children?: JSX.Element;
}

/**
 * Area that responds to right-click (contextmenu) to open the ContextMenu.
 * Does NOT render aria-haspopup since context menus are discoverable by convention.
 */
export function ContextMenuTrigger(props: ContextMenuTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onContextMenu"]);
  const ctx = useInternalContextMenuContext();

  const handleContextMenu: JSX.EventHandler<HTMLDivElement, PointerEvent> = (e) => {
    e.preventDefault();
    if (typeof local.onContextMenu === "function") local.onContextMenu(e);
    ctx.setAnchorPosition(e.clientX, e.clientY);
    ctx.open();
  };

  return (
    <div
      data-state={ctx.isOpen() ? "open" : "closed"}
      onContextMenu={handleContextMenu}
      {...rest}
    >
      {local.children}
    </div>
  );
}
