"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useCallback, useState, useRef, useMemo, useEffect } from 'react';
import { Plus, ZoomIn, ZoomOut, Crosshair, MousePointer } from 'lucide-react';
import { useLayerStore } from '../../../lib/ui-builder/store/layer-store.mjs';
import { TransformWrapper, TransformComponent, useControls } from '../../../../../../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.mjs';
import LayerRenderer from '../layer-renderer.mjs';
import { DndContextProvider } from '../../../lib/ui-builder/context/dnd-context.mjs';
import { cn } from '../../../lib/utils.mjs';
import { useEditorStore } from '../../../lib/ui-builder/store/editor-store.mjs';
import { AddComponentsPopover } from './components/add-component-popover.mjs';
import { Button } from '../../button.mjs';
import { ResizableWrapper } from './canvas/resizable-wrapper.mjs';
import AutoFrame from './canvas/auto-frame.mjs';
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from '../../tooltip.mjs';
import { LayerContextMenuPortal } from './components/layer-context-menu-portal.mjs';
import { useComponentDragContext } from '../../../lib/ui-builder/context/dnd-contexts.mjs';
import { countLayers } from '../../../lib/ui-builder/store/layer-utils.mjs';

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 } = useControls();
  const handleZoomIn = useCallback(() => zoomIn(), [zoomIn]);
  const handleZoomOut = useCallback(() => zoomOut(), [zoomOut]);
  const handleReset = useCallback(() => resetTransform(), [resetTransform]);
  const handleTogglePointerEvents = useCallback(() => {
    onPointerEventsToggle(!pointerEventsEnabled);
  }, [onPointerEventsToggle, pointerEventsEnabled]);
  return /* @__PURE__ */ jsx(TooltipProvider, { children: /* @__PURE__ */ jsxs("div", { className: "absolute bottom-24 md:bottom-4 right-4 z-[1000] flex shadow-lg rounded-full", children: [
    /* @__PURE__ */ jsxs(Tooltip, { children: [
      /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
        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__ */ jsx("span", { className: "sr-only", children: "Zoom in" }),
            /* @__PURE__ */ jsx(ZoomIn, { className: "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsx(TooltipContent, { side: "top", children: /* @__PURE__ */ jsx("p", { children: "Zoom in" }) })
    ] }),
    /* @__PURE__ */ jsxs(Tooltip, { children: [
      /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
        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__ */ jsx("span", { className: "sr-only", children: "Zoom out" }),
            /* @__PURE__ */ jsx(ZoomOut, { className: "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsx(TooltipContent, { side: "top", children: /* @__PURE__ */ jsx("p", { children: "Zoom out" }) })
    ] }),
    /* @__PURE__ */ jsxs(Tooltip, { children: [
      /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
        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__ */ jsx("span", { className: "sr-only", children: "Reset" }),
            /* @__PURE__ */ jsx(Crosshair, { className: "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsx(TooltipContent, { side: "top", children: /* @__PURE__ */ jsx("p", { children: "Reset zoom and position" }) })
    ] }),
    /* @__PURE__ */ jsxs(Tooltip, { children: [
      /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
        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__ */ jsx("span", { className: "sr-only", children: pointerEventsEnabled ? "Disable pointer events" : "Enable pointer events" }),
            /* @__PURE__ */ jsx(MousePointer, { className: pointerEventsEnabled ? "text-primary-foreground" : "text-secondary-foreground" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsx(TooltipContent, { side: "top", children: /* @__PURE__ */ jsx("p", { children: pointerEventsEnabled ? "Disable page interaction" : "Enable page interaction" }) })
    ] })
  ] }) });
};
const EditorPanel = ({ className }) => {
  const {
    selectLayer,
    selectedLayerId,
    findLayerById,
    selectedPageId
  } = useLayerStore();
  const previewMode = useEditorStore((state) => state.previewMode);
  const componentRegistry = useEditorStore((state) => state.registry);
  const selectedLayer = findLayerById(selectedLayerId);
  const selectedPage = findLayerById(selectedPageId);
  const onSelectElement = useCallback(
    (layerId) => {
      selectLayer(layerId);
    },
    [selectLayer]
  );
  return /* @__PURE__ */ jsx(DndContextProvider, { children: /* @__PURE__ */ jsx(
    EditorPanelContent,
    {
      className,
      selectedLayerId,
      selectedPageId,
      selectedLayer,
      selectedPage,
      previewMode,
      componentRegistry,
      autoZoomToSelected: false,
      onSelectElement
    }
  ) });
};
const EditorPanelContent = ({
  className,
  selectedPageId,
  selectedLayerId,
  selectedLayer,
  selectedPage,
  previewMode,
  componentRegistry,
  autoZoomToSelected,
  onSelectElement
}) => {
  const { isDragging: isComponentDragging } = useComponentDragContext();
  const [resizing, setResizing] = useState(false);
  const [frameSize, setFrameSize] = useState({
    width: 1e3,
    height: 1e3
  });
  const [pointerEventsEnabled, setPointerEventsEnabled] = useState(true);
  const frameRef = useRef(null);
  const handleResizingChange = useCallback((isDragging) => {
    setResizing(isDragging);
  }, []);
  const handleSizeChange = useCallback((width, height) => {
    setFrameSize({ width, height });
  }, []);
  const handlePointerEventsToggle = useCallback((enabled) => {
    setPointerEventsEnabled(enabled);
  }, []);
  const layers = selectedPage.children;
  const totalLayers = useMemo(() => countLayers(layers), [layers]);
  const editorConfig = useMemo(
    () => ({
      zIndex: 1,
      totalLayers,
      selectedLayer,
      onSelectElement
    }),
    [
      totalLayers,
      selectedLayer,
      onSelectElement
    ]
  );
  const widthClass = 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 = 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 = useMemo(() => ({
    isResizable: previewMode === "responsive",
    onDraggingChange: handleResizingChange,
    onSizeChange: handleSizeChange
  }), [previewMode, handleResizingChange, handleSizeChange]);
  const autoFrameProps = useMemo(() => ({
    height: frameSize.height,
    className: cn("shadow-lg", widthClass, heightClass),
    pointerEventsEnabled
  }), [frameSize.height, widthClass, heightClass, pointerEventsEnabled]);
  const layerRendererProps = useMemo(() => ({
    className: "contents",
    page: selectedPage,
    editorConfig,
    componentRegistry
  }), [selectedPage, editorConfig, componentRegistry]);
  const renderer = useMemo(
    () => /* @__PURE__ */ jsx(ResizableWrapper, { ...resizableProps, children: /* @__PURE__ */ jsx(
      "div",
      {
        id: "editor-panel-content",
        className: cn("overflow-visible ", widthClass),
        children: /* @__PURE__ */ jsxs(AutoFrame, { ...autoFrameProps, ref: frameRef, children: [
          /* @__PURE__ */ jsx(LayerRenderer, { ...layerRendererProps }),
          /* @__PURE__ */ jsx(LayerContextMenuPortal, {})
        ] })
      }
    ) }),
    [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 = useMemo(() => ({
    disabled: resizing || isComponentDragging
  }), [resizing, isComponentDragging]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      id: "editor-panel-container",
      className: 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__ */ jsxs(
          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__ */ jsx(
                ZoomControls,
                {
                  onPointerEventsToggle: handlePointerEventsToggle,
                  pointerEventsEnabled
                }
              ),
              autoZoomToSelected && /* @__PURE__ */ jsx(
                AutoZoomToSelected,
                {
                  selectedLayerId,
                  autoZoomToSelected
                }
              ),
              /* @__PURE__ */ jsx(
                TransformComponent,
                {
                  wrapperStyle,
                  contentStyle,
                  children: /* @__PURE__ */ jsx(
                    "div",
                    {
                      className: cn("relative", widthClass),
                      "data-testid": "transform-component",
                      style: transformDivStyle,
                      children: renderer
                    }
                  )
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ jsx(AddComponentsPopover, { parentLayerId: selectedPageId, enableDragToCanvas: true, children: /* @__PURE__ */ jsx(
          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__ */ jsx(Plus, { className: "text-secondary-foreground" })
          }
        ) })
      ]
    }
  );
};
const AutoZoomToSelected = ({ selectedLayerId, autoZoomToSelected }) => {
  const { zoomToElement } = useControls();
  const previousSelectedLayerIdRef = useRef(null);
  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;
};

export { EditorPanel as default };
