import { useLayoutEffect, useRef, useState } from 'react';

/**
 * Right-click menu for the file trees. Rendered as a fixed element over a
 * transparent overlay: the overlay eats the outside click/scroll that should
 * dismiss the menu, so the tree underneath never sees it.
 */
export function TreeContextMenu({ x, y, items, onClose }) {
  const menuRef = useRef(null);
  const [pos, setPos] = useState({ x, y });

  // Clamp to the viewport after first paint (menu size isn't known before).
  useLayoutEffect(() => {
    const el = menuRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    setPos({
      x: Math.max(4, Math.min(x, window.innerWidth - rect.width - 4)),
      y: Math.max(4, Math.min(y, window.innerHeight - rect.height - 4)),
    });
  }, [x, y]);

  return (
    <div
      className="context-menu-overlay"
      onMouseDown={onClose}
      onContextMenu={(e) => {
        e.preventDefault();
        onClose();
      }}
      onWheel={onClose}
      onKeyDown={(e) => {
        if (e.key === 'Escape') onClose();
      }}
      tabIndex={-1}
      ref={(el) => el?.focus()}
    >
      <div
        ref={menuRef}
        className="context-menu"
        style={{ left: pos.x, top: pos.y }}
        onMouseDown={(e) => e.stopPropagation()}
        role="menu"
      >
        {items.map((item) =>
          item.separator ? (
            <div key={item.key} className="context-menu-separator" role="separator" />
          ) : (
            <button
              key={item.key}
              type="button"
              role="menuitem"
              className={`context-menu-item${item.disabled ? ' context-menu-item--disabled' : ''}`}
              aria-disabled={item.disabled || undefined}
              tabIndex={item.disabled ? -1 : undefined}
              onClick={() => {
                if (item.disabled) return;
                onClose();
                item.onClick?.();
              }}
            >
              {item.icon ? <img src={item.icon} alt="" className="context-menu-icon" /> : null}
              <span>{item.label}</span>
            </button>
          )
        )}
      </div>
    </div>
  );
}
