"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const LucideIcons = require('lucide-react');
const layerStore = require('../../../lib/ui-builder/store/layer-store.cjs');
const index_esm = require('../../../../../../node_modules/.pnpm/react-zoom-pan-pinch@3.7.0_react-dom@19.2.0_react@19.2.0__react@19.2.0/node_modules/react-zoom-pan-pinch/dist/index.esm.cjs');
const layerRenderer = require('../layer-renderer.cjs');
const dndContext = require('../../../lib/ui-builder/context/dnd-context.cjs');
const utils = require('../../../lib/utils.cjs');
const editorStore = require('../../../lib/ui-builder/store/editor-store.cjs');
const addComponentPopover = require('./components/add-component-popover.cjs');
const button = require('../../button.cjs');
const resizableWrapper = require('./canvas/resizable-wrapper.cjs');
const autoFrame = require('./canvas/auto-frame.cjs');
const tooltip = require('../../tooltip.cjs');
const dndContexts = require('../../../lib/ui-builder/context/dnd-contexts.cjs');
const layerUtils = require('../../../lib/ui-builder/store/layer-utils.cjs');

const WRAPPER_STYLE = {
  width: "100%",
  height: "100%"
};
const CONTENT_STYLE = {
  width: "100%",
  height: "100%"
};
const TRANSFORM_DIV_STYLE = {
  minHeight: "100vh",
  padding: "50px"
};
const WHEEL_CONFIG = { step: 0.1 };
const DOUBLE_CLICK_CONFIG = { disabled: false };
const ZoomControls = ({
  onPointerEventsToggle,
  pointerEventsEnabled
}) => {
  const { zoomIn, zoomOut, resetTransform } = index_esm.useControls();
  const handleZoomIn = React.useCallback(() => zoomIn(), [zoomIn]);
  const handleZoomOut = React.useCallback(() => zoomOut(), [zoomOut]);
  const handleReset = React.useCallback(() => resetTransform(), [resetTransform]);
  const handleTogglePointerEvents = React.useCallback(() => {
    onPointerEventsToggle(!pointerEventsEnabled);
  }, [onPointerEventsToggle, pointerEventsEnabled]);
  return /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipProvider, { children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute bottom-24 md:bottom-4 right-4 z-[1000] flex shadow-lg rounded-full", children: [
    /* @__PURE__ */ jsxRuntime.jsxs(tooltip.Tooltip, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
        button.Button,
        {
          "data-testid": "button-ZoomIn",
          variant: "secondary",
          className: "size-14 md:size-10 rounded-l-full rounded-r-none border-r border-border [&_svg]:size-7 [&_svg]:md:size-4",
          onClick: handleZoomIn,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Zoom in" }),
            /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ZoomIn, { className: "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipContent, { side: "top", children: /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Zoom in" }) })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs(tooltip.Tooltip, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
        button.Button,
        {
          "data-testid": "button-ZoomOut",
          variant: "secondary",
          className: "size-14 md:size-10 rounded-none border-r border-border [&_svg]:size-7 [&_svg]:md:size-4",
          onClick: handleZoomOut,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Zoom out" }),
            /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ZoomOut, { className: "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipContent, { side: "top", children: /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Zoom out" }) })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs(tooltip.Tooltip, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
        button.Button,
        {
          "data-testid": "button-Reset",
          variant: "secondary",
          className: "size-14 md:size-10 rounded-none border-r border-border [&_svg]:size-7 [&_svg]:md:size-4",
          onClick: handleReset,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Reset" }),
            /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Crosshair, { className: "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipContent, { side: "top", children: /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Reset zoom and position" }) })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs(tooltip.Tooltip, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
        button.Button,
        {
          "data-testid": "button-PointerEvents",
          variant: pointerEventsEnabled ? "default" : "secondary",
          className: "size-14 md:size-10 rounded-r-full rounded-l-none [&_svg]:size-7 [&_svg]:md:size-4",
          onClick: handleTogglePointerEvents,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: pointerEventsEnabled ? "Disable pointer events" : "Enable pointer events" }),
            /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.MousePointer, { className: pointerEventsEnabled ? "text-primary-foreground" : "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipContent, { side: "top", children: /* @__PURE__ */ jsxRuntime.jsx("p", { children: pointerEventsEnabled ? "Disable page interaction" : "Enable page interaction" }) })
    ] })
  ] }) });
};
const EditorPanel = ({ className }) => {
  const {
    selectLayer,
    selectedLayerId,
    findLayerById,
    duplicateLayer,
    removeLayer,
    selectedPageId
  } = layerStore.useLayerStore();
  const previewMode = editorStore.useEditorStore((state) => state.previewMode);
  const componentRegistry = editorStore.useEditorStore((state) => state.registry);
  const selectedLayer = findLayerById(selectedLayerId);
  const selectedPage = findLayerById(selectedPageId);
  const isLayerAPage = layerStore.useLayerStore(
    (state) => state.isLayerAPage(selectedLayerId || "")
  );
  const allowPagesCreation = editorStore.useEditorStore(
    (state) => state.allowPagesCreation
  );
  const allowPagesDeletion = editorStore.useEditorStore(
    (state) => state.allowPagesDeletion
  );
  const onSelectElement = React.useCallback(
    (layerId) => {
      selectLayer(layerId);
    },
    [selectLayer]
  );
  const handleDeleteLayer = React.useCallback(() => {
    if (selectedLayer && !isLayerAPage) {
      removeLayer(selectedLayer.id);
    }
  }, [selectedLayer, removeLayer, isLayerAPage]);
  const handleDuplicateLayer = React.useCallback(() => {
    if (selectedLayer && !isLayerAPage) {
      duplicateLayer(selectedLayer.id);
    }
  }, [selectedLayer, duplicateLayer, isLayerAPage]);
  return /* @__PURE__ */ jsxRuntime.jsx(dndContext.DndContextProvider, { children: /* @__PURE__ */ jsxRuntime.jsx(
    EditorPanelContent,
    {
      className,
      selectedLayerId,
      selectedPageId,
      selectedLayer,
      selectedPage,
      isLayerAPage,
      allowPagesCreation,
      allowPagesDeletion,
      previewMode,
      componentRegistry,
      autoZoomToSelected: false,
      onSelectElement,
      handleDeleteLayer,
      handleDuplicateLayer
    }
  ) });
};
const EditorPanelContent = ({
  className,
  selectedPageId,
  selectedLayerId,
  selectedLayer,
  selectedPage,
  allowPagesCreation,
  allowPagesDeletion,
  previewMode,
  componentRegistry,
  autoZoomToSelected,
  onSelectElement,
  handleDeleteLayer,
  handleDuplicateLayer
}) => {
  const { isDragging: isComponentDragging } = dndContexts.useComponentDragContext();
  const [resizing, setResizing] = React.useState(false);
  const [frameSize, setFrameSize] = React.useState({
    width: 1e3,
    height: 1e3
  });
  const [pointerEventsEnabled, setPointerEventsEnabled] = React.useState(true);
  const frameRef = React.useRef(null);
  const handleResizingChange = React.useCallback((isDragging) => {
    setResizing(isDragging);
  }, []);
  const handleSizeChange = React.useCallback((width, height) => {
    setFrameSize({ width, height });
  }, []);
  const handlePointerEventsToggle = React.useCallback((enabled) => {
    setPointerEventsEnabled(enabled);
  }, []);
  const layers = selectedPage.children;
  const totalLayers = React.useMemo(() => layerUtils.countLayers(layers), [layers]);
  const editorConfig = React.useMemo(
    () => ({
      zIndex: 1,
      totalLayers,
      selectedLayer,
      onSelectElement,
      handleDuplicateLayer: allowPagesCreation ? handleDuplicateLayer : void 0,
      handleDeleteLayer: allowPagesDeletion ? handleDeleteLayer : void 0
    }),
    [
      totalLayers,
      selectedLayer,
      onSelectElement,
      handleDuplicateLayer,
      handleDeleteLayer,
      allowPagesCreation,
      allowPagesDeletion
    ]
  );
  const widthClass = React.useMemo(() => {
    if (previewMode === "responsive") {
      return "w-full";
    } else if (previewMode === "mobile") {
      return "w-[390px]";
    } else if (previewMode === "tablet") {
      return "w-[768px]";
    } else if (previewMode === "desktop") {
      return "w-[1440px]";
    } else {
      return "w-full";
    }
  }, [previewMode]);
  const heightClass = React.useMemo(() => {
    if (previewMode === "responsive") {
      return "";
    } else if (previewMode === "mobile") {
      return "h-[844px]";
    } else if (previewMode === "tablet") {
      return "h-[1024px]";
    } else if (previewMode === "desktop") {
      return "h-[900px]";
    } else {
      return "h-full";
    }
  }, [previewMode]);
  const resizableProps = React.useMemo(() => ({
    isResizable: previewMode === "responsive",
    onDraggingChange: handleResizingChange,
    onSizeChange: handleSizeChange
  }), [previewMode, handleResizingChange, handleSizeChange]);
  const autoFrameProps = React.useMemo(() => ({
    height: frameSize.height,
    className: utils.cn("shadow-lg", widthClass, heightClass),
    pointerEventsEnabled
  }), [frameSize.height, widthClass, heightClass, pointerEventsEnabled]);
  const layerRendererProps = React.useMemo(() => ({
    className: "contents",
    page: selectedPage,
    editorConfig,
    componentRegistry
  }), [selectedPage, editorConfig, componentRegistry]);
  const renderer = React.useMemo(
    () => /* @__PURE__ */ jsxRuntime.jsx(resizableWrapper.ResizableWrapper, { ...resizableProps, children: /* @__PURE__ */ jsxRuntime.jsx(
      "div",
      {
        id: "editor-panel-content",
        className: utils.cn("overflow-visible ", widthClass),
        children: /* @__PURE__ */ jsxRuntime.jsx(autoFrame.default, { ...autoFrameProps, ref: frameRef, children: /* @__PURE__ */ jsxRuntime.jsx(layerRenderer, { ...layerRendererProps }) })
      }
    ) }),
    [resizableProps, widthClass, autoFrameProps, layerRendererProps]
  );
  const wrapperStyle = WRAPPER_STYLE;
  const contentStyle = CONTENT_STYLE;
  const transformDivStyle = TRANSFORM_DIV_STYLE;
  const wheelConfig = WHEEL_CONFIG;
  const doubleClickConfig = DOUBLE_CLICK_CONFIG;
  const panningConfig = React.useMemo(() => ({
    disabled: resizing || isComponentDragging
  }), [resizing, isComponentDragging]);
  return /* @__PURE__ */ jsxRuntime.jsxs(
    "div",
    {
      id: "editor-panel-container",
      className: utils.cn(
        "flex flex-col relative size-full bg-fixed bg-[radial-gradient(hsl(var(--border))_1px,hsl(var(--primary)/0.05)_1px)] [background-size:16px_16px] will-change-auto",
        className
      ),
      children: [
        /* @__PURE__ */ jsxRuntime.jsxs(
          index_esm.TransformWrapper,
          {
            initialScale: 0.8,
            initialPositionX: -30,
            initialPositionY: -30,
            minScale: 0.1,
            maxScale: 5,
            wheel: wheelConfig,
            doubleClick: doubleClickConfig,
            panning: panningConfig,
            centerOnInit: false,
            limitToBounds: false,
            children: [
              /* @__PURE__ */ jsxRuntime.jsx(
                ZoomControls,
                {
                  onPointerEventsToggle: handlePointerEventsToggle,
                  pointerEventsEnabled
                }
              ),
              autoZoomToSelected && /* @__PURE__ */ jsxRuntime.jsx(
                AutoZoomToSelected,
                {
                  selectedLayerId,
                  autoZoomToSelected
                }
              ),
              /* @__PURE__ */ jsxRuntime.jsx(
                index_esm.TransformComponent,
                {
                  wrapperStyle,
                  contentStyle,
                  children: /* @__PURE__ */ jsxRuntime.jsx(
                    "div",
                    {
                      className: utils.cn("relative", widthClass),
                      "data-testid": "transform-component",
                      style: transformDivStyle,
                      children: renderer
                    }
                  )
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntime.jsx(addComponentPopover.AddComponentsPopover, { parentLayerId: selectedPageId, enableDragToCanvas: true, children: /* @__PURE__ */ jsxRuntime.jsx(
          button.Button,
          {
            variant: "secondary",
            size: "icon",
            className: "absolute bottom-4 left-4 size-14 md:size-10 flex items-center rounded-full bg-secondary shadow-lg z-[1000] [&_svg]:size-7 [&_svg]:md:size-4",
            children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Plus, { className: "text-secondary-foreground" })
          }
        ) })
      ]
    }
  );
};
const AutoZoomToSelected = ({ selectedLayerId, autoZoomToSelected }) => {
  const { zoomToElement } = index_esm.useControls();
  const previousSelectedLayerIdRef = React.useRef(null);
  React.useEffect(() => {
    if (!selectedLayerId || !zoomToElement || !autoZoomToSelected) return;
    if (previousSelectedLayerIdRef.current === selectedLayerId) return;
    previousSelectedLayerIdRef.current = selectedLayerId;
    const timeoutId = setTimeout(() => {
      const selectedElement = document.querySelector(`[data-layer-id="${selectedLayerId}"]`) || document.getElementById(`layer-${selectedLayerId}`);
      if (selectedElement) {
        zoomToElement(selectedElement, void 0, 300);
      }
    }, 100);
    return () => clearTimeout(timeoutId);
  }, [selectedLayerId, zoomToElement, autoZoomToSelected]);
  return null;
};

module.exports = EditorPanel;
