import React from "react";

export function ContextMenu({ items = [], className = "", children }) {
  const [pos, setPos] = React.useState(null);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!pos) return undefined;
    const away = () => setPos(null);
    document.addEventListener("mousedown", away);
    return () => document.removeEventListener("mousedown", away);
  }, [pos]);
  return (
    <div ref={ref} className={className} style={{ position: "relative" }} data-slot="context-menu"
      onContextMenu={(e) => { e.preventDefault(); const r = ref.current.getBoundingClientRect(); setPos({ x: e.clientX - r.left, y: e.clientY - r.top }); }}>
      {children}
      {pos ? (
        <div role="menu" className="o-popup o-menu" data-slot="context-menu-popup" style={{ position: "absolute", zIndex: 50, left: pos.x, top: pos.y, minWidth: "10rem" }}>
          {items.map((item, i) => (item.separator
            ? <div key={"s" + i} className="o-menu__separator" role="separator" />
            : <div key={item.label} role="menuitem" tabIndex={-1} className={["o-menu__item", item.variant === "destructive" ? "o-menu__item--destructive" : ""].filter(Boolean).join(" ")}
                onClick={() => { setPos(null); if (item.onSelect) item.onSelect(); }}>{item.icon}{item.label}{item.shortcut ? <span className="o-menu__shortcut">{item.shortcut}</span> : null}</div>))}
        </div>
      ) : null}
    </div>
  );
}
