import { j as jsxRuntimeExports } from "../../../../../_virtual/jsx-runtime.js";
import { useEditorHelpers, useSelectedSectionId, useSelectedBrickId } from "../../../../../use-editor.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 { tx as D, css as E } from "../../../../style-system/dist/twind.js";
import { PanelBlockTitle } from "./PanelBlockTitle.js";
import { useState, useRef, useEffect } from "react";
import { RxDragHandleHorizontal } from "../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/rx/index.js";
import { HelpIcon } from "./json-form/HelpIcon.js";
import { DragDropContext, Droppable as ConnectedDroppable, Draggable as PublicDraggable } from "../../../../../node_modules/.pnpm/@hello-pangea_dnd@18.0.1_@types_react@19.1.13_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@hello-pangea/dnd/dist/dnd.esm.js";
import { useSections, useDraftHelpers } from "../../../../../use-page-data.js";
function PageHierarchy({
  brick: selectedBrick,
  className = "h-[calc(50cqh-58px)]"
}) {
  const { setSelectedBrickId, setSelectedSectionId } = useEditorHelpers();
  const sections = useSections();
  const selectedSectionId = useSelectedSectionId();
  const selectedBrickId = useSelectedBrickId();
  const draftHelpers = useDraftHelpers();
  const [hoverElement, setHoverElement] = useState();
  const lastElementHovered = useRef(null);
  const pageRef = useRef(null);
  const draggingRef = useRef(null);
  useEffect(() => {
    const currentElement = selectedSectionId ?? selectedBrickId;
    if (currentElement) {
      const domObj = document.getElementById(`hierarchy_${currentElement}`);
      if (domObj && "scrollIntoViewIfNeeded" in domObj && typeof domObj?.scrollIntoViewIfNeeded === "function") {
        domObj.scrollIntoViewIfNeeded({ behavior: "smooth", block: "center" });
      } else if (domObj) {
        domObj.scrollIntoView({
          behavior: "smooth",
          block: "center"
        });
      }
    }
  }, [selectedSectionId, selectedBrickId]);
  useEffect(() => {
    pageRef.current = document.getElementById("page-container");
  }, []);
  useEffect(() => {
    if (lastElementHovered.current) {
      lastElementHovered.current.classList.remove(D("outline-upstart-400"));
    }
    if (hoverElement) {
      lastElementHovered.current = document.getElementById(hoverElement.id);
      if (lastElementHovered.current) {
        lastElementHovered.current.classList.add(D("outline-upstart-400"));
        if (pageRef.current && !isVisibleInContainer(lastElementHovered.current, pageRef.current)) {
          lastElementHovered.current.scrollIntoView({ behavior: "smooth", block: "nearest" });
        }
      }
    }
  }, [hoverElement]);
  function BricksHierarchy({
    bricks,
    level = 0,
    // currentIndex = -1,
    isChild = false
  }) {
    return bricks.map((brick, brickIndex) => {
      const childBricks = "$children" in brick.props ? brick.props.$children : [];
      const hasChildren = childBricks.length > 0;
      const isContainer = fe[brick.type].isContainer;
      const Icon = fe[brick.type].icon;
      const brickName = fe[brick.type].name;
      return /* @__PURE__ */ jsxRuntimeExports.jsx(PublicDraggable, { draggableId: `hierarchy_${brick.id}`, index: brickIndex, children: (provided, snapshot) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          ref: provided.innerRef,
          ...provided.draggableProps,
          className: D("min-h-fit flex flex-col gap-2", isContainer && "mt-1 mr-1 ml-1 last:mb-1"),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              id: `hierarchy_${brick.id}`,
              "data-element-type": "brick",
              "data-brick-type": brick.type,
              "data-level": level,
              "data-has-children": hasChildren,
              className: D(
                "select-none cursor-pointer flex flex-col ",
                // level > 0 || (hasChildren && "ml-1.5"),
                isContainer && "rounded outline outline-2 min-h-fit",
                isContainer ? selectedBrick?.id === brick.id ? "outline-orange-300 " : "outline-transparent hover:(outline-orange-200)" : selectedBrick?.id === brick.id ? "outline-upstart-400 " : "outline-transparent hover:(outline-upstart-100)",
                snapshot.isDragging && "outline outline-2 outline-upstart-400 bg-upstart-100"
              ),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: D(
                      `flex items-center justify-between group/${brick.id} transition-all py-1 px-1.5`,
                      (isChild || level === 0) && E({
                        paddingLeft: `${(level + 1) * 10}px`
                      }),
                      isContainer ? selectedBrick?.id === brick.id ? "bg-orange-300 text-white font-bold" : "hover:bg-orange-50" : selectedBrick?.id === brick.id ? "bg-upstart-500 text-white font-bold" : "hover:bg-upstart-50"
                    ),
                    onClick: (e) => {
                      e.stopPropagation();
                      e.preventDefault();
                      setSelectedBrickId(brick.id);
                      setSelectedSectionId();
                      document.getElementById(brick.id)?.scrollIntoView({ behavior: "smooth", block: "nearest" });
                    },
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1.5 select-none", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-4 h-4" }),
                        " ",
                        brickName
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ...provided.dragHandleProps, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        RxDragHandleHorizontal,
                        {
                          className: `w-5 h-5 cursor-row-resize opacity-0 group-hover/${brick.id}:opacity-80 transition-opacity`
                        }
                      ) })
                    ]
                  }
                ),
                childBricks.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
                  ConnectedDroppable,
                  {
                    droppableId: `hierarchy_${brick.id}`,
                    direction: "vertical",
                    children: (provided2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "div",
                      {
                        ref: provided2.innerRef,
                        ...provided2.droppableProps,
                        className: D("hierarchy-container"),
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(BricksHierarchy, { bricks: childBricks, level: level + 1, isChild: true }),
                          provided2.placeholder
                        ]
                      }
                    )
                  }
                )
              ]
            }
          )
        },
        brick.id
      ) }, `hierarchy_${brick.id}`);
    });
  }
  const handleDragEnd = (result) => {
    const { source, destination, type, draggableId } = result;
    draggingRef.current = null;
    if (destination) {
      const draggableId2 = result.draggableId.replace(/^hierarchy_/, "");
      let { droppableId: destDroppable, index: destIndex } = destination;
      destDroppable = destDroppable.replace(/^hierarchy_/, "");
      let { droppableId: sourceDroppable } = source;
      sourceDroppable = sourceDroppable.replace(/^hierarchy_/, "");
      if (destDroppable === "main-hierarchy") {
        const newSectionOrder = Array.from(sections);
        const [reorderedSection] = newSectionOrder.splice(source.index, 1);
        newSectionOrder.splice(destination.index, 0, reorderedSection);
        draftHelpers.reorderSections(newSectionOrder.map((section) => section.id));
      } else if (type === "brick-hierarchy" || type === "DEFAULT") {
        if (sourceDroppable === destDroppable) {
          console.log("Reordering brick within the same section/parent", result);
          draftHelpers.reorderBrickWithin(draggableId2, destIndex);
        } else {
          const isDestSection = sections.some((s) => s.id === destDroppable);
          if (isDestSection) {
            draftHelpers.moveBrickToSection(draggableId2, destDroppable, destIndex);
          } else {
            draftHelpers.moveBrickToContainerBrick(draggableId2, destDroppable, destIndex);
          }
        }
      } else {
        console.warn("Unhandled drag type:", type);
        console.warn("Result:", result);
      }
    }
    const element = document.getElementById(draggableId);
    element?.style.removeProperty("z-index");
    if (element?.dataset.elementType === "section") {
      const descendants = element.querySelectorAll(".hierarchy-container");
      descendants.forEach((descendant) => {
        descendant.style.removeProperty("display");
        descendant.style.removeProperty("z-index");
      });
    } else if (element?.dataset.hasChildren === "true") {
      const lastChild = element.lastElementChild;
      if (lastChild) {
        lastChild.style.removeProperty("display");
        lastChild.style.removeProperty("z-index");
      }
    }
  };
  const onBeforeCapture = (cap) => {
    draggingRef.current = cap.draggableId;
    const element = document.getElementById(cap.draggableId);
    console.log("BEFORE CAPTURE", { cap, dataset: element?.dataset });
    element?.style.setProperty("z-index", "9999");
    if (element?.dataset.elementType === "section") {
      const descendants = element.querySelectorAll(".hierarchy-container");
      descendants.forEach((descendant) => {
        descendant.style.setProperty("display", "none", "important");
      });
    } else if (element?.dataset.hasChildren === "true") {
      const lastChild = element.lastElementChild;
      lastChild?.style.setProperty("display", "none", "important");
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: D("grow shrink-0 bg-red", className), onMouseLeave: () => setHoverElement(void 0), children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(PanelBlockTitle, { className: "border-t", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Hierarchy" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        HelpIcon,
        {
          help: `View and manage the hierarchy of sections and bricks on this page. Click on a section or brick to select it.
Drag and drop sections and bricks to reorder them.
          `
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(DragDropContext, { onDragEnd: handleDragEnd, onBeforeCapture, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ConnectedDroppable, { droppableId: "main-hierarchy", type: "hierarchy-section", direction: "vertical", children: (provided, snapshot) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          ref: provided.innerRef,
          className: D(
            "flex flex-col gap-1 py-2 pt-1 px-1 text-sm text-[80%] scrollbar-thin max-h-[calc(100%-38px)] overflow-y-auto"
          ),
          ...provided.droppableProps,
          children: [
            sections.map((section, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              PublicDraggable,
              {
                draggableId: `hierarchy_${section.id}`,
                index,
                children: (provided2, dragSnapshot) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    id: `hierarchy_${section.id}`,
                    "data-element-type": "section",
                    ref: provided2.innerRef,
                    ...provided2.draggableProps,
                    className: D(
                      "rounded group mt-1 outline outline-2 outline-transparent",
                      dragSnapshot.isDragging && "outline-upstart-400 bg-upstart-100",
                      section.id === selectedSectionId ? "outline-upstart-400" : "hover:(outline-upstart-100)"
                    ),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs(
                        "div",
                        {
                          className: D(
                            "py-1 px-1.5 rounded-t select-none flex justify-between items-center group min-h-fit",
                            section.id === selectedSectionId ? "bg-upstart-500 text-white font-bold cursor-default" : "hover:bg-upstart-50 cursor-pointer"
                          ),
                          onClick: (e) => {
                            if (e.defaultPrevented) {
                              console.log(
                                "Event was already handled, skipping click action on section hierarchy"
                              );
                              return;
                            }
                            e.preventDefault();
                            setSelectedBrickId();
                            setSelectedSectionId(section.id);
                            document.getElementById(section.id)?.scrollIntoView({ behavior: "smooth", block: "nearest" });
                          },
                          children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                              "Section ",
                              section.label ?? "Unnamed"
                            ] }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ...provided2.dragHandleProps, children: /* @__PURE__ */ jsxRuntimeExports.jsx(RxDragHandleHorizontal, { className: "w-5 h-5 cursor-row-resize opacity-0 group-hover:opacity-80 transition-opacity" }) })
                          ]
                        }
                      ),
                      /* @__PURE__ */ jsxRuntimeExports.jsx(ConnectedDroppable, { droppableId: `hierarchy_${section.id}`, type: "brick-hierarchy", children: (provided3) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                        "div",
                        {
                          ref: provided3.innerRef,
                          ...provided3.droppableProps,
                          className: D("hierarchy-container"),
                          children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(BricksHierarchy, { bricks: section.bricks }),
                            section.bricks.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
                              "div",
                              {
                                className: D(
                                  "w-full h-full px-2 py-1.5 flex items-center text-gray-500 font-normal"
                                ),
                                children: "No bricks in this section."
                              }
                            ),
                            provided3.placeholder
                          ]
                        }
                      ) })
                    ]
                  },
                  section.id
                )
              },
              `hierarchy_${section.id}`
            )),
            provided.placeholder
          ]
        }
      );
    } }) })
  ] });
}
function isVisibleInContainer(element, container) {
  const elementRect = element.getBoundingClientRect();
  const containerRect = container.getBoundingClientRect();
  const elementRelativeTop = elementRect.top - containerRect.top + container.scrollTop;
  const elementRelativeLeft = elementRect.left - containerRect.left + container.scrollLeft;
  const elementRelativeBottom = elementRelativeTop + element.offsetHeight;
  const elementRelativeRight = elementRelativeLeft + element.offsetWidth;
  const containerScrollTop = container.scrollTop;
  const containerScrollLeft = container.scrollLeft;
  const containerVisibleBottom = containerScrollTop + container.clientHeight;
  const containerVisibleRight = containerScrollLeft + container.clientWidth;
  return elementRelativeBottom > containerScrollTop && elementRelativeTop < containerVisibleBottom && elementRelativeRight > containerScrollLeft && elementRelativeLeft < containerVisibleRight;
}
export {
  PageHierarchy as default
};
//# sourceMappingURL=PageHierarchy.js.map
