"use client";
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';

export default function WinbarMoveMenu({ x, y, spaces, activeSpaceId, onMove, onClose }) {
  const ref = useRef(null);
  const [pos, setPos] = useState({ left: x, top: y });

  useEffect(() => {
    function onDocPointer(e) {
      if (!ref.current?.contains(e.target)) onClose();
    }
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('pointerdown', onDocPointer);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('pointerdown', onDocPointer);
      document.removeEventListener('keydown', onKey);
    };
  }, [onClose]);

  // After mount, measure and clamp so the menu never escapes the viewport.
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const margin = 8;
    let left = x;
    let top = y;
    if (left + rect.width + margin > window.innerWidth) left = Math.max(margin, window.innerWidth - rect.width - margin);
    if (top + rect.height + margin > window.innerHeight) top = Math.max(margin, window.innerHeight - rect.height - margin);
    setPos({ left, top });
  }, [x, y]);

  const others = spaces.filter(s => s.id !== activeSpaceId);

  // Portal to body so position:fixed is unaffected by transformed/filtered ancestors.
  if (typeof document === 'undefined') return null;
  return createPortal(
    <div className="winbar-move-menu" ref={ref} style={{ left: pos.left, top: pos.top }} onClick={e => e.stopPropagation()}>
      <div className="winbar-move-menu-label">Move to space</div>
      {others.length === 0 ? (
        <div className="winbar-move-menu-empty">No other spaces</div>
      ) : (
        others.map(s => (
          <button key={s.id} type="button" onClick={() => { onMove(s.id); onClose(); }}>{s.name}</button>
        ))
      )}
    </div>,
    document.body
  );
}
