import { j as jsxRuntimeExports } from "../../../../../_virtual/jsx-runtime.js";
import { useRef, useState, useEffect, useCallback, startTransition } from "react";
import { useSelectedBrickId, usePreviewMode, usePanel, useEditorHelpers, useDraggingBrickType } from "../../../../../use-editor.js";
import "../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import { useFloating, useHover, safePolygon, useInteractions, useMergeRefs, FloatingPortal } from "../../../../../node_modules/.pnpm/@floating-ui_react@0.27.5_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@floating-ui/react/dist/floating-ui.react.js";
import "../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/react-hot-toast/dist/index.js";
import BrickComponent from "../../shared/components/BrickComponent.js";
import { useBrickWrapperStyle } from "../../shared/hooks/use-brick-style.js";
import { useBrickManifest } from "../../shared/hooks/use-brick-manifest.js";
import { tx as D } from "../../../../style-system/dist/twind.js";
import ResizeHandle from "./ResizeHandle.js";
import { a as fe } from "../../../../sdk/dist/shared/chunk-PSCN3VVA.js";
import "../../../../sdk/dist/shared/chunk-R6ATC4TC.js";
import "@sinclair/typebox";
import "../../../../sdk/dist/shared/chunk-CFF6Q7O7.js";
import "../../../../sdk/dist/shared/chunk-IKC3FK7L.js";
import "../../../../sdk/dist/shared/chunk-E6XEI7IK.js";
import "../../../../sdk/dist/shared/chunk-SQ5T4AT5.js";
import "../../../../sdk/dist/shared/chunk-G5CJU6RD.js";
import "../../../../sdk/dist/shared/chunk-PSTFJ5IJ.js";
import "../../../../sdk/dist/shared/chunk-NJGXC7D6.js";
import "../../../../sdk/dist/shared/chunk-SXHDQ64Z.js";
import "../../../../sdk/dist/shared/chunk-QX6OGRRT.js";
import "../../../../sdk/dist/shared/chunk-FLOMNC6J.js";
import "../../../../sdk/dist/shared/chunk-PLSV746R.js";
import "../../../../sdk/dist/shared/chunk-WBZW5LVH.js";
import "../../../../sdk/dist/shared/chunk-WYVJE6J5.js";
import "../../../../sdk/dist/shared/chunk-I3VL6SRH.js";
import "../../../../sdk/dist/shared/chunk-B3EATRFX.js";
import "../../../../sdk/dist/shared/chunk-IKHZD2JH.js";
import "../../../../sdk/dist/shared/chunk-PXI7AHWS.js";
import "../../../../sdk/dist/shared/chunk-SY6DZLTC.js";
import "../../../../sdk/dist/shared/chunk-7A2JNQX3.js";
import "../../../../sdk/dist/shared/chunk-3YVJ2ELD.js";
import "../../../../sdk/dist/shared/chunk-AFVJZPLS.js";
import "../../../../sdk/dist/shared/chunk-A3GF4PYW.js";
import "../../../../sdk/dist/shared/chunk-W33JMRRN.js";
import { getBrickResizeOptions } from "../../shared/utils/layout-utils.js";
import useIsHovered from "../hooks/use-is-hovered.js";
import { usePageQueries, useDraftHelpers, useSectionByBrickId } from "../../../../../use-page-data.js";
import { MdRepeat } from "../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/md/index.js";
import { useSortable } from "../../../../../node_modules/.pnpm/@dnd-kit_react@0.1.21_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@dnd-kit/react/sortable.js";
import { pointerIntersection } from "../../../../../node_modules/.pnpm/@dnd-kit_collision@0.1.21/node_modules/@dnd-kit/collision/dist/index.js";
import { RestrictToElement } from "../../../../../node_modules/.pnpm/@dnd-kit_dom@0.1.21/node_modules/@dnd-kit/dom/modifiers.js";
import { useCmdOrCtrlPressed } from "../hooks/use-key-pressed.js";
import { CollisionPriority } from "../../../../../node_modules/.pnpm/@dnd-kit_abstract@0.1.21/node_modules/@dnd-kit/abstract/index.js";
import BrickArrows from "./EditableBrickArrows.js";
import EditableBrickContextMenu from "./EditableBrickContextMenu.js";
import EditableBrickNavBar from "./EditableBrickNavBar.js";
import { range } from "lodash-es";
import { useDragDropMonitor } from "../../../../../node_modules/.pnpm/@dnd-kit_react@0.1.21_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@dnd-kit/react/index.js";
import { offset, autoPlacement } from "../../../../../node_modules/.pnpm/@floating-ui_react-dom@2.1.2_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.js";
import { autoUpdate } from "../../../../../node_modules/.pnpm/@floating-ui_dom@1.6.13/node_modules/@floating-ui/dom/dist/floating-ui.dom.js";
import { Tooltip as e } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/tooltip.js";
function useBarPlacements(brick) {
  return ["bottom", "top"];
}
function EditableBrickWrapperSimple({
  brick,
  index,
  level = 0,
  isDynamicPreview,
  iterationIndex
}) {
  const hasMouseMoved = useRef(false);
  const selectedBrickId = useSelectedBrickId();
  const previewMode = usePreviewMode();
  const { panelPosition } = usePanel();
  const editorHelpers = useEditorHelpers();
  const { getParentBrick, updateBrickProps } = useDraftHelpers();
  const section = useSectionByBrickId(brick.id);
  const manifest = useBrickManifest(brick.type);
  const parentBrick = getParentBrick(brick.id);
  const [isMenuBarVisible, setMenuBarVisible] = useState(false);
  const allowedPlacements = useBarPlacements();
  const draggingBrickType = useDraggingBrickType();
  const wrapperRef = useRef(null);
  const isContainerChild = !!parentBrick;
  const cmdKeyPressed = useCmdOrCtrlPressed();
  const [globalDragging, setGlobalDragging] = useState(false);
  const isDragDisabled = !!isDynamicPreview || !manifest.movable || isContainerChild || !!brick.props.ghost || previewMode === "mobile";
  useDragDropMonitor({
    onBeforeDragStart(event) {
      setGlobalDragging(true);
    },
    onDragEnd(event) {
      setTimeout(() => {
        setGlobalDragging(false);
      }, 200);
    }
  });
  const { isDragging, isDropping, isDropTarget, isDragSource } = useSortable({
    id: brick.id,
    index,
    element: wrapperRef,
    disabled: isDragDisabled,
    collisionPriority: CollisionPriority.Normal,
    collisionDetector: cmdKeyPressed ? pointerIntersection : void 0,
    type: "brick",
    accept: (source) => source.type === "brick" || source.type === "library",
    group: section?.id,
    data: { brick, parentBrick, section, manifest },
    transition: {
      duration: 250,
      // Animation duration in ms
      easing: "cubic-bezier(0.25, 1, 0.5, 1)",
      // Animation easing
      idle: true
      // Whether to animate when no drag is in progress but its index changes
    },
    modifiers: [
      RestrictToElement.configure({
        element: (operation) => {
          if (isContainerChild) {
            return wrapperRef.current?.parentElement;
          }
          return document.querySelector("#page-container");
        }
      })
    ]
  });
  const {
    refs: barsRefs,
    floatingStyles: barsFloatingStyles,
    update: updateBarsPlacement,
    context: barsFloatingContext
  } = useFloating({
    open: isMenuBarVisible,
    onOpenChange: setMenuBarVisible,
    whileElementsMounted: autoUpdate,
    transform: true,
    middleware: [
      offset(manifest.isContainer ? { mainAxis: 8, crossAxis: 0 } : { mainAxis: 6, crossAxis: 0 }),
      autoPlacement({
        allowedPlacements
      })
    ]
  });
  const hover = useHover(barsFloatingContext, {
    handleClose: safePolygon(),
    enabled: !isDynamicPreview,
    delay: {
      open: 50,
      close: 200
    }
  });
  const { getReferenceProps, getFloatingProps } = useInteractions([hover]);
  useEffect(() => {
    if (barsRefs.reference.current) {
      const onMouseMove = () => {
        hasMouseMoved.current = true;
      };
      const onMouseDown = () => {
        hasMouseMoved.current = false;
      };
      const onMouseUp = () => {
        updateBarsPlacement();
        setTimeout(() => {
          hasMouseMoved.current = false;
        }, 200);
      };
      const el = barsRefs.reference.current;
      el.addEventListener("mousedown", onMouseDown);
      el.addEventListener("mouseup", onMouseUp);
      el.addEventListener("mousemove", onMouseMove);
      return () => {
        el.removeEventListener("mousedown", onMouseDown);
        el.removeEventListener("mouseup", onMouseUp);
        el.removeEventListener("mousemove", onMouseMove);
      };
    }
  }, [barsRefs.reference, updateBarsPlacement]);
  const onBrickWrapperClick = useCallback(
    (e2) => {
      const originalTarget = e2.target;
      const brickTarget = e2.currentTarget;
      if (hasMouseMoved.current || !brickTarget?.matches("[data-element-kind='brick']") && !originalTarget?.matches("[data-element-kind='brick']") || e2.defaultPrevented && !originalTarget.closest('[data-prevented-by-editor="true"]')) {
        console.debug(
          "EditableBrickWrapper: Click ignored due to mouse movement or default prevented",
          originalTarget,
          e2
        );
        return;
      }
      if (manifest.isGlobalBrick) {
        editorHelpers.setPanel("settings");
        editorHelpers.setAttributesGroup(manifest.type);
        editorHelpers.setAttributesTab("site");
        editorHelpers.setSelectedBrickId(brick.id);
        return;
      }
      let selectedElement = brick;
      let elementType = "brick";
      if (e2.shiftKey) {
        if (parentBrick) {
          console.log("Selecting parent brick", parentBrick);
          selectedElement = parentBrick;
        }
      } else if ((e2.ctrlKey || e2.metaKey) && section) {
        elementType = "section";
        selectedElement = section;
      }
      editorHelpers.hidePanel();
      if (panelPosition === "left" && e2.clientX < window.innerWidth * 0.25) {
        editorHelpers.togglePanelPosition();
      } else if (panelPosition === "right" && e2.clientX > window.innerWidth * 0.75) {
        editorHelpers.togglePanelPosition();
      }
      startTransition(() => {
        if (elementType === "section") {
          editorHelpers.setSelectedSectionId(selectedElement.id);
        } else {
          console.log("Selecting brick", selectedElement);
          editorHelpers.setSelectedBrickId(selectedElement.id);
        }
        editorHelpers.setPanel("inspector");
      });
      hasMouseMoved.current = false;
      e2.stopPropagation();
    },
    [panelPosition]
  );
  const { ref: hoverRef, isHovered } = useIsHovered({ tolerance: 6, deepCheck: true });
  const wrapperClass = useBrickWrapperStyle({
    brick,
    editable: true,
    selected: selectedBrickId === brick.id,
    isContainerChild
  });
  const mergedRef = useMergeRefs([barsRefs.setReference, wrapperRef, hoverRef]);
  const resizeOpts = getBrickResizeOptions(fe[brick.type]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(EditableBrickContextMenu, { brick, isContainerChild, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      ref: mergedRef,
      ...getReferenceProps(),
      id: brick.id,
      "data-element-kind": "brick",
      "data-brick-id": brick.id,
      "data-brick-type": brick.type,
      "data-last-touched": brick.props.lastTouched ?? "0",
      "data-is-container": manifest.isContainer,
      "data-is-container-child": isContainerChild,
      "data-dragging": isDragging,
      "data-level": level,
      "data-index": index,
      "data-brick-width": brick.props.width,
      "data-brick-height": brick.props.height,
      "data-brick-max-width": JSON.stringify(manifest.maxWidth),
      "data-brick-min-width": JSON.stringify(manifest.minWidth),
      className: D(
        wrapperClass,
        isDynamicPreview && "hover:(opacity-40 grayscale) group-hover/section:(opacity-40 grayscale pointer-events-none)",
        isDragging ? "!z-[9999] !shadow-2xl overflow-hidden !cursor-grabbing" : "hover:cursor-auto",
        isDynamicPreview && globalDragging && "scale-0",
        !!brick.props.ghost && "opacity-50 pointer-events-none grayscale bg-white"
      ),
      onClick: onBrickWrapperClick,
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          BrickComponent,
          {
            brick,
            iterationIndex,
            isDynamicPreview,
            editable: true
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(FloatingPortal, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          EditableBrickNavBar,
          {
            ref: barsRefs.setFloating,
            brick,
            isContainerChild,
            style: barsFloatingStyles,
            show: isMenuBarVisible,
            ...getFloatingProps()
          }
        ) }),
        fe[brick.type]?.resizable && !draggingBrickType && !isDragging && !isDynamicPreview && selectedBrickId === brick.id && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          (resizeOpts.canGrowVertical || resizeOpts.canShrinkVertical) && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "s", show: isHovered, manifest }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "n", show: isHovered, manifest })
          ] }),
          (resizeOpts.canGrowHorizontal || resizeOpts.canShrinkHorizontal) && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "w", show: isHovered, manifest }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "e", show: isHovered, manifest })
          ] }),
          (resizeOpts.canGrowVertical && resizeOpts.canGrowHorizontal || resizeOpts.canShrinkVertical && resizeOpts.canShrinkHorizontal) && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "se", show: isHovered, manifest }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "sw", show: isHovered, manifest }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "ne", show: isHovered, manifest }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ResizeHandle, { direction: "nw", show: isHovered, manifest })
          ] })
        ] }),
        previewMode === "desktop" && !isDynamicPreview && brick.id === selectedBrickId && /* @__PURE__ */ jsxRuntimeExports.jsx(BrickArrows, { brick }),
        typeof brick.props.loop !== "undefined" && !isDynamicPreview && /* @__PURE__ */ jsxRuntimeExports.jsx(e, { content: "This brick will be repeated for each item in the query result", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: D(
              `group-hover/brick:opacity-100 absolute cursor-help -top-[12px] -right-[12px] z-[99999] w-5 h-5 rounded-full
            flex items-center justify-center text-upstart-500 group/dyn-helper bg-white/90 shadow border border-upstart-500`,
              brick.id === selectedBrickId ? "opacity-100" : "opacity-0"
            ),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(MdRepeat, { className: "w-3 h-3" })
          }
        ) }),
        manifest.isContainer && !isDragging && isDropTarget && cmdKeyPressed && !isDragSource && /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: D(
              "absolute inset-0 z-auto flex items-center justify-center bg-black/30 font-bold text-white rounded"
            ),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex rounded-full px-4 py-2 bg-black/50", children: "Drop in box" })
          }
        )
      ]
    }
  ) });
}
function EditableBrickWrapper(props) {
  const {
    brick: { props: brickProps, type }
  } = props;
  const pageQueries = usePageQueries();
  const manifest = useBrickManifest(type);
  const loop = brickProps.loop;
  if (!loop?.over || manifest.consumesMultipleQueryRows) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(EditableBrickWrapperSimple, { ...props });
  }
  const loopQuery = pageQueries.find((q) => q.alias === loop?.over);
  const limit = Math.min(loop.overrideLimit ?? Infinity, loopQuery?.queryInfo.limit ?? 1, 3);
  const { brick, ...rest } = props;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: range(0, limit).map((i, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    EditableBrickWrapperSimple,
    {
      ...rest,
      iterationIndex: index,
      isDynamicPreview: index > 0,
      brick: {
        ...brick,
        id: index > 0 ? `${brick.id}-${index}` : brick.id
      }
    },
    i
  )) });
}
export {
  EditableBrickWrapperSimple,
  EditableBrickWrapper as default
};
//# sourceMappingURL=EditableBrick.js.map
