'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const index = require('../../../../../../../_virtual/index.cjs');
const button = require('../../../button.cjs');
const LucideIcons = require('lucide-react');
const utils = require('../../../../lib/utils.cjs');
const layerUtils = require('../../../../lib/ui-builder/store/layer-utils.cjs');
const dropdownMenu = require('../../../dropdown-menu.cjs');
const addComponentPopover = require('./add-component-popover.cjs');
const nameEdit = require('./name-edit.cjs');
const editorStore = require('../../../../lib/ui-builder/store/editor-store.cjs');
const schemaUtils = require('../../../../lib/ui-builder/store/schema-utils.cjs');

const TreeRowNode = React.memo(({
  node,
  id,
  level,
  open,
  draggable,
  onToggle,
  nodeAttributes,
  selectedLayerId,
  selectLayer,
  removeLayer,
  duplicateLayer,
  updateLayer
}) => {
  const componentRegistry = editorStore.useEditorStore((state) => state.registry);
  const [isRenaming, setIsRenaming] = React.useState(false);
  const [popoverOrMenuOpen, setPopoverOrMenuOpen] = React.useState(false);
  const allowPagesCreation = editorStore.useEditorStore(
    (state) => state.allowPagesCreation
  );
  const allowPagesDeletion = editorStore.useEditorStore(
    (state) => state.allowPagesDeletion
  );
  const handleOpen = React.useCallback(() => {
    onToggle(id, !open);
  }, [id, open, onToggle]);
  const handleSelect = React.useCallback(() => {
    selectLayer(node.id);
  }, [node.id, selectLayer]);
  const handleRemove = React.useCallback(() => {
    removeLayer(node.id);
  }, [node.id, removeLayer]);
  const handleDuplicate = React.useCallback(() => {
    duplicateLayer(node.id);
  }, [node.id, duplicateLayer]);
  const handleRenameClick = React.useCallback(() => {
    setIsRenaming(true);
  }, []);
  const handleSaveRename = React.useCallback(
    (newName) => {
      updateLayer(node.id, {}, { name: newName });
      setIsRenaming(false);
    },
    [node.id, updateLayer]
  );
  const handleCancelRename = React.useCallback(() => {
    setIsRenaming(false);
  }, []);
  const canRenderAddChild = React.useMemo(() => {
    const componentDef = componentRegistry[node.type];
    if (!componentDef) return false;
    const canAddChildren = "shape" in componentDef.schema && schemaUtils.hasAnyChildrenField(componentDef.schema) && !schemaUtils.hasChildrenFieldOfTypeString(componentDef.schema);
    return canAddChildren;
  }, [node, componentRegistry]);
  const { key, ...rest } = nodeAttributes;
  if (!node) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { ...rest, className: "w-fit flex items-center group relative", children: [
    /* @__PURE__ */ jsxRuntime.jsx(RowOffset, { level }),
    layerUtils.hasLayerChildren(node) && node.children.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
      button.Button,
      {
        className: "w-4 ml-3 p-0",
        variant: "ghost",
        size: "sm",
        onClick: handleOpen,
        children: open ? /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ChevronDown, { className: "size-4 bg-secondary rounded-full" }) : /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ChevronRight, { className: "size-4 bg-secondary rounded-full" })
      }
    ) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "size-4 rounded-none opacity-0 ml-3" }),
    isRenaming ? /* @__PURE__ */ jsxRuntime.jsx(
      nameEdit.NameEdit,
      {
        initialName: node.name ?? "",
        onSave: handleSaveRename,
        onCancel: handleCancelRename
      }
    ) : /* @__PURE__ */ jsxRuntime.jsxs(
      button.Button,
      {
        variant: "ghost",
        size: "sm",
        className: utils.cn(
          "pl-0 gap-0",
          node.id === selectedLayerId ? "text-primary" : "text-muted-foreground"
        ),
        onClick: handleSelect,
        children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            "div",
            {
              className: utils.cn(
                "w-4 h-full flex items-center justify-center cursor-move opacity-0 rounded group-hover:opacity-100 hover:bg-muted-foreground hover:text-muted transition-opacity duration-200 ease-in-out",
                popoverOrMenuOpen ? "opacity-100" : "opacity-0"
              ),
              draggable,
              children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.GripVertical, { className: "size-4" })
            }
          ),
          node.name
        ]
      }
    ),
    canRenderAddChild && /* @__PURE__ */ jsxRuntime.jsx(
      addComponentPopover.AddComponentsPopover,
      {
        parentLayerId: node.id,
        onOpenChange: setPopoverOrMenuOpen,
        children: /* @__PURE__ */ jsxRuntime.jsxs(
          button.Button,
          {
            variant: "ghost",
            size: "icon",
            className: utils.cn(
              "opacity-0 group-hover:opacity-100 transition-opacity duration-200 ease-in-out",
              popoverOrMenuOpen ? "opacity-100" : "opacity-0"
            ),
            children: [
              /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Plus, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Add component" })
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsxs(dropdownMenu.DropdownMenu, { onOpenChange: setPopoverOrMenuOpen, children: [
      /* @__PURE__ */ jsxRuntime.jsx(dropdownMenu.DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsx(
        button.Button,
        {
          className: utils.cn(
            "opacity-0 group-hover:opacity-100 transition-opacity duration-200 ease-in-out",
            popoverOrMenuOpen ? "opacity-100" : "opacity-0"
          ),
          variant: "ghost",
          size: "icon",
          "aria-label": "More options",
          children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.MoreVertical, { className: "h-4 w-4" })
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsxs(dropdownMenu.DropdownMenuContent, { align: "end", children: [
        /* @__PURE__ */ jsxRuntime.jsx(dropdownMenu.DropdownMenuItem, { onClick: handleRenameClick, children: "Rename" }),
        allowPagesCreation && /* @__PURE__ */ jsxRuntime.jsx(dropdownMenu.DropdownMenuItem, { onClick: handleDuplicate, children: "Duplicate" }),
        allowPagesDeletion && /* @__PURE__ */ jsxRuntime.jsx(dropdownMenu.DropdownMenuItem, { onClick: handleRemove, children: "Remove" })
      ] })
    ] })
  ] }, key);
}, (prevProps, nextProps) => {
  if (prevProps.node.id !== nextProps.node.id) return false;
  if (!index(prevProps.node, nextProps.node)) return false;
  if (prevProps.id !== nextProps.id) return false;
  if (prevProps.level !== nextProps.level) return false;
  if (prevProps.open !== nextProps.open) return false;
  if (prevProps.draggable !== nextProps.draggable) return false;
  if (prevProps.selectedLayerId !== nextProps.selectedLayerId) return false;
  if (!index(prevProps.nodeAttributes, nextProps.nodeAttributes)) return false;
  if (prevProps.onToggle !== nextProps.onToggle) return false;
  if (prevProps.selectLayer !== nextProps.selectLayer) return false;
  if (prevProps.removeLayer !== nextProps.removeLayer) return false;
  if (prevProps.duplicateLayer !== nextProps.duplicateLayer) return false;
  if (prevProps.updateLayer !== nextProps.updateLayer) return false;
  return true;
});
TreeRowNode.displayName = "TreeRowNode";
const RowOffset = ({ level }) => {
  const style = React.useMemo(() => ({
    width: level * 20
  }), [level]);
  const arr = React.useMemo(() => Array.from({ length: level }), [level]);
  return /* @__PURE__ */ jsxRuntime.jsx(
    "div",
    {
      className: "z-[-1] left-0 pointer-events-none absolute flex flex-row bottom-[20px] h-full",
      style,
      children: arr.map((_, index) => /* @__PURE__ */ jsxRuntime.jsx(
        "div",
        {
          className: utils.cn(
            "w-5 h-full border-l border-dashed border-primary bg-background",
            index === level - 1 && "border-b "
          )
        },
        index
      ))
    }
  );
};
const TreeRowPlaceholder = ({ nodeAttributes }) => {
  const { key, ...rest } = nodeAttributes;
  return /* @__PURE__ */ jsxRuntime.jsx("div", { ...rest, className: "w-40 h-2", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "size-full border-b-2 border-blue-500 border-dashed" }) }, key);
};

exports.TreeRowNode = TreeRowNode;
exports.TreeRowPlaceholder = TreeRowPlaceholder;
