'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const index = require('../../../../../../_virtual/index.cjs');
const layerStore = require('../../../lib/ui-builder/store/layer-store.cjs');
const utils = require('../../../lib/utils.cjs');
const layerUtils = require('../../../lib/ui-builder/store/layer-utils.cjs');
const LucideIcons = require('lucide-react');
const index$1 = require('../../../../../../node_modules/.pnpm/he-tree-react@1.2.0_react-dom@19.2.0_react@19.2.0__react@19.2.0/node_modules/he-tree-react/dist/index.cjs');
const treeRowNode = require('./components/tree-row-node.cjs');
const devProfiler = require('./components/dev-profiler.cjs');
const addComponentPopover = require('./components/add-component-popover.cjs');
const button = require('../../button.cjs');
const dividerControl = require('./components/divider-control.cjs');

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

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

const LayersPanel = ({ className }) => {
  const {
    selectedPageId,
    selectedLayerId,
    findLayerById,
    updateLayer,
    selectLayer,
    removeLayer,
    duplicateLayer
  } = layerStore.useLayerStore();
  const pageLayer = findLayerById(selectedPageId);
  const layers = React.useMemo(() => [pageLayer], [pageLayer]);
  if (!pageLayer) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsx(
    LayersTree,
    {
      className,
      layers,
      selectedPageId,
      selectedLayerId,
      updateLayer,
      selectLayer,
      removeLayer,
      duplicateLayer
    }
  );
};
const LayersTree = React__default.memo(
  ({
    className,
    layers,
    selectedPageId,
    selectedLayerId,
    updateLayer,
    selectLayer,
    removeLayer,
    duplicateLayer
  }) => {
    const [openIdsArray, setOpenIdsArray] = React.useState([]);
    const prevSelectedLayerId = React.useRef(selectedLayerId);
    const handleNodeToggle = React.useCallback((id, open) => {
      setOpenIdsArray((prev) => {
        if (open) {
          return prev.includes(id) ? prev : [...prev, id];
        } else {
          return prev.filter((existingId) => existingId !== id);
        }
      });
    }, []);
    const handleChange = React.useCallback(
      (newLayers) => {
        if (Array.isArray(newLayers) && newLayers.length > 0) {
          const updatedPageLayer = newLayers[0];
          if (!updatedPageLayer || !updatedPageLayer.id || updatedPageLayer.id !== selectedPageId) {
            console.error(
              "LayersTree onChange: Invalid layer structure - ID mismatch",
              { updatedPageLayer, selectedPageId }
            );
            return;
          }
          const updatedChildren = layerUtils.hasLayerChildren(updatedPageLayer) ? updatedPageLayer.children || [] : [];
          const currentLayer = layers[0];
          const currentChildren = currentLayer && layerUtils.hasLayerChildren(currentLayer) ? currentLayer.children || [] : [];
          if (!index(currentChildren, updatedChildren)) {
            updateLayer(selectedPageId, {}, { children: updatedChildren });
          }
        } else {
          console.error(
            "LayersTree onChange: Invalid newLayers structure received",
            newLayers
          );
        }
      },
      [updateLayer, selectedPageId, layers]
    );
    const handleDragOpen = React.useCallback(
      (stat) => {
        if (layerUtils.hasLayerChildren(stat.node)) {
          handleNodeToggle(stat.id, true);
        }
      },
      [handleNodeToggle]
    );
    const canNodeDrop = React.useCallback((layer) => {
      const isDroppable = layerUtils.hasLayerChildren(layer.node);
      return isDroppable;
    }, []);
    const renderNode = React.useCallback(
      ({ stat, attrs, isPlaceholder }) => {
        const stableKey = isPlaceholder ? `placeholder-${attrs.key}` : stat.node.id;
        if (isPlaceholder) {
          return /* @__PURE__ */ jsxRuntime.jsx(
            treeRowNode.TreeRowPlaceholder,
            {
              nodeAttributes: attrs
            },
            stableKey
          );
        }
        const findOriginalLayer = (layers2, id) => {
          for (const layer of layers2) {
            if (layer.id === id) return layer;
            if (layerUtils.hasLayerChildren(layer)) {
              const found = findOriginalLayer(layer.children, id);
              if (found) return found;
            }
          }
          return null;
        };
        const originalNode = findOriginalLayer(layers, stat.node.id) || stat.node;
        return /* @__PURE__ */ jsxRuntime.jsx(
          treeRowNode.TreeRowNode,
          {
            nodeAttributes: attrs,
            node: originalNode,
            id: stat.id,
            open: stat.open,
            draggable: stat.draggable,
            onToggle: handleNodeToggle,
            level: stat.level,
            selectedLayerId,
            selectLayer,
            removeLayer,
            duplicateLayer,
            updateLayer
          },
          stableKey
        );
      },
      [
        handleNodeToggle,
        selectedLayerId,
        selectLayer,
        removeLayer,
        duplicateLayer,
        updateLayer,
        layers
      ]
    );
    const processedLayers = React.useMemo(() => {
      const processLayer = (layer) => {
        const processed = { ...layer };
        if (layerUtils.hasLayerChildren(layer)) {
          processed.children = layer.children.map(processLayer);
        } else if (typeof layer.children === "string") {
          processed.children = [];
        } else if (!layer.children) {
          processed.children = [];
        }
        return processed;
      };
      return layers.map(processLayer);
    }, [layers]);
    const data = React.useMemo(() => {
      return {
        data: processedLayers,
        dataType: "tree",
        childrenKey: "children",
        openIds: openIdsArray,
        dragOpen: true,
        onChange: handleChange,
        renderNodeBox: renderNode,
        onDragOpen: handleDragOpen,
        canDrop: canNodeDrop
      };
    }, [
      processedLayers,
      openIdsArray,
      handleChange,
      renderNode,
      handleDragOpen,
      canNodeDrop
    ]);
    const { renderTree, scrollToNode } = index$1.useHeTree(data);
    React.useLayoutEffect(() => {
      if (selectedLayerId) {
        const parentLayers = layerUtils.findAllParentLayersRecursive(
          layers,
          selectedLayerId
        );
        const parentIds = parentLayers.map((layer) => layer.id);
        setOpenIdsArray((prevOpenIds) => {
          const newIds = [...prevOpenIds];
          let hasChanges = false;
          parentIds.forEach((id) => {
            if (!newIds.includes(id)) {
              newIds.push(id);
              hasChanges = true;
            }
          });
          return hasChanges ? newIds : prevOpenIds;
        });
      }
    }, [selectedLayerId, layers]);
    React.useLayoutEffect(() => {
      if (prevSelectedLayerId.current !== selectedLayerId) {
        prevSelectedLayerId.current = selectedLayerId;
        if (selectedLayerId) {
          scrollToNode(selectedLayerId);
        }
      }
    }, [scrollToNode, selectedLayerId]);
    const buttonClass = React.useMemo(() => {
      return utils.cn(
        button.buttonVariants({ variant: "default", size: "sm" }),
        "cursor-pointer w-full"
      );
    }, []);
    return /* @__PURE__ */ jsxRuntime.jsx(devProfiler.DevProfiler, { id: "LayersPanel", threshold: 40, children: /* @__PURE__ */ jsxRuntime.jsx(
      "div",
      {
        "data-testid": "layers-tree",
        className: utils.cn(
          className,
          "flex flex-col size-full overflow-x-auto pl-4"
        ),
        children: layers.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            dividerControl.DividerControl,
            {
              className: "border-l border-dashed border-primary",
              addPosition: 0,
              parentLayerId: selectedPageId
            }
          ),
          renderTree(),
          /* @__PURE__ */ jsxRuntime.jsx("div", { className: "relative", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-[1px] h-4 absolute left-0 bottom-0 border-l border-dashed border-primary bg-background" }) }),
          /* @__PURE__ */ jsxRuntime.jsx(
            dividerControl.DividerControl,
            {
              className: "border-l border-dashed border-primary",
              parentLayerId: selectedPageId
            }
          )
        ] }) : /* @__PURE__ */ jsxRuntime.jsx(
          addComponentPopover.AddComponentsPopover,
          {
            parentLayerId: selectedPageId,
            className: "w-full mt-4",
            children: /* @__PURE__ */ jsxRuntime.jsxs(
              "div",
              {
                className: buttonClass,
                children: [
                  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Add Component" }),
                  /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Plus, { className: "h-5 w-5" }),
                  /* @__PURE__ */ jsxRuntime.jsx("span", { children: "Add Component" })
                ]
              }
            )
          }
        )
      }
    ) });
  },
  (prevProps, nextProps) => {
    return index(prevProps.layers, nextProps.layers) && prevProps.selectedPageId === nextProps.selectedPageId && prevProps.selectedLayerId === nextProps.selectedLayerId && prevProps.className === nextProps.className;
  }
);
LayersTree.displayName = "LayersTree";

exports.LayersTree = LayersTree;
exports.default = LayersPanel;
