"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { createPortal } from "react-dom";
import { MoreVertical } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
const MENU_GAP = 6;
function MenuShortcut({ children }) {
  return /* @__PURE__ */ jsx(
    "kbd",
    {
      "aria-hidden": "true",
      className: "ml-auto inline-flex items-center rounded border border-border bg-muted px-1.5 py-px font-mono text-[10px] font-medium leading-none text-muted-foreground",
      children
    }
  );
}
const ITEM_SHORTCUTS = {
  open: "\u21B5",
  edit: "E",
  duplicate: "\u2318D"
};
function matchesShortcut(itemId, event) {
  if (itemId === "open" && event.key === "Enter") return true;
  if (itemId === "edit" && (event.key === "e" || event.key === "E") && !event.metaKey && !event.ctrlKey) return true;
  if (itemId === "duplicate" && (event.key === "d" || event.key === "D") && (event.metaKey || event.ctrlKey)) return true;
  return false;
}
function DealCardMenu({ items, ariaLabel }) {
  const [open, setOpen] = React.useState(false);
  const [anchor, setAnchor] = React.useState(null);
  const [direction, setDirection] = React.useState("down");
  const btnRef = React.useRef(null);
  const menuRef = React.useRef(null);
  const updatePosition = React.useCallback(() => {
    if (!btnRef.current) return;
    const rect = btnRef.current.getBoundingClientRect();
    setAnchor(rect);
    const spaceBelow = window.innerHeight - rect.bottom;
    const spaceAbove = rect.top;
    setDirection(spaceBelow < 220 && spaceAbove > spaceBelow ? "up" : "down");
  }, []);
  React.useEffect(() => {
    if (!open) return;
    updatePosition();
    requestAnimationFrame(() => {
      const first = menuRef.current?.querySelector('[role="menuitem"]');
      first?.focus();
    });
    function onDocClick(e) {
      const target = e.target;
      if (menuRef.current && !menuRef.current.contains(target) && btnRef.current && !btnRef.current.contains(target)) {
        setOpen(false);
      }
    }
    function onKey(e) {
      if (e.key === "Escape") {
        setOpen(false);
        btnRef.current?.focus();
        return;
      }
      const active = document.activeElement;
      if (active) {
        const tag = active.tagName;
        if (tag === "INPUT" || tag === "TEXTAREA" || active.isContentEditable) return;
      }
      if (!menuRef.current?.contains(active)) return;
      for (const item of items) {
        if (item.id && matchesShortcut(item.id, e)) {
          e.preventDefault();
          setOpen(false);
          item.onSelect?.();
          return;
        }
      }
    }
    function onScrollOrResize() {
      updatePosition();
    }
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    window.addEventListener("scroll", onScrollOrResize, true);
    window.addEventListener("resize", onScrollOrResize);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
      window.removeEventListener("scroll", onScrollOrResize, true);
      window.removeEventListener("resize", onScrollOrResize);
    };
  }, [open, updatePosition]);
  const handleMenuKeyDown = React.useCallback((event) => {
    const items2 = Array.from(
      menuRef.current?.querySelectorAll('[role="menuitem"]') ?? []
    );
    if (items2.length === 0) return;
    const currentIdx = items2.findIndex((el) => el === document.activeElement);
    if (event.key === "ArrowDown") {
      event.preventDefault();
      const next = items2[(currentIdx + 1 + items2.length) % items2.length];
      next?.focus();
    } else if (event.key === "ArrowUp") {
      event.preventDefault();
      const prev = items2[(currentIdx - 1 + items2.length) % items2.length];
      prev?.focus();
    } else if (event.key === "Home") {
      event.preventDefault();
      items2[0]?.focus();
    } else if (event.key === "End") {
      event.preventDefault();
      items2[items2.length - 1]?.focus();
    }
  }, []);
  if (!items.length) return null;
  return /* @__PURE__ */ jsxs("div", { className: "relative inline-flex", "data-card-action": "true", onClick: (event) => event.stopPropagation(), children: [
    /* @__PURE__ */ jsx(
      IconButton,
      {
        ref: btnRef,
        variant: "ghost",
        size: "xs",
        "aria-haspopup": "menu",
        "aria-expanded": open,
        "aria-label": ariaLabel,
        onClick: (event) => {
          event.stopPropagation();
          setOpen((previous) => !previous);
          requestAnimationFrame(updatePosition);
        },
        className: "inline-flex size-4 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
        children: /* @__PURE__ */ jsx(MoreVertical, { className: "size-3.5", "aria-hidden": "true" })
      }
    ),
    open && anchor && typeof document !== "undefined" ? createPortal(
      /* @__PURE__ */ jsx(
        "div",
        {
          ref: menuRef,
          role: "menu",
          onKeyDown: handleMenuKeyDown,
          className: "fixed z-dropdown w-52 max-w-[calc(100vw-1rem)] rounded-md border border-border bg-background p-1.5 shadow-md",
          style: {
            top: direction === "down" ? anchor.bottom + MENU_GAP : anchor.top - MENU_GAP,
            left: Math.min(anchor.right, window.innerWidth - 8),
            transform: `translate(-100%, ${direction === "down" ? "0" : "-100%"})`
          },
          children: items.map((item, idx) => {
            const shortcut = item.id ? ITEM_SHORTCUTS[item.id] : null;
            return /* @__PURE__ */ jsxs(
              Button,
              {
                variant: item.destructive ? "destructive-ghost" : "ghost",
                size: "sm",
                type: "button",
                role: "menuitem",
                onClick: (event) => {
                  event.stopPropagation();
                  setOpen(false);
                  item.onSelect?.();
                },
                className: `flex w-full items-center justify-start rounded-sm px-3 py-2 text-left text-sm leading-5 transition-colors hover:bg-muted focus-visible:bg-muted focus-visible:outline-none ${item.destructive ? "text-status-error-text hover:bg-status-error-bg/30" : "text-foreground"}`,
                children: [
                  /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: item.label }),
                  shortcut ? /* @__PURE__ */ jsx(MenuShortcut, { children: shortcut }) : null
                ]
              },
              item.id ?? `${item.label}-${idx}`
            );
          })
        }
      ),
      document.body
    ) : null
  ] });
}
var DealCardMenu_default = DealCardMenu;
export {
  DealCardMenu,
  DealCardMenu_default as default
};
//# sourceMappingURL=DealCardMenu.js.map
