import { j as J, a as S } from "./packages/sdk/dist/shared/chunk-GOMXZC4B.js";
import "@sinclair/typebox";
import "./packages/sdk/dist/shared/chunk-PSCN3VVA.js";
import "./packages/sdk/dist/shared/chunk-R6ATC4TC.js";
import "./packages/sdk/dist/shared/chunk-CFF6Q7O7.js";
import "./packages/sdk/dist/shared/chunk-IKC3FK7L.js";
import "./packages/sdk/dist/shared/chunk-E6XEI7IK.js";
import "./packages/sdk/dist/shared/chunk-SQ5T4AT5.js";
import "./packages/sdk/dist/shared/chunk-G5CJU6RD.js";
import "./packages/sdk/dist/shared/chunk-PSTFJ5IJ.js";
import "./packages/sdk/dist/shared/chunk-NJGXC7D6.js";
import "./packages/sdk/dist/shared/chunk-SXHDQ64Z.js";
import "./packages/sdk/dist/shared/chunk-QX6OGRRT.js";
import "./packages/sdk/dist/shared/chunk-FLOMNC6J.js";
import "./packages/sdk/dist/shared/chunk-PLSV746R.js";
import "./packages/sdk/dist/shared/chunk-WBZW5LVH.js";
import "./packages/sdk/dist/shared/chunk-WYVJE6J5.js";
import "./packages/sdk/dist/shared/chunk-I3VL6SRH.js";
import "./packages/sdk/dist/shared/chunk-B3EATRFX.js";
import "./packages/sdk/dist/shared/chunk-IKHZD2JH.js";
import "./packages/sdk/dist/shared/chunk-PXI7AHWS.js";
import { a as m } from "./packages/sdk/dist/shared/chunk-OIY3EPHO.js";
import "./packages/sdk/dist/shared/chunk-SY6DZLTC.js";
import "./packages/sdk/dist/shared/chunk-7A2JNQX3.js";
import "./packages/sdk/dist/shared/chunk-3YVJ2ELD.js";
import "./packages/sdk/dist/shared/chunk-AFVJZPLS.js";
import "./packages/sdk/dist/shared/chunk-A3GF4PYW.js";
import "./packages/sdk/dist/shared/chunk-W33JMRRN.js";
import { a as e } from "./packages/sdk/dist/shared/chunk-RDZK73KV.js";
import { enableMapSet } from "./node_modules/.pnpm/immer@10.1.1/node_modules/immer/dist/immer.js";
import { debounce, isEqual, unset, merge } from "lodash-es";
import { createContext, useContext, useEffect } from "react";
import { temporal } from "./node_modules/.pnpm/zundo@2.3.0_zustand@4.5.5_@types_react@19.1.13_immer@10.1.1_react@19.1.1_/node_modules/zundo/dist/index.js";
import { useStore } from "./node_modules/.pnpm/zustand@4.5.5_@types_react@19.1.13_immer@10.1.1_react@19.1.1/node_modules/zustand/esm/index.js";
import { subscribeWithSelector } from "./node_modules/.pnpm/zustand@4.5.5_@types_react@19.1.13_immer@10.1.1_react@19.1.1/node_modules/zustand/esm/middleware.js";
import { immer } from "./node_modules/.pnpm/zustand@4.5.5_@types_react@19.1.13_immer@10.1.1_react@19.1.1/node_modules/zustand/esm/middleware/immer.js";
import { createStore } from "./node_modules/.pnpm/zustand@4.5.5_@types_react@19.1.13_immer@10.1.1_react@19.1.1/node_modules/zustand/esm/vanilla.js";
enableMapSet();
const createDraftStore = (initProps) => {
  const DEFAULT_PROPS = {
    data: {},
    additionalAssets: [],
    brickMap: buildBrickMap(initProps.page.sections)
  };
  return createStore()(
    subscribeWithSelector(
      temporal(
        immer((set, _get) => ({
          ...DEFAULT_PROPS,
          ...initProps,
          addAdditionalAssets: (assets) => set((state) => {
            state.additionalAssets.push(...assets);
          }),
          upsertQuery: (query) => set((state) => {
            const existingIndex = state.site.attributes.queries?.findIndex((q) => q.id === query.id) ?? -1;
            if (existingIndex !== -1) {
              state.site.attributes.queries[existingIndex] = query;
            } else {
              state.site.attributes.queries ??= [];
              state.site.attributes.queries.push(query);
            }
          }),
          detachBrickFromContainer: (id) => set((state) => {
            const data = state.brickMap.get(id);
            e(data, `Cannot detach brick ${id}, it does not exist in the brickMap`);
            const { brick, sectionId, parentId } = data;
            if (!parentId) {
              console.warn("Cannot detach brick %s, it is not in a container", id);
              return;
            }
            const parentBrick = getBrickFromDraft(parentId, state);
            if (!parentBrick) {
              console.error("Cannot detach brick %s, its parent %s does not exist", id, parentId);
              return;
            }
            const parentSection = state.page.sections.find((s) => s.id === sectionId);
            if (!parentSection) {
              console.error("Cannot detach brick %s, its parent section %s does not exist", id, sectionId);
              return;
            }
            parentBrick.props.$children = parentBrick.props.$children?.filter(
              (child) => child.id !== id
            );
            const index = parentSection.bricks.findIndex((b) => b.id === parentId);
            parentSection.bricks.splice(index + 1, 0, {
              ...brick
            });
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          createEmptySection: (id, afterSectionId) => set((state) => {
            const count = state.page.sections.length;
            const nextOrder = 1 + (afterSectionId ? state.page.sections.find((s) => s.id === afterSectionId)?.order ?? count : count);
            const newSection = {
              id,
              order: nextOrder,
              label: `Section ${count + 1}`,
              bricks: [],
              props: {
                direction: "flex-row"
              }
            };
            state.page.sections.forEach((s) => {
              if (s.order >= nextOrder) {
                s.order += 1;
              }
            });
            state.page.sections.push(newSection);
          }),
          addPage: (page) => set((state) => {
            state.page = page;
            const existing = state.site.sitemap.find((p) => p.id === page.id);
            if (!existing) {
              state.site.sitemap.push(page);
            }
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          isFirstSection: (sectionId) => {
            const state = _get();
            return state.page.sections.find((s) => s.order === 0)?.id === sectionId;
          },
          setSections: (sections) => set((state) => {
            state.page.sections = sections;
            state.brickMap = buildBrickMap(sections);
          }),
          pickTheme: (themeId) => set((state) => {
            const theme = state.site.themes.find((t) => t.id === themeId);
            if (!theme) {
              console.error("Cannot pick theme %s, it does not exist", themeId);
              return;
            }
            state.site.theme = theme;
          }),
          setThemes: (themes) => set((state) => {
            const hasAlreadyThemes = state.site.themes.length > 0;
            state.site.themes = themes;
            if (!hasAlreadyThemes) {
              state.site.theme = themes[0];
            }
          }),
          setSitemap: (sitemap) => set((state) => {
            state.site.sitemap = sitemap;
          }),
          getPageDataForDuplication: () => {
            const state = _get();
            const pageCount = state.site.sitemap.length + 1;
            const newPage = {
              ...state.page,
              id: `page-${S()}`,
              label: `${state.page.label} (page ${pageCount})`,
              attributes: {
                ...state.page.attributes,
                path: `${state.page.attributes.path}-${pageCount}`
              }
            };
            return newPage;
          },
          isLastSection: (sectionId) => {
            const state = _get();
            return state.page.sections.find((s) => s.order === state.page.sections.length - 1)?.id === sectionId;
          },
          addDatasource: (datasource) => set((state) => {
            const existing = state.site.datasources.find((ds) => ds.id === datasource.id);
            if (existing) {
              console.error("Cannot add datasource %s, it already exists", datasource.id);
              return;
            }
            state.site.datasources.push(datasource);
          }),
          addDatarecord: (datarecord) => set((state) => {
            const existing = state.site.datarecords.find((dr) => dr.id === datarecord.id);
            if (existing) {
              console.error("Cannot add datarecord %s, it already exists", datarecord.id);
              return;
            }
            state.site.datarecords.push(datarecord);
          }),
          addSection: (section) => set((state) => {
            state.page.sections.push(section);
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          updateSection: (id, sectionData) => set((state) => {
            const sectionIndex = state.page.sections.findIndex((s) => s.id === id);
            if (sectionIndex !== -1) {
              state.page.sections[sectionIndex] = {
                ...state.page.sections[sectionIndex],
                ...sectionData
              };
            }
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          duplicateSection: (id) => set((state) => {
            const section = state.page.sections.find((s) => s.id === id);
            if (!section) {
              console.error("Cannot duplicate section %s, it does not exist", id);
              return;
            }
            const sectionIndex = state.page.sections.findIndex((s) => s.id === id);
            const newSection = {
              ...section,
              id: `s_${S()}`,
              order: section.order + 1,
              // increment order to place it after the original
              label: `${section.label} (copy)`,
              // generate new bricks with new IDs
              bricks: section.bricks.map((brick) => ({
                ...brick,
                id: `b_${S()}`,
                props: m({}, brick.props, {
                  $children: brick.props.$children?.map((child) => ({
                    ...child,
                    id: `b_${S()}`
                  }))
                })
              }))
            };
            state.page.sections.splice(sectionIndex + 1, 0, newSection);
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          deleteSection: (id) => set((state) => {
            const section = state.page.sections.find((s) => s.id === id);
            if (!section) {
              console.warn("Cannot delete section %s: not found", id);
              return null;
            }
            state.brickMap.forEach((m2) => {
              if (m2.sectionId === id) {
                state.brickMap.delete(m2.brick.id);
              }
            });
            state.page.sections = state.page.sections.filter((s) => s.id !== id);
          }),
          getSection: (id) => {
            return _get().page.sections.find((s) => s.id === id);
          },
          moveSectionUp: (sectionId) => set((state) => {
            const section = state.page.sections.find((s) => s.id === sectionId);
            state.page.sections.findIndex((s) => s.id === sectionId);
            e(section, "Section not found");
            const previous = state.page.sections.find((s) => s.order === section.order - 1);
            state.page.sections.findIndex((s) => s.order === section.order - 1);
            e(previous, "Previous section not found");
            const temp = section.order;
            section.order = previous.order;
            previous.order = temp;
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          moveSectionDown: (sectionId) => set((state) => {
            const section = state.page.sections.find((s) => s.id === sectionId);
            const sectionIndex = state.page.sections.findIndex((s) => s.id === sectionId);
            e(section, "Section not found");
            const next = state.page.sections.filter((s) => s.order > section.order).toSorted((a, b) => a.order - b.order).at(0);
            e(next, `Next section not found. No section with order > ${section.order} exists.`);
            const nextIndex = state.page.sections.findIndex((s) => s.id === next?.id);
            const currentOrder = section.order;
            const nextOrder = next.order;
            state.page.sections[sectionIndex].order = nextOrder;
            state.page.sections[nextIndex].order = currentOrder;
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          reorderSections: (orderedIds) => set((state) => {
            const newSections = [];
            let tmpOrder = 0;
            orderedIds.forEach((id) => {
              const section = state.page.sections.find((s) => s.id === id);
              if (section) {
                newSections.push({ ...section, order: ++tmpOrder });
              }
            });
            state.page.sections.forEach((section) => {
              if (!orderedIds.includes(section.id)) {
                newSections.push({ ...section, order: ++tmpOrder });
              }
            });
            state.page.sections = newSections;
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          deleteBrick: (id) => set((state) => {
            const brickToDelete = state.brickMap.get(id);
            if (!brickToDelete) {
              console.error("Cannot delete brick %s, it does not exist", id);
              return;
            }
            const childrenIds = [];
            const collectChildrenIds = (brickId) => {
              const map = state.brickMap.get(brickId);
              if (map?.brick.props?.$children) {
                const children = map.brick.props.$children;
                children.forEach((child) => {
                  childrenIds.push(child.id);
                  collectChildrenIds(child.id);
                });
              }
            };
            collectChildrenIds(id);
            const { sectionId, parentId } = brickToDelete;
            const section = state.page.sections.find((s) => s.id === sectionId);
            if (parentId) {
              const parentBrick = getBrickFromDraft(parentId, state);
              if (parentBrick?.props.$children) {
                const index = parentBrick.props.$children.findIndex((b) => b.id === id);
                parentBrick.props.$children.splice(index, 1);
              }
            } else if (section) {
              section.bricks = section.bricks.filter((b) => b.id !== id);
            }
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          duplicateBrick: (id) => set((state) => {
            const original = state.brickMap.get(id);
            if (!original) {
              console.error("Cannot duplicate brick %s, it does not exist", id);
              return;
            }
            const deepCloneBrick = (brick) => {
              const newId = `brick-${S()}`;
              const newBrick2 = {
                ...brick,
                id: newId,
                props: { ...brick.props },
                mobileProps: brick.mobileProps ? { ...brick.mobileProps } : void 0
              };
              if (brick.props.$children) {
                const children = brick.props.$children;
                newBrick2.props.$children = children.map((child) => deepCloneBrick(child));
              }
              return newBrick2;
            };
            const newBrick = deepCloneBrick(original.brick);
            const { sectionId, parentId } = original;
            if (parentId) {
              const parentBrick = getBrickFromDraft(parentId, state);
              if (parentBrick?.props.$children) {
                const children = parentBrick.props.$children;
                const originalIndex = children.findIndex((b) => b.id === id);
                parentBrick.props.$children.splice(originalIndex + 1, 0, newBrick);
              }
            } else {
              const section = state.page.sections.find((s) => s.id === sectionId);
              if (section) {
                const originalIndex = section.bricks.findIndex((b) => b.id === id);
                section.bricks.splice(originalIndex + 1, 0, newBrick);
              }
            }
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          updateBrickProps: (id, props, isMobileProps) => set((state) => {
            const brick = getBrickFromDraft(id, state);
            if (brick) {
              if (isMobileProps) {
                brick.mobileProps = m({}, brick.mobileProps, props, {
                  lastTouched: Date.now()
                });
              } else {
                brick.props = m({}, brick.props, props, {
                  lastTouched: Date.now()
                });
              }
              state.brickMap = buildBrickMap(state.page.sections);
            } else {
              console.error("Cannot update props for brick %s, it does not exist in the brick map", id);
            }
          }),
          updateSectionProps: (id, props, isMobileProps) => set((state) => {
            const section = state.page.sections.find((s) => s.id === id);
            if (section) {
              if (isMobileProps) {
                section.mobileProps = m({}, section.mobileProps, props, {
                  lastTouched: Date.now()
                });
              } else {
                section.props = m({}, section.props, props, {
                  lastTouched: Date.now()
                });
              }
              state.brickMap = buildBrickMap(state.page.sections);
            } else {
              console.warn("Cannot update section %s, it does not exist", id);
            }
          }),
          /**
           * Move a brick inside its container or its section
           * If the brick does not belong to a container, it will be moved within its section
           */
          moveBrick: (id, to) => set((state) => {
            let children = [];
            let currentIndex = -1;
            const roParentBrick = state.getParentBrick(id);
            if (roParentBrick) {
              const parentBrick = getBrickFromDraft(roParentBrick.id, state);
              children = parentBrick.props.$children;
              currentIndex = children.findIndex((b) => b.id === id);
            } else {
              const section = getBrickSection(id, state);
              children = section.bricks;
              currentIndex = children.findIndex((b) => b.id === id);
            }
            const newIndex = to === "previous" ? Math.max(0, currentIndex - 1) : Math.min(children.length - 1, currentIndex + 1);
            if (newIndex === currentIndex) {
              return;
            }
            const [brickToMove] = children.splice(currentIndex, 1);
            children.splice(newIndex, 0, brickToMove);
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          /**
           * Reorder a brick within its section using indices
           */
          reorderBrickWithin: (brickId, toIndex) => set((state) => {
            const brickMapping = state.brickMap.get(brickId);
            if (!brickMapping) {
              console.error("Cannot reorder brick %s, brick mapping not found", brickId);
              return;
            }
            const { sectionId, parentId } = brickMapping;
            console.debug("Reordering brick %s in section %s, parent %s", brickId, sectionId, parentId);
            if (parentId) {
              const parentBrick = getBrickFromDraft(parentId, state);
              if (parentBrick?.props.$children) {
                const children = parentBrick.props.$children;
                const originalIndex = children.findIndex((b) => b.id === brickId);
                if (originalIndex === -1) {
                  console.error("Cannot reorder brick %s, it does not exist in parent's children", brickId);
                  console.log({ sectionId, parentId });
                  return;
                }
                const [movedBrick] = children.splice(originalIndex, 1);
                children.splice(toIndex, 0, movedBrick);
              } else {
                console.error(
                  "Cannot reorder brick %s, parent brick %s has no children",
                  brickId,
                  parentId
                );
              }
            } else {
              const section = state.page.sections.find((s) => s.id === sectionId);
              if (section) {
                const originalIndex = section.bricks.findIndex((b) => b.id === brickId);
                if (originalIndex === -1) {
                  console.error(
                    "Cannot reorder brick %s, it does not exist in section %s",
                    brickId,
                    sectionId
                  );
                  return;
                }
                const [movedBrick] = section.bricks.splice(originalIndex, 1);
                section.bricks.splice(toIndex, 0, movedBrick);
              }
            }
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          moveBrickToContainerBrick: (id, parentId, index) => set((state) => {
            const brick = state.getBrick(id);
            const parent = getBrickFromDraft(parentId, state);
            const brickMapping = state.brickMap.get(id);
            if (!brick || !parent || !brickMapping) {
              console.error("Cannot move brick %s to new parent, brick or new parent is null", id);
              return;
            }
            if (!("$children" in parent.props)) {
              console.error("Cannot move brick %s, parent brick %s is not a container", id, parentId);
              return;
            }
            const { sectionId, parentId: currentParentId } = brickMapping;
            if (currentParentId) {
              const currentParent = getBrickFromDraft(currentParentId, state);
              if (currentParent?.props.$children) {
                currentParent.props.$children = currentParent.props.$children.filter(
                  (child) => child.id !== id
                );
              }
            } else {
              const section = state.page.sections.find((s) => s.id === sectionId);
              if (section) {
                section.bricks = section.bricks.filter((b) => b.id !== id);
              }
            }
            if (!parent.props.$children) {
              parent.props.$children = [];
            }
            parent.props.$children.splice(index, 0, brick);
            state.brickMap = buildBrickMap(state.page.sections);
          }),
          /**
           * @todo check bricksmap update
           */
          moveBrickToSection: (id, sectionId, index) => set((state) => {
            const brick = state.getBrick(id);
            if (!sectionId) {
              sectionId = state.brickMap.get(id)?.sectionId;
            }
            const targetSection = state.page.sections.find((s) => s.id === sectionId);
            const brickMapping = state.brickMap.get(id);
            if (!brick || !targetSection || !brickMapping) {
              console.error(
                "Cannot move brick %s to section %s, brick or section not found",
                id,
                sectionId
              );
              return;
            }
            const { sectionId: currentSectionId, parentId: currentParentId } = brickMapping;
            if (currentParentId) {
              const currentParent = getBrickFromDraft(currentParentId, state);
              if (currentParent?.props.$children) {
                currentParent.props.$children = currentParent.props.$children.filter(
                  (child) => child.id !== id
                );
              }
            } else {
              const currentSection = state.page.sections.find((s) => s.id === currentSectionId);
              if (currentSection) {
                currentSection.bricks = currentSection.bricks.filter((b) => b.id !== id);
              }
            }
            if (typeof index === "number") {
              targetSection.bricks.splice(index, 0, brick);
            } else {
              targetSection.bricks.push(brick);
            }
            state.brickMap.set(id, {
              brick,
              sectionId,
              parentId: null
              // Top level in section
            });
            const updateChildMappings = (brickId, newSectionId, newParentId) => {
              const mapping = state.brickMap.get(brickId);
              if (mapping?.brick.props?.$children) {
                const children = mapping.brick.props.$children;
                children.forEach((child) => {
                  state.brickMap.set(child.id, {
                    brick: child,
                    sectionId: newSectionId,
                    parentId: brickId
                  });
                  updateChildMappings(child.id, newSectionId);
                });
              }
            };
            updateChildMappings(id, sectionId);
          }),
          /**
           * @deprecated Use getBrickFromDraft instead
           */
          getBrick: (id) => {
            return _get().brickMap.get(id)?.brick;
          },
          getParentBrick: (id) => {
            const map = _get().brickMap;
            const { parentId } = map.get(id) ?? {};
            if (parentId) {
              return map.get(parentId)?.brick;
            }
          },
          getPositionWithinParent: (brickId) => {
            const parent = _get().getParentBrick(brickId);
            if (parent && "$children" in parent.props) {
              return parent.props.$children.findIndex((b) => b.id === brickId);
            }
          },
          canMoveTo: (brickId, to) => {
            const parent = _get().getParentBrick(brickId);
            if (parent && "$children" in parent.props) {
              const children = parent.props.$children;
              const index2 = children.findIndex((b) => b.id === brickId);
              return to === "previous" ? index2 > 0 : index2 < children.length - 1;
            }
            const section = getBrickSection(brickId, _get());
            const index = section?.bricks.findIndex((b) => b.id === brickId) ?? -1;
            return to === "previous" ? index > 0 : index < section?.bricks.length - 1;
          },
          setPreviewTheme: (theme) => set((state) => {
            state.previewTheme = theme;
          }),
          validatePreviewTheme: (accept) => set((state) => {
            if (state.previewTheme && accept) {
              state.site.theme = state.previewTheme;
            }
            state.previewTheme = void 0;
          }),
          cancelPreviewTheme: () => set((state) => {
            state.previewTheme = void 0;
          }),
          setTheme: (theme) => set((state) => {
            state.site.theme = theme;
          }),
          toggleBrickVisibility: (id, breakpoint) => set((state) => {
            const brick = getBrickFromDraft(id, state);
            if (brick) {
              brick.props.hidden ??= { desktop: false, mobile: false };
              brick.props.hidden[breakpoint] = !brick.props.hidden?.[breakpoint];
            }
          }),
          addBrick: (brick, sectionId, index, parentContainerId) => set((state) => {
            const section = state.page.sections.find((s) => s.id === sectionId);
            if (!section) {
              console.error("Cannot add brick, section %s does not exist", sectionId);
              return;
            }
            if (parentContainerId) {
              console.log("Adding brick to parent container", parentContainerId);
              const parentBrick = getBrickFromMap(parentContainerId, state);
              if (!parentBrick) {
                console.warn("Cannot add brick, parent container %s does not exist", parentContainerId);
                return;
              }
              const parentSection = state.page.sections.find((s) => s.id === sectionId);
              if (!parentSection) {
                console.warn("Cannot add brick, parent section %s does not exist", sectionId);
                return;
              }
              const parentBrickInSection = parentSection.bricks.find((b) => b.id === parentContainerId);
              if (!parentBrickInSection) {
                console.warn(
                  "Cannot add brick, parent brick %s does not exist in section %s",
                  parentContainerId,
                  sectionId
                );
                return;
              }
              if (!parentBrickInSection.props.$children) {
                console.warn("Brick added to a container without $children, initializing it");
                parentBrickInSection.props.$children = [];
              }
              parentBrickInSection.props.$children.push(brick);
            } else {
              section.bricks.splice(index, 0, brick);
            }
            state.brickMap.set(brick.id, {
              brick,
              sectionId,
              parentId: parentContainerId ?? null
            });
            if (brick.props?.$children) {
              const addChildrenToBrickMap = (children, parentId) => {
                children.forEach((child) => {
                  state.brickMap.set(child.id, {
                    brick: child,
                    sectionId,
                    parentId
                  });
                  if (child.props?.$children) {
                    addChildrenToBrickMap(child.props.$children, child.id);
                  }
                });
              };
              console.log("Adding children to brick map", brick.props.$children);
              addChildrenToBrickMap(brick.props.$children, brick.id);
            }
          }),
          updatePageAttributes: (attr) => set((state) => {
            state.page.attributes = merge({}, _get().page.attributes, attr);
          }),
          deletePageAttribute: (key) => set((state) => {
            unset(state.page.attributes, key);
          }),
          updateSiteAttributes: (attr) => set((state) => {
            state.site.attributes = merge({}, _get().site.attributes, attr);
          }),
          deleteSiteAttribute: (key) => set((state) => {
            unset(state.site.attributes, key);
          }),
          setVersion: (version) => set((state) => {
            state.page.version = version;
          }),
          setLastSaved: (date) => set((state) => {
            state.lastSaved = date;
          }),
          setDirty: (dirty) => set((state) => {
            state.dirty = dirty;
          })
        })),
        {
          // limit undo history to 100
          limit: 100,
          equality: (pastState, currentState) => isEqual(pastState, currentState),
          partialize: (state) => Object.fromEntries(
            Object.entries(state).filter(([key]) => ["sections", "attr"].includes(key))
          )
          // handleSet: (handleSet) =>
          //   debounce<typeof handleSet>((state) => {
          //     if (state) {
          //       handleSet(state);
          //     }
          //   }, 200),
        }
      )
    )
  );
};
const DraftStoreContext = createContext(null);
const usePageContext = () => {
  const store = useContext(DraftStoreContext);
  e(store, "useDraftStoreContext must be used within a DraftStoreContext");
  return store;
};
const useDraftUndoManager = () => {
  const ctx = usePageContext();
  return ctx.temporal.getState();
};
const useSitemap = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.site.sitemap);
};
const useGenerationState = () => {
  const draft = usePageContext();
  return useStore(draft, (state) => {
    const hasSitemap = state.site.sitemap.length > 0;
    const hasThemesGenerated = state.site.themes.length > 0;
    const hasPages = state.page.id !== "_default_";
    const isReady = hasSitemap && hasThemesGenerated && hasPages && state.page.sections.length > 0 && state.page.sections.some((s) => s.bricks.length > 0);
    const isSetup = new URL(window.location.href).searchParams.get("action") === "setup";
    return {
      hasSitemap,
      hasThemesGenerated,
      isSetup,
      isReady: !isSetup || isReady
    };
  });
};
const useThemes = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.site.themes);
};
const useDraft = () => {
  const ctx = usePageContext();
  return useStore(ctx);
};
function useSiteQueries() {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.site.attributes.queries ?? []);
}
function useSiteQuery(queryId) {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.site.attributes.queries?.find((q) => q.id === queryId) ?? null);
}
function useParentBrick(brickId) {
  const ctx = usePageContext();
  const getParentBrick = useStore(ctx, (state) => state.getParentBrick);
  return getParentBrick(brickId);
}
function usePageVersion() {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.page.version);
}
function useLastSaved() {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.lastSaved);
}
const useSections = () => {
  const ctx = usePageContext();
  const sections = useStore(ctx, (state) => state.page.sections);
  const siteAttributes = useSiteAttributes();
  const pageAttributes = usePageAttributes();
  return J(sections, siteAttributes, pageAttributes);
};
const useSection = (sectionId) => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => {
    const section = state.page.sections.find((s) => sectionId && s.id === sectionId);
    if (!section) {
      return null;
    }
    return {
      section,
      bricks: Array.from(state.brickMap).filter(([, rec]) => rec.sectionId === sectionId)
    };
  });
};
const useBrick = (brickId) => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => {
    return brickId ? getBrickFromDraft(brickId, state) : null;
  });
};
const useSectionByBrickId = (brickId) => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => getBrickSection(brickId, state));
};
const usePageAttributes = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.page.attributes);
};
const useSiteAttributes = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.site.attributes);
};
const useData = (editable) => {
  const ctx = usePageContext();
  const pageQueries = usePageQueries();
  return useStore(ctx, (state) => {
    if (!editable) {
      console.log("useData: returning production data");
      return state.data;
    }
    const data = {};
    for (const query of pageQueries) {
      const examples = query.datasource.schema.items.examples;
      if (examples) {
        data[query.alias] = examples;
      }
    }
    return data;
  });
};
const useLoopedQuery = (loopAlias) => {
  const pageQueries = usePageQueries();
  return pageQueries.find((q) => q.alias === loopAlias) ?? null;
};
function useLoopAlias(brickId) {
  const ctx = usePageContext();
  const getParentBrick = useStore(ctx, (state) => state.getParentBrick);
  let currentBrickId = brickId;
  while (currentBrickId) {
    const brick = getBrickFromDraft(currentBrickId, ctx.getState());
    if (brick?.props.loop?.over) {
      return brick?.props.loop.over;
    }
    currentBrickId = getParentBrick(currentBrickId)?.id;
  }
  return null;
}
const usePageQueries = () => {
  const ctx = usePageContext();
  return useStore(
    ctx,
    (state) => state.page.attributes.queries?.map((pageQuery) => {
      const queryInfo = state.site.attributes.queries?.find((q) => q.id === pageQuery.queryId);
      if (!queryInfo) {
        console.log(`WARN: Query with id ${pageQuery.queryId} not found in the store`);
        return null;
      }
      const datasource = state.site.datasources.find((ds) => ds.id === queryInfo.datasourceId);
      if (!datasource) {
        console.warn(
          `Datasource with id ${queryInfo.datasourceId} not found for query ${pageQuery.queryId}`
        );
        return null;
      }
      return {
        ...pageQuery,
        queryInfo,
        datasource
      };
    }).filter((item) => item !== null) ?? []
  );
};
const useDraftHelpers = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => ({
    addAdditionalAssets: state.addAdditionalAssets,
    deleteBrick: state.deleteBrick,
    detachBrickFromContainer: state.detachBrickFromContainer,
    updateSiteAttributes: state.updateSiteAttributes,
    updatePageAttributes: state.updatePageAttributes,
    upsertQuery: state.upsertQuery,
    setSections: state.setSections,
    setThemes: state.setThemes,
    setTheme: state.setTheme,
    pickTheme: state.pickTheme,
    setSitemap: state.setSitemap,
    addPage: state.addPage,
    addDatasource: state.addDatasource,
    addDatarecord: state.addDatarecord,
    duplicateBrick: state.duplicateBrick,
    addBrick: state.addBrick,
    getBrick: state.getBrick,
    validatePreviewTheme: state.validatePreviewTheme,
    duplicateSection: state.duplicateSection,
    toggleBrickVisibilityPerBreakpoint: state.toggleBrickVisibility,
    getParentBrick: state.getParentBrick,
    updateBrickProps: state.updateBrickProps,
    moveBrick: state.moveBrick,
    reorderBrickWithin: state.reorderBrickWithin,
    getPositionWithinParent: state.getPositionWithinParent,
    canMoveTo: state.canMoveTo,
    moveBrickToContainerBrick: state.moveBrickToContainerBrick,
    moveBrickToSection: state.moveBrickToSection,
    deleteSection: state.deleteSection,
    moveSectionUp: state.moveSectionUp,
    moveSectionDown: state.moveSectionDown,
    reorderSections: state.reorderSections,
    updateSection: state.updateSection,
    updateSectionProps: state.updateSectionProps,
    addSection: state.addSection,
    createEmptySection: state.createEmptySection,
    isFirstSection: state.isFirstSection,
    isLastSection: state.isLastSection
  }));
};
const usePage = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.page);
};
const useSite = () => {
  const draft = usePageContext();
  const draftData = useStore(draft, (state) => state.site);
  return draftData;
};
const useTheme = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.site.theme);
};
const usePreviewTheme = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.previewTheme);
};
const useSectionsSubscribe = (callback) => {
  const ctx = usePageContext();
  useEffect(() => {
    return ctx.subscribe((state) => state?.page.sections ?? [], debounce(callback, 200), {
      fireImmediately: false
    });
  }, []);
};
const usePageAttributesSubscribe = (callback) => {
  const ctx = usePageContext();
  useEffect(() => {
    return ctx.subscribe((state) => state.page.attributes, callback, {
      equalityFn: isEqual
    });
  }, []);
};
const useSiteAttributesSubscribe = (callback) => {
  const ctx = usePageContext();
  useEffect(() => {
    return ctx.subscribe((state) => state.site.attributes, callback, {
      equalityFn: isEqual
    });
  }, []);
};
const useThemeSubscribe = (callback) => {
  const ctx = usePageContext();
  useEffect(() => {
    return ctx.subscribe((state) => state.site.theme, callback);
  }, []);
};
const usePagePathParams = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => {
    const path = state.page.attributes.path;
    const regex = /:([a-zA-Z0-9_]+)/g;
    const matches = Array.from(path.matchAll(regex));
    return matches.map((match) => match[0]);
  });
};
const useAdditionalAssets = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.additionalAssets);
};
function getBrickFromMap(id, state) {
  const { brick } = state.brickMap.get(id) ?? {};
  return brick;
}
function getBrickSection(brickId, state) {
  const mapping = state.brickMap.get(brickId);
  if (mapping) {
    return state.page.sections.find((s) => s.id === mapping.sectionId);
  }
}
function getBrickFromDraft(id, state) {
  for (const section of state.page.sections) {
    const brick = section.bricks.find((b) => b.id === id);
    if (brick) {
      return brick;
    }
    const findInChildren = (children) => {
      for (const child of children) {
        if (child.id === id) {
          return child;
        }
        if (child.props?.$children) {
          const found = findInChildren(child.props.$children);
          if (found) {
            return found;
          }
        }
      }
      return void 0;
    };
    const foundInChildren = findInChildren(section.bricks);
    if (foundInChildren) {
      return foundInChildren;
    }
  }
  return null;
}
const useSitePrompt = () => {
  const ctx = usePageContext();
  return useStore(ctx, (state) => state.site.sitePrompt);
};
function buildBrickMap(sections) {
  const brickMap = /* @__PURE__ */ new Map();
  function collectBrick(brick, sectionId, parentId) {
    brickMap.set(brick.id, { brick, sectionId, parentId });
    if (brick.props?.$children) {
      const children = brick.props.$children;
      children.forEach((child) => collectBrick(child, sectionId, brick.id));
    }
  }
  sections.forEach((section) => {
    section.bricks.forEach((brick) => collectBrick(brick, section.id, null));
  });
  return brickMap;
}
export {
  DraftStoreContext,
  createDraftStore,
  useAdditionalAssets,
  useBrick,
  useData,
  useDraft,
  useDraftHelpers,
  useDraftUndoManager,
  useGenerationState,
  useLastSaved,
  useLoopAlias,
  useLoopedQuery,
  usePage,
  usePageAttributes,
  usePageAttributesSubscribe,
  usePageContext,
  usePagePathParams,
  usePageQueries,
  usePageVersion,
  useParentBrick,
  usePreviewTheme,
  useSection,
  useSectionByBrickId,
  useSections,
  useSectionsSubscribe,
  useSite,
  useSiteAttributes,
  useSiteAttributesSubscribe,
  useSitePrompt,
  useSiteQueries,
  useSiteQuery,
  useSitemap,
  useTheme,
  useThemeSubscribe,
  useThemes
};
//# sourceMappingURL=use-page-data.js.map
