"use client";
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import React__default, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Plus, Copy, Scissors, ClipboardPaste, CopyPlus, Trash } from 'lucide-react';
import { useEditorStore } from '../../../../lib/ui-builder/store/editor-store.mjs';
import { useLayerStore } from '../../../../lib/ui-builder/store/layer-store.mjs';
import { canComponentAcceptChildren } from '../../../../lib/ui-builder/store/schema-utils.mjs';
import { SHORTCUTS } from '../../../../lib/ui-builder/shortcuts/shortcut-registry.mjs';
import { useGlobalLayerActions } from '../../../../lib/ui-builder/hooks/use-layer-actions.mjs';
import { canPasteLayer } from '../../../../lib/ui-builder/utils/paste-validation.mjs';
import { AddComponentsPopover } from './add-component-popover.mjs';
import { cn } from '../../../../lib/utils.mjs';
import { useFrame } from '../canvas/auto-frame.mjs';
import '../../../../../../../node_modules/.pnpm/@dnd-kit_core@6.3.1_react-dom@19.2.0_react@19.2.0__react@19.2.0/node_modules/@dnd-kit/core/dist/core.esm.mjs';
import '../../../../lib/ui-builder/context/dnd-context-colission-utils.mjs';
import { useDndContext } from '../../../../lib/ui-builder/context/dnd-contexts.mjs';
import { useFloating } from '../../../../../../../node_modules/.pnpm/@floating-ui_react@0.27.16_react-dom@19.2.0_react@19.2.0__react@19.2.0/node_modules/@floating-ui/react/dist/floating-ui.react.mjs';
import { offset, flip, shift, limitShift } from '../../../../../../../node_modules/.pnpm/@floating-ui_react-dom@2.1.6_react-dom@19.2.0_react@19.2.0__react@19.2.0/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs';

