/* ============================================================
   beedle dataroom — "…" overflow menu (shared)
   Compact dropdown that folds toolbar buttons away on phones.
   Same open/ref/outside-click pattern as ViewAs (shell.jsx) and
   reuses the .menu / .menu-item CSS both pages already ship.
   items: { icon, label, sub, onClick, disabled, danger, checked, badge }
        | { heading: "…" } | { divider: true }   (falsy items skipped)
   badge: a pending count — renders a red pill on the item and a red
   dot on the "…" trigger so the pending state shows while folded.
   btnClass picks the trigger's look (.act, .vbtn, .btn btn-ghost…).
   ============================================================ */
function OverflowMenu({ items, icon = "dots", btnClass = "act", className = "", title, menuStyle }) {
  const [open, setOpen] = React.useState(false);
  const [shift, setShift] = React.useState(0);   // px nudge to keep the menu on-screen
  const ref = React.useRef(null);
  const menuRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, [open]);
  // The menu is right-anchored (CSS: position:absolute; right:0) so it always
  // grows leftward. When the trigger sits mid-screen — e.g. a left-column card
  // in the phone doc grid — that overflows (and clips on) the LEFT edge. Measure
  // the natural rect on open and nudge it back inside an 8px margin of either
  // edge. max-width keeps the menu narrower than the viewport, so one shift fits.
  // We nudge via the `right` offset (not transform — scaleIn animates transform
  // with fill:both, which would clobber it). A +dx rightward move ⇒ right:-dx.
  React.useLayoutEffect(() => {
    if (!open) { setShift(0); return; }
    const el = menuRef.current;
    if (!el) return;
    // shift is reset to 0 on close, so the menu is at its natural right:0 here.
    const r = el.getBoundingClientRect();
    const M = 8;
    let dx = 0;
    if (r.left < M) dx = Math.round(M - r.left);                          // hanging off the left → push right
    else if (r.right > window.innerWidth - M) dx = Math.round(window.innerWidth - M - r.right); // off the right → pull left
    setShift(dx);
  }, [open]);
  const hasBadge = items.filter(Boolean).some(it => !it.heading && !it.divider && it.badge > 0);
  return (
    <div className={"viewas om" + (className ? " " + className : "")} ref={ref} onClick={(e) => e.stopPropagation()}>
      <button className={btnClass} title={title || T("More")} aria-haspopup="menu" aria-expanded={open}
        onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}>
        <Icon name={icon} size={16} />
        {hasBadge && <span className="om-dot" />}
      </button>
      {open && (
        <div className="menu" role="menu" ref={menuRef}
          style={shift ? { ...menuStyle, right: -shift } : menuStyle}>
          {items.filter(Boolean).map((it, i) => {
            if (it.heading) return <div key={i} className="mh">{it.heading}</div>;
            if (it.divider) return <div key={i} className="om-divider" />;
            return (
              <button key={i} className={"menu-item" + (it.danger ? " om-danger" : "")} role="menuitem"
                disabled={it.disabled} style={it.disabled ? { opacity: .45, cursor: "not-allowed" } : {}}
                onClick={() => { if (it.disabled) return; setOpen(false); it.onClick && it.onClick(); }}>
                {it.icon && <span className="om-ico"><Icon name={it.icon} size={15} /></span>}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="nm">{it.label}</div>
                  {it.sub && <div className="ds">{it.sub}</div>}
                </div>
                {it.badge > 0 && <span className="count-badge">{it.badge}</span>}
                {it.checked && <Icon name="check" size={16} className="ck" sw={2.4} />}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
Object.assign(window, { OverflowMenu });
