// src/components/navbar/ActionMenuPortal.jsx
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { clamp } from "../../utils/navbar";
import useOutsidePointerDown from "./useOutsidePointerDown";

// ✅ global event name (one menu open at a time)
const ACTION_MENU_EVENT = "app:actionmenu:open";

export default function ActionMenuPortal({
  open,
  rect,
  onClose,
  children,
  width = 340,
  offset = 10,
}) {
  const menuRef = useRef(null);
  const [pos, setPos] = useState({ top: 0, left: 0 });

  // ✅ stable id for this instance
  const instanceId = useMemo(() => {
    // crypto.randomUUID supported in modern browsers; fallback if not
    return (globalThis.crypto?.randomUUID?.() ?? `am_${Math.random().toString(16).slice(2)}`);
  }, []);

  // ✅ 1) Only ONE menu open globally:
  // - When THIS menu opens => broadcast its id
  // - All others listen => if different id, close themselves
  useEffect(() => {
    const onGlobalOpen = (e) => {
      const openedId = e?.detail?.id;
      if (!openedId) return;
      if (openedId !== instanceId && open) onClose?.();
    };

    document.addEventListener(ACTION_MENU_EVENT, onGlobalOpen);
    return () => document.removeEventListener(ACTION_MENU_EVENT, onGlobalOpen);
  }, [open, onClose, instanceId]);

  useEffect(() => {
    if (!open) return;
    document.dispatchEvent(new CustomEvent(ACTION_MENU_EVENT, { detail: { id: instanceId } }));
  }, [open, instanceId]);

  // ✅ close on outside click
  useOutsidePointerDown(menuRef, () => onClose?.(), open);

  // ✅ close on ESC
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose?.();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  // ✅ calc position based on viewport (FIXED) — not document
  useLayoutEffect(() => {
    if (!open || !rect) return;

    const calc = () => {
      const vh = window.innerHeight;
      const vw = window.innerWidth;

      const menuW = width;
      const menuH = menuRef.current?.offsetHeight || 240;

      let top = rect.bottom + offset;
      let left = rect.right - menuW;

      // اگر پایین جا نشد، ببر بالا
      if (top + menuH > vh - 8) top = rect.top - menuH - offset;

      // clamp داخل صفحه
      top = clamp(top, 8, vh - menuH - 8);
      left = clamp(left, 8, vw - menuW - 8);

      setPos({ top, left });
    };

    calc();
    window.addEventListener("resize", calc);
    return () => window.removeEventListener("resize", calc);
  }, [open, rect, width, offset]);

  if (!open || !rect) return null;

  return createPortal(
    <div
      ref={menuRef}
      style={{
        position: "fixed",
        top: pos.top,
        left: pos.left,
        width,
      }}
      className="pointer-events-auto z-999999 rounded-2xl max-w-[96vw] shadow-xl border border-black/5 dark:border-white/10 bg-[#f2f2f2] dark:bg-[#0b2445]"
      onPointerDown={(e) => e.stopPropagation()}
      onClick={(e) => e.stopPropagation()}
    >
      {children}
    </div>,
    document.body
  );
}