const LayerContextMenuPortal = () => {
  const contextMenu = useEditorStore((state) => state.contextMenu);
  const closeContextMenu = useEditorStore((state) => state.closeContextMenu);
  const selectedLayerId = useLayerStore((state) => state.selectedLayerId);
  const { isDragging } = useDndContext();
  const [mounted, setMounted] = useState(false);
  const contextMenuLayerIdRef = useRef(null);
  const frameContext = useFrame();
  const { refs, floatingStyles } = useFloating({
    placement: "bottom-start",
    middleware: [
      offset(2),
      // Small offset from cursor
      flip({
        fallbackPlacements: ["top-start", "bottom-end", "top-end"],
        padding: 8
      }),
      shift({
        crossAxis: true,
        limiter: limitShift(),
        padding: 8
      })
    ]
  });
  useEffect(() => {
    if (!contextMenu.open) return;
    const virtualReference = {
      getBoundingClientRect: () => ({
        x: contextMenu.x,
        y: contextMenu.y,
        width: 0,
        height: 0,
        top: contextMenu.y,
        left: contextMenu.x,
        right: contextMenu.x,
        bottom: contextMenu.y
      })
    };
    refs.setPositionReference(virtualReference);
  }, [contextMenu.open, contextMenu.x, contextMenu.y, refs]);
  useEffect(() => {
    setMounted(true);
  }, []);
  useEffect(() => {
    if (contextMenu.open && contextMenu.layerId) {
      contextMenuLayerIdRef.current = contextMenu.layerId;
    } else {
      contextMenuLayerIdRef.current = null;
    }
  }, [contextMenu.open, contextMenu.layerId]);
  useEffect(() => {
    if (contextMenu.open && contextMenuLayerIdRef.current && selectedLayerId !== contextMenuLayerIdRef.current) {
      closeContextMenu();
    }
  }, [selectedLayerId, contextMenu.open, closeContextMenu]);
  useEffect(() => {
    if (isDragging && contextMenu.open) {
      closeContextMenu();
    }
  }, [isDragging, contextMenu.open, closeContextMenu]);
  useEffect(() => {
    if (!contextMenu.open) return;
    const handleClickOutside = (e) => {
      const floatingEl = refs.floating.current;
      if (floatingEl && !floatingEl.contains(e.target)) {
        closeContextMenu();
      }
    };
    const handleContextMenuOutside = (e) => {
      const floatingEl = refs.floating.current;
      if (floatingEl && !floatingEl.contains(e.target)) {
        closeContextMenu();
      }
    };
    const targetDoc = frameContext.document ?? document;
    targetDoc.addEventListener("mousedown", handleClickOutside);
    targetDoc.addEventListener("contextmenu", handleContextMenuOutside);
    return () => {
      targetDoc.removeEventListener("mousedown", handleClickOutside);
      targetDoc.removeEventListener("contextmenu", handleContextMenuOutside);
    };
  }, [contextMenu.open, closeContextMenu, refs.floating, frameContext.document]);
  useEffect(() => {
    if (!contextMenu.open) return;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        closeContextMenu();
      }
    };
    const targetDoc = frameContext.document ?? document;
    targetDoc.addEventListener("keydown", handleKeyDown);
    return () => targetDoc.removeEventListener("keydown", handleKeyDown);
  }, [contextMenu.open, closeContextMenu, frameContext.document]);
  if (!mounted || !contextMenu.open || !contextMenu.layerId) {
    return null;
  }
  const portalTarget = frameContext.document?.body || document.body;
  const menuContent = /* @__PURE__ */ jsx(
    "div",
    {
      ref: refs.setFloating,
      "data-testid": "layer-context-menu-portal",
      className: "z-[10000] min-w-[14rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95",
      style: floatingStyles,
      children: /* @__PURE__ */ jsx(
        ContextMenuPortalItems,
        {
          layerId: contextMenu.layerId,
          onAction: closeContextMenu
        }
      )
    }
  );
  return createPortal(menuContent, portalTarget);
};
const ContextMenuPortalItems = ({
  layerId,
  onAction
}) => {
  const selectedLayer = useLayerStore((state) => state.findLayerById(layerId));
  const findLayerById = useLayerStore((state) => state.findLayerById);
  const componentRegistry = useEditorStore((state) => state.registry);
  const clipboardLayer = useEditorStore((state) => state.clipboard.layer);
  const {
    canDuplicate,
    canDelete,
    canCut,
    handleCopy,
    handleCut,
    handlePaste,
    handleDelete,
    handleDuplicate
  } = useGlobalLayerActions(layerId);
  const canPaste = React__default.useMemo(() => {
    if (!clipboardLayer || !selectedLayer) return false;
    return canPasteLayer(clipboardLayer, layerId, componentRegistry, findLayerById);
  }, [clipboardLayer, layerId, componentRegistry, findLayerById, selectedLayer]);
  const canRenderAddChild = React__default.useMemo(() => {
    if (!selectedLayer) return false;
    const componentDef = componentRegistry[selectedLayer.type];
    if (!componentDef) return false;
    return canComponentAcceptChildren(componentDef.schema);
  }, [selectedLayer, componentRegistry]);
  const handleCopyClick = useCallback(() => {
    handleCopy();
    onAction();
  }, [handleCopy, onAction]);
  const handleCutClick = useCallback(() => {
    handleCut();
    onAction();
  }, [handleCut, onAction]);
  const handlePasteClick = useCallback(() => {
    handlePaste();
    onAction();
  }, [handlePaste, onAction]);
  const handleDuplicateClick = useCallback(() => {
    handleDuplicate();
    onAction();
  }, [handleDuplicate, onAction]);
  const handleDeleteClick = useCallback(() => {
    handleDelete();
    onAction();
  }, [handleDelete, onAction]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    canRenderAddChild && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(AddComponentsPopover, { parentLayerId: layerId, children: /* @__PURE__ */ jsxs(MenuItem, { onClick: (e) => e.stopPropagation(), children: [
        /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
        "Add Child"
      ] }) }),
      /* @__PURE__ */ jsx(MenuSeparator, {})
    ] }),
    /* @__PURE__ */ jsxs(MenuItem, { onClick: handleCopyClick, children: [
      /* @__PURE__ */ jsx(Copy, { className: "mr-2 h-4 w-4" }),
      "Copy",
      /* @__PURE__ */ jsx(MenuShortcut, { children: SHORTCUTS.copy.shortcutDisplay })
    ] }),
    canCut && /* @__PURE__ */ jsxs(MenuItem, { onClick: handleCutClick, children: [
      /* @__PURE__ */ jsx(Scissors, { className: "mr-2 h-4 w-4" }),
      "Cut",
      /* @__PURE__ */ jsx(MenuShortcut, { children: SHORTCUTS.cut.shortcutDisplay })
    ] }),
    /* @__PURE__ */ jsxs(MenuItem, { onClick: handlePasteClick, disabled: !canPaste, children: [
      /* @__PURE__ */ jsx(ClipboardPaste, { className: "mr-2 h-4 w-4" }),
      "Paste",
      /* @__PURE__ */ jsx(MenuShortcut, { children: SHORTCUTS.paste.shortcutDisplay })
    ] }),
    /* @__PURE__ */ jsx(MenuSeparator, {}),
    canDuplicate && /* @__PURE__ */ jsxs(MenuItem, { onClick: handleDuplicateClick, children: [
      /* @__PURE__ */ jsx(CopyPlus, { className: "mr-2 h-4 w-4" }),
      "Duplicate",
      /* @__PURE__ */ jsx(MenuShortcut, { children: SHORTCUTS.duplicate.shortcutDisplay })
    ] }),
    canDelete && /* @__PURE__ */ jsxs(
      MenuItem,
      {
        onClick: handleDeleteClick,
        className: "text-destructive focus:text-destructive",
        children: [
          /* @__PURE__ */ jsx(Trash, { className: "mr-2 h-4 w-4" }),
          "Delete",
          /* @__PURE__ */ jsx(MenuShortcut, { children: SHORTCUTS.delete.shortcutDisplay })
        ]
      }
    )
  ] });
};
const MenuItem = ({
  children,
  onClick,
  disabled,
  className
}) => {
  return /* @__PURE__ */ jsx(
    "div",
    {
      role: "menuitem",
      "data-testid": "menu-item",
      onClick: disabled ? void 0 : onClick,
      className: cn(
        "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
        disabled && "pointer-events-none opacity-50",
        className
      ),
      children
    }
  );
};
const MenuSeparator = () => {
  return /* @__PURE__ */ jsx("div", { className: "-mx-1 my-1 h-px bg-muted", "data-testid": "menu-separator" });
};
const MenuShortcut = ({ children }) => {
  return /* @__PURE__ */ jsx("span", { className: "ml-auto text-xs tracking-widest opacity-60", "data-testid": "menu-shortcut", children });
};

export { LayerContextMenuPortal };
