"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const ReactDOM = require('react-dom');
const LucideIcons = require('lucide-react');
const editorStore = require('../../../../lib/ui-builder/store/editor-store.cjs');
const layerStore = require('../../../../lib/ui-builder/store/layer-store.cjs');
const schemaUtils = require('../../../../lib/ui-builder/store/schema-utils.cjs');
const shortcutRegistry = require('../../../../lib/ui-builder/shortcuts/shortcut-registry.cjs');
const useLayerActions = require('../../../../lib/ui-builder/hooks/use-layer-actions.cjs');
const pasteValidation = require('../../../../lib/ui-builder/utils/paste-validation.cjs');
const addComponentPopover = require('./add-component-popover.cjs');
const utils = require('../../../../lib/utils.cjs');
const autoFrame = require('../canvas/auto-frame.cjs');
require('../../../../../../../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.cjs');
require('../../../../lib/ui-builder/context/dnd-context-colission-utils.cjs');
const dndContexts = require('../../../../lib/ui-builder/context/dnd-contexts.cjs');
const floatingUi_react = require('../../../../../../../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.cjs');
const floatingUi_reactDom = require('../../../../../../../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.cjs');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }

const React__default = /*#__PURE__*/_interopDefaultCompat(React);

const LayerContextMenuPortal = () => {
  const contextMenu = editorStore.useEditorStore((state) => state.contextMenu);
  const closeContextMenu = editorStore.useEditorStore((state) => state.closeContextMenu);
  const selectedLayerId = layerStore.useLayerStore((state) => state.selectedLayerId);
  const { isDragging } = dndContexts.useDndContext();
  const [mounted, setMounted] = React.useState(false);
  const contextMenuLayerIdRef = React.useRef(null);
  const frameContext = autoFrame.useFrame();
  const { refs, floatingStyles } = floatingUi_react.useFloating({
    placement: "bottom-start",
    middleware: [
      floatingUi_reactDom.offset(2),
      // Small offset from cursor
      floatingUi_reactDom.flip({
        fallbackPlacements: ["top-start", "bottom-end", "top-end"],
        padding: 8
      }),
      floatingUi_reactDom.shift({
        crossAxis: true,
        limiter: floatingUi_reactDom.limitShift(),
        padding: 8
      })
    ]
  });
  React.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]);
  React.useEffect(() => {
    setMounted(true);
  }, []);
  React.useEffect(() => {
    if (contextMenu.open && contextMenu.layerId) {
      contextMenuLayerIdRef.current = contextMenu.layerId;
    } else {
      contextMenuLayerIdRef.current = null;
    }
  }, [contextMenu.open, contextMenu.layerId]);
  React.useEffect(() => {
    if (contextMenu.open && contextMenuLayerIdRef.current && selectedLayerId !== contextMenuLayerIdRef.current) {
      closeContextMenu();
    }
  }, [selectedLayerId, contextMenu.open, closeContextMenu]);
  React.useEffect(() => {
    if (isDragging && contextMenu.open) {
      closeContextMenu();
    }
  }, [isDragging, contextMenu.open, closeContextMenu]);
  React.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]);
  React.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__ */ jsxRuntime.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__ */ jsxRuntime.jsx(
        ContextMenuPortalItems,
        {
          layerId: contextMenu.layerId,
          onAction: closeContextMenu
        }
      )
    }
  );
  return ReactDOM.createPortal(menuContent, portalTarget);
};
const ContextMenuPortalItems = ({
  layerId,
  onAction
}) => {
  const selectedLayer = layerStore.useLayerStore((state) => state.findLayerById(layerId));
  const findLayerById = layerStore.useLayerStore((state) => state.findLayerById);
  const componentRegistry = editorStore.useEditorStore((state) => state.registry);
  const clipboardLayer = editorStore.useEditorStore((state) => state.clipboard.layer);
  const {
    canDuplicate,
    canDelete,
    canCut,
    handleCopy,
    handleCut,
    handlePaste,
    handleDelete,
    handleDuplicate
  } = useLayerActions.useGlobalLayerActions(layerId);
  const canPaste = React__default.useMemo(() => {
    if (!clipboardLayer || !selectedLayer) return false;
    return pasteValidation.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 schemaUtils.canComponentAcceptChildren(componentDef.schema);
  }, [selectedLayer, componentRegistry]);
  const handleCopyClick = React.useCallback(() => {
    handleCopy();
    onAction();
  }, [handleCopy, onAction]);
  const handleCutClick = React.useCallback(() => {
    handleCut();
    onAction();
  }, [handleCut, onAction]);
  const handlePasteClick = React.useCallback(() => {
    handlePaste();
    onAction();
  }, [handlePaste, onAction]);
  const handleDuplicateClick = React.useCallback(() => {
    handleDuplicate();
    onAction();
  }, [handleDuplicate, onAction]);
  const handleDeleteClick = React.useCallback(() => {
    handleDelete();
    onAction();
  }, [handleDelete, onAction]);
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    canRenderAddChild && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(addComponentPopover.AddComponentsPopover, { parentLayerId: layerId, children: /* @__PURE__ */ jsxRuntime.jsxs(MenuItem, { onClick: (e) => e.stopPropagation(), children: [
        /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Plus, { className: "mr-2 h-4 w-4" }),
        "Add Child"
      ] }) }),
      /* @__PURE__ */ jsxRuntime.jsx(MenuSeparator, {})
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs(MenuItem, { onClick: handleCopyClick, children: [
      /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Copy, { className: "mr-2 h-4 w-4" }),
      "Copy",
      /* @__PURE__ */ jsxRuntime.jsx(MenuShortcut, { children: shortcutRegistry.SHORTCUTS.copy.shortcutDisplay })
    ] }),
    canCut && /* @__PURE__ */ jsxRuntime.jsxs(MenuItem, { onClick: handleCutClick, children: [
      /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Scissors, { className: "mr-2 h-4 w-4" }),
      "Cut",
      /* @__PURE__ */ jsxRuntime.jsx(MenuShortcut, { children: shortcutRegistry.SHORTCUTS.cut.shortcutDisplay })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs(MenuItem, { onClick: handlePasteClick, disabled: !canPaste, children: [
      /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ClipboardPaste, { className: "mr-2 h-4 w-4" }),
      "Paste",
      /* @__PURE__ */ jsxRuntime.jsx(MenuShortcut, { children: shortcutRegistry.SHORTCUTS.paste.shortcutDisplay })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsx(MenuSeparator, {}),
    canDuplicate && /* @__PURE__ */ jsxRuntime.jsxs(MenuItem, { onClick: handleDuplicateClick, children: [
      /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.CopyPlus, { className: "mr-2 h-4 w-4" }),
      "Duplicate",
      /* @__PURE__ */ jsxRuntime.jsx(MenuShortcut, { children: shortcutRegistry.SHORTCUTS.duplicate.shortcutDisplay })
    ] }),
    canDelete && /* @__PURE__ */ jsxRuntime.jsxs(
      MenuItem,
      {
        onClick: handleDeleteClick,
        className: "text-destructive focus:text-destructive",
        children: [
          /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Trash, { className: "mr-2 h-4 w-4" }),
          "Delete",
          /* @__PURE__ */ jsxRuntime.jsx(MenuShortcut, { children: shortcutRegistry.SHORTCUTS.delete.shortcutDisplay })
        ]
      }
    )
  ] });
};
const MenuItem = ({
  children,
  onClick,
  disabled,
  className
}) => {
  return /* @__PURE__ */ jsxRuntime.jsx(
    "div",
    {
      role: "menuitem",
      "data-testid": "menu-item",
      onClick: disabled ? void 0 : onClick,
      className: utils.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__ */ jsxRuntime.jsx("div", { className: "-mx-1 my-1 h-px bg-muted", "data-testid": "menu-separator" });
};
const MenuShortcut = ({ children }) => {
  return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "ml-auto text-xs tracking-widest opacity-60", "data-testid": "menu-shortcut", children });
};

exports.LayerContextMenuPortal = LayerContextMenuPortal;
