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

// ✅ از همین هوکی که تو navbar داری استفاده کن
import useOutsidePointerDown from "../navbar/useOutsidePointerDown";

// ✅ همون ایونت سراسری => فقط یکی تو کل صفحه باز می‌مونه
const MENU_EVENT = "app:actionmenu:open";

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

  const instanceId = useMemo(() => {
    return globalThis.crypto?.randomUUID?.() ?? `dp_${Math.random().toString(16).slice(2)}`;
  }, []);

  // ✅ only one open globally
  useEffect(() => {
    const onGlobalOpen = (e) => {
      const openedId = e?.detail?.id;
      if (!openedId) return;
      if (openedId !== instanceId && open) onClose?.();
    };
    document.addEventListener(MENU_EVENT, onGlobalOpen);
    return () => document.removeEventListener(MENU_EVENT, onGlobalOpen);
  }, [open, onClose, instanceId]);

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

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

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

  // ✅ fixed position by rect (viewport)
  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;

      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 }}
      dir="rtl"
      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-[#001F3F]"
      onPointerDown={(e) => e.stopPropagation()}
      onClick={(e) => e.stopPropagation()}
    >
      {children}
    </div>,
    document.body
  );
}
