import { j as jsxRuntimeExports } from "./_virtual/jsx-runtime.js";
import { useEditorEnabled, useChatVisible, usePanel, useEditorHelpers, useSelectedBrickId, useSelectedSectionId, useDebugMode } from "./use-editor.js";
import { lazy, useRef, useEffect, Suspense } from "react";
import { tw as e, css as E, tx as D } from "./packages/style-system/dist/twind.js";
import "./node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import { Toaster as Oe } from "./node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/react-hot-toast/dist/index.js";
import { usePageAutoSave } from "./packages/components/src/editor/hooks/use-page-autosave.js";
import { getThemeCss } from "./get-theme-css.js";
import { useEditorHotKeys } from "./packages/components/src/editor/hooks/use-editor-hot-keys.js";
import ThemesPreviewList from "./packages/components/src/editor/components/ThemesPreviewList.js";
import BlankWaitPage from "./packages/components/src/editor/components/BlankWaitPage.js";
import { l as X } 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 { isEqual } from "lodash-es";
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 { useIsLocalDev } from "./packages/components/src/editor/hooks/use-is-local-dev.js";
import { useDraft, useSections, useThemes, useGenerationState, useDraftHelpers } from "./use-page-data.js";
import { DragDropProvider } from "./node_modules/.pnpm/@dnd-kit_react@0.1.21_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@dnd-kit/react/index.js";
import { move } from "./node_modules/.pnpm/@dnd-kit_helpers@0.1.21/node_modules/@dnd-kit/helpers/dist/index.js";
import Modal from "./packages/components/src/editor/components/Modal.js";
import useBeforeUnload from "./packages/components/src/editor/hooks/use-beforeunload.js";
import { useUserConfig } from "./packages/components/src/editor/hooks/use-user-config.js";
import { Switch as i } from "./node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/switch.js";
import { Button as o } from "./node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/button.js";
const Tour = lazy(() => import("./packages/components/src/editor/components/Tour.js"));
const NavBar = lazy(() => import("./packages/components/src/editor/components/NavBar.js"));
const Chat = lazy(() => import("./packages/components/src/editor/components/Chat.js"));
const EditablePage = lazy(() => import("./packages/components/src/editor/components/EditablePage.js"));
lazy(() => import("./Page.js"));
const DeviceFrame = lazy(() => import("./packages/components/src/editor/components/DeviceFrame.js"));
const Panel = lazy(() => import("./packages/components/src/editor/components/Panel.js"));
function Editor(props) {
  const rootRef = useRef(null);
  const draft = useDraft();
  useEditorEnabled();
  const chatVisible = useChatVisible();
  const sections = useSections();
  const { panelPosition } = usePanel();
  const themes = useThemes();
  const generationState = useGenerationState();
  const draftHelpers = useDraftHelpers();
  const { setDraggingBrickType, toggleDebugMode, hidePanel } = useEditorHelpers();
  const selectedBrickId = useSelectedBrickId();
  const selectedSectionId = useSelectedSectionId();
  const islocalDev = useIsLocalDev();
  const debug = useDebugMode();
  const userConfig = useUserConfig();
  const tmpAddedBrick = useRef(null);
  usePageAutoSave();
  useEditorHotKeys();
  useBeforeUnload(() => !!draft.dirty, "You have unsaved changes. Are you sure you want to leave?");
  useEffect(() => {
    const themeUsed = draft.previewTheme ?? draft.site.theme;
    if (themeUsed) {
      e(E(getThemeCss(themeUsed)));
    }
  }, [draft.previewTheme, draft.site.theme]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    DragDropProvider,
    {
      onDragStart: (event, manager) => {
        const { operation } = event;
        if (operation.source?.type === "library") {
          const brickType = operation.source.data.manifest.type;
          setDraggingBrickType(brickType);
          return;
        }
        console.log(`Started dragging ${operation.source?.id}`);
        if (operation.source?.id) {
          const element = document.getElementById(operation.source.id);
          if (!element) {
            return;
          }
          console.log(`adding class ${operation.source.id}`);
          element?.classList.add("moving");
          element.style.setProperty("box-shadow", "0 4px 8px rgba(0, 0, 0, 0.2)", "important");
          element.style.setProperty("outline", "2px solid var(--violet-8)", "important");
          element.style.setProperty("outline-offset", "0px", "important");
          const computedStyle = window.getComputedStyle(element);
          if (computedStyle.getPropertyValue("background-color") === "rgba(0, 0, 0, 0)") {
            console.log("Changing background color to upstart-200");
            element.style.setProperty("background-color", "var(--violet-a5)", "important");
          }
        }
      },
      onDragOver: (event, manager) => {
        const { operation } = event;
        const isLibraryDrag = operation.source?.type === "library";
        if (operation.canceled || !operation.target) {
          return;
        }
        if (operation.target?.data?.manifest?.isContainer && operation.activatorEvent?.metaKey) {
          console.log("operation.activatorEvent", operation.activatorEvent);
          console.error("Dropping over a container, disable reordering");
          event.preventDefault();
          return;
        }
        const items = sections.reduce(
          (acc, section) => {
            acc[section.id] = section.bricks.filter((brick) => !draftHelpers.getParentBrick(brick.id)).map((brick) => brick.id);
            return acc;
          },
          {}
        );
        if (isLibraryDrag) {
          items.$library$ = tmpAddedBrick.current ? [] : [operation.source.id];
        }
        const newItems = move(items, event);
        if (isEqual(items, newItems)) {
          console.debug("Items are equal, no changes made");
        } else {
          for (const section of sections) {
            if (!isEqual(items[section.id], newItems[section.id])) {
              console.log("Rebuilding section", section.id);
              const modifiedSection = {
                ...section,
                bricks: newItems[section.id].map((brickId, index) => {
                  if (isLibraryDrag && brickId === operation.source.id && !draftHelpers.getBrick(brickId)) {
                    const newBrick = X(operation.source.data?.manifest.type, true);
                    tmpAddedBrick.current = newBrick.id;
                    draftHelpers.addBrick(newBrick, section.id, index, null);
                    return newBrick;
                  }
                  return draftHelpers.getBrick(brickId);
                })
              };
              draftHelpers.updateSection(section.id, modifiedSection);
            }
          }
        }
      },
      onDragEnd: (event) => {
        console.log(`Ended dragging`, event);
        const {
          operation: { source }
        } = event;
        if (tmpAddedBrick.current) {
          draftHelpers.updateBrickProps(tmpAddedBrick.current, { ghost: false });
        }
        setDraggingBrickType(null);
        tmpAddedBrick.current = null;
        if (source?.id) {
          setTimeout(() => {
            const element = document.getElementById(source.id);
            if (element) {
              element.classList.remove("moving");
              element.style.removeProperty("box-shadow");
              element.style.removeProperty("outline");
              element.style.removeProperty("outline-offset");
              element.style.removeProperty("background-color");
            }
          }, 200);
        }
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          id: "editor",
          className: D(
            "grid relative transition-all mx-auto w-full",
            getEditorCss(generationState, chatVisible),
            "h-[100dvh] min-h-[100dvh] max-h-[100dvh]",
            generationState.isReady === false && E({
              background: `linear-gradient(120deg,
              oklab(from #9291e7 l a b / 0.65),
              oklab(from #7270c6 l a b / 0.65),
              oklab(from #c050c2 l a b / 0.65),
              oklab(from #ef50a2 l a b / 0.65),
              oklab(from #ff6285 l a b / 0.65),
              oklab(from #ff806b l a b / 0.65),
              oklab(from #ffa25a l a b / 0.65),
              oklab(from #ffc358 l a b / 0.65)
          )`
            }),
            generationState.isReady === false && "transition-all duration-500 ease-in-out"
          ),
          ...props,
          ref: rootRef,
          children: [
            sections.length > 0 && generationState.isReady && /* @__PURE__ */ jsxRuntimeExports.jsx(Suspense, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Tour, {}) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Suspense, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(NavBar, {}) }),
            chatVisible && /* @__PURE__ */ jsxRuntimeExports.jsx(Suspense, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Chat, {}) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Suspense, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Modal, {}),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Panel, {}),
              !generationState.isReady && debug === true && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "fixed flex flex-col gap-3 w-[23dvw] top-[60px] right-0 bottom-0 bg-gray-100 dark:bg-dark-800 border-gray-300 dark:border-gray-700 p-5 overflow-y-auto", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-xl font-bold", children: "Debug Information" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-lg font-semibold", children: "Site" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(draft.site, null, 2) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-lg font-semibold", children: "Page" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(draft.page, null, 2) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-lg font-semibold", children: "User config" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(userConfig, null, 2) })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "main",
              {
                className: D(
                  "flex-1 flex place-content-center z-40 overflow-x-auto overscroll-none",
                  generationState.isReady === false && "!hidden",
                  E({
                    gridArea: "main",
                    scrollbarColor: "var(--violet-4) var(--violet-2)",
                    scrollBehavior: "smooth",
                    scrollbarGutter: "stable",
                    scrollbarWidth: panelPosition === "left" ? "thin" : "none",
                    "&:hover": {
                      scrollbarColor: "var(--violet-7) var(--violet-3)"
                    }
                  })
                ),
                children: [
                  generationState.isReady && /* @__PURE__ */ jsxRuntimeExports.jsx(Suspense, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DeviceFrame, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(EditablePage, {}),
                    draft.previewTheme && /* @__PURE__ */ jsxRuntimeExports.jsx(ThemePreviewConfirmButton, {})
                  ] }) }),
                  !generationState.isReady && (themes.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(DeviceFrame, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(ThemesPreviewList, { themes }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(DeviceFrame, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(BlankWaitPage, {}) })),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Oe,
                    {
                      toastOptions: {
                        position: "bottom-center",
                        style: {
                          background: "rgba(0, 0, 0, 0.85)",
                          color: "white",
                          fontSize: "0.85rem",
                          fontWeight: "500"
                          // marginBottom: "1rem",
                        },
                        className: D("last:mb-1 px-1 py-1 rounded-lg"),
                        error: {
                          style: {
                            background: "#880808"
                          }
                        }
                      }
                    }
                  ),
                  islocalDev && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: "fixed flex max-w-[548px] items-center divide-x divide-gray-300 bottom-0 right-6 p-2 text-xs text-gray-500 bg-gray-100 dark:bg-dark-800 z-[19999] rounded-t-md",
                      style: {
                        // Shadow to the top left corner
                        boxShadow: "0 -2px 4px rgba(0, 0, 0, 0.1), -2px 0 4px rgba(0, 0, 0, 0.1)"
                      },
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-2", children: [
                          "Selected brick: ",
                          selectedBrickId ?? "none"
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-2", children: [
                          "Selected section: ",
                          selectedSectionId ?? "none"
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 px-2", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(i, { defaultChecked: debug, onCheckedChange: toggleDebugMode, size: "1", id: "debug-mode" }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { htmlFor: "debug-mode", className: "cursor-pointer select-none", children: [
                            "Debug mode",
                            " ",
                            /* @__PURE__ */ jsxRuntimeExports.jsx("b", { className: D("font-semibold", debug ? "text-upstart-600" : "text-gray-500"), children: debug ? "on" : "off" })
                          ] })
                        ] })
                      ]
                    }
                  )
                ]
              }
            )
          ]
        }
      )
    }
  );
}
function getEditorCss(generationState, chatVisible) {
  return E({
    gridTemplateAreas: chatVisible ? `"navbar navbar" "chat main"` : `"navbar" "main"`,
    gridTemplateRows: "64px 1fr",
    gridTemplateColumns: generationState.isReady === false ? "1fr 0px" : chatVisible ? "360px 1fr" : "1fr"
    // maxWidth: generationState.isReady === false ? "clamp(500px, 40dvw, 650px)" : "none",
  });
}
function ThemePreviewConfirmButton() {
  const { validatePreviewTheme } = useDraftHelpers();
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fixed bottom-0 left-0 right-0 flex justify-center items-center z-[9999]", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-3 pb-2 bg-black/70 backdrop-blur-md rounded-t-lg max-w-fit flex gap-2 shadow-xl", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(o, { variant: "solid", color: "gray", onClick: () => validatePreviewTheme(false), children: "Revert" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(o, { onClick: () => validatePreviewTheme(true), variant: "solid", children: "Accept theme" })
  ] }) });
}
export {
  Editor as default
};
//# sourceMappingURL=Editor.js.map
