import { useRef, useCallback, useEffect } from "react";
import interact from "../../../../../_virtual/interact.min.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 { usePreviewMode } from "../../../../../use-editor.js";
function useResizable(cssQuery, options) {
  const interactablesRef = useRef(/* @__PURE__ */ new Set());
  const observerRef = useRef(null);
  const previewMode = usePreviewMode();
  const { gridSnap, onResizeStart, onResize, onResizeEnd, enabled = true } = options;
  const getActiveDirection = useCallback((handle) => {
    if (!handle?.classList.contains("resizable-handle")) return "";
    const directionClass = Array.from(handle.classList).find((cls) => cls.startsWith("resizable-handle-"));
    return directionClass ? directionClass.replace("resizable-handle-", "") : "";
  }, []);
  const createResizeEvent = useCallback(
    (target, rect, deltaRect, edges, activeHandle) => ({
      target,
      rect,
      deltaRect,
      edges,
      activeDirection: getActiveDirection(activeHandle || null)
    }),
    [getActiveDirection]
  );
  const initializeResizable = useCallback(() => {
    if (!enabled) return;
    interactablesRef.current.forEach((interactable) => interactable.unset());
    interactablesRef.current.clear();
    const elements = document.querySelectorAll(cssQuery);
    elements.forEach((element) => {
      const htmlElement = element;
      const hasHandles = htmlElement.querySelector(".resizable-handle");
      if (!hasHandles) return;
      const interactable = interact(htmlElement, {
        preventDefault: "always"
      }).resizable({
        edges: {
          top: ".resizable-handle-n, .resizable-handle-ne, .resizable-handle-nw",
          right: ".resizable-handle-e, .resizable-handle-ne, .resizable-handle-se",
          bottom: ".resizable-handle-s, .resizable-handle-se, .resizable-handle-sw",
          left: ".resizable-handle-w, .resizable-handle-nw, .resizable-handle-sw"
        },
        listeners: {
          start(event) {
            const target = event.target;
            const rect = target.getBoundingClientRect();
            const activeHandle = event.interaction.downEvent?.target;
            target.classList.toggle("resizing", true);
            setElementSize(target, rect.width, rect.height, event);
            const resizeEvent = createResizeEvent(
              target,
              { width: rect.width, height: rect.height },
              { left: 0, top: 0, width: 0, height: 0 },
              event.edges,
              activeHandle
            );
            onResizeStart?.(resizeEvent);
          },
          move(event) {
            const target = event.target;
            let { width, height } = event.rect;
            const manifest = fe[target.dataset.brickType || "unknown"] || {};
            if (manifest.minWidth?.[previewMode]) {
              width = Math.max(width, manifest.minWidth[previewMode]);
            }
            if (manifest.minHeight?.[previewMode]) {
              height = Math.max(height, manifest.minHeight[previewMode]);
            }
            if (manifest.maxWidth?.[previewMode]) {
              width = Math.min(width, manifest.maxWidth[previewMode]);
            }
            if (manifest.maxHeight?.[previewMode]) {
              height = Math.min(height, manifest.maxHeight[previewMode]);
            }
            setElementSize(target, width, height, event);
            if (event.edges.left) ;
            if (event.edges.right) ;
            if (event.edges.top) ;
            if (event.edges.bottom) ;
            const activeHandle = event.interaction.downEvent?.target;
            const resizeEvent = createResizeEvent(
              target,
              { width, height },
              event.deltaRect,
              event.edges,
              activeHandle
            );
            onResize?.(resizeEvent);
          },
          end(event) {
            event.stopPropagation();
            const target = event.target;
            const rect = target.getBoundingClientRect();
            const activeHandle = event.interaction.downEvent?.target;
            target.classList.toggle("resizing", false);
            const resizeEvent = createResizeEvent(
              target,
              { width: rect.width, height: rect.height },
              event.deltaRect,
              event.edges,
              activeHandle
            );
            onResizeEnd?.(resizeEvent);
          }
        },
        modifiers: [
          interact.modifiers.restrictSize({
            // @ts-ignore
            min: (x, y, event) => {
              const element2 = event.element;
              const brickType = element2.dataset.brickType;
              if (!brickType) {
                return { width: gridSnap.width, height: gridSnap.height };
              }
              const manifest = fe[brickType];
              const minWidth = manifest.minWidth?.[previewMode] ?? gridSnap.width;
              const minHeight = manifest.minHeight?.[previewMode] ?? gridSnap.height;
              return { width: minWidth, height: minHeight };
            },
            // @ts-ignore
            max: (x, y, event) => {
              const element2 = event.element;
              const parent = element2.parentElement;
              const parentHeight = parent.clientHeight - parseFloat(getComputedStyle(parent).paddingTop) - parseFloat(getComputedStyle(parent).paddingBottom);
              const brickType = element2.dataset.brickType;
              if (!brickType) {
                return { width: Infinity, height: parentHeight };
              }
              const manifest = fe[brickType];
              const maxWidth = manifest.maxWidth?.[previewMode] ?? Infinity;
              const maxHeight = manifest.maxHeight?.[previewMode] ?? Infinity;
              return { width: maxWidth, height: maxHeight };
            }
          }),
          ...gridSnap?.enabled !== false && gridSnap ? [
            interact.modifiers.snapSize({
              endOnly: true,
              targets: [
                interact.snappers.grid({
                  width: gridSnap.width,
                  height: gridSnap.height,
                  offset: gridSnap.offset || { x: 0, y: 0 },
                  range: gridSnap.range || Infinity
                })
              ]
            })
          ] : []
        ].filter(Boolean)
      });
      interactable.on("resizeend", function() {
        window.addEventListener("click", (ev) => ev.stopImmediatePropagation(), {
          capture: true,
          once: true
        });
      });
      interactablesRef.current.add(interactable);
    });
  }, [enabled, cssQuery, previewMode, gridSnap, onResizeStart, onResize, onResizeEnd, createResizeEvent]);
  const setupMutationObserver = useCallback(() => {
    if (observerRef.current) {
      observerRef.current.disconnect();
    }
    observerRef.current = new MutationObserver((mutations) => {
      const hasRelevantChanges = mutations.some((mutation) => {
        if (mutation.type !== "childList") return false;
        const checkNodes = (nodes) => Array.from(nodes).some(
          (node) => node.nodeType === Node.ELEMENT_NODE && (node.matches?.(cssQuery) || node.querySelector?.(cssQuery))
        );
        return checkNodes(mutation.addedNodes) || checkNodes(mutation.removedNodes);
      });
      if (hasRelevantChanges) {
        setTimeout(initializeResizable, 100);
      }
    });
    observerRef.current.observe(document.body, {
      childList: true,
      subtree: true
    });
  }, [cssQuery, initializeResizable]);
  useEffect(() => {
    if (enabled) {
      initializeResizable();
      setupMutationObserver();
    } else {
      interactablesRef.current.forEach((interactable) => interactable.unset());
      interactablesRef.current.clear();
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    }
    return () => {
      interactablesRef.current.forEach((interactable) => interactable.unset());
      interactablesRef.current.clear();
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [enabled, initializeResizable, setupMutationObserver]);
}
function setElementSize(element, width, height, event) {
  let { x = 0, y = 0 } = element.dataset;
  x = (parseFloat(`${x}`) || 0) + event.deltaRect.left;
  y = (parseFloat(`${y}`) || 0) + event.deltaRect.top;
  requestAnimationFrame(() => {
    element.style.width = `${width}px`;
    element.style.height = `${height}px`;
    element.style.setProperty("flex-grow", "0");
    element.style.transform = `translate(${x}px, ${y}px)`;
  });
}
export {
  useResizable
};
//# sourceMappingURL=use-resizable.js.map
