import { jsxs, jsx } from "react/jsx-runtime";
import { u as useEditorHelpers, a as usePreviewMode, b as useSelectedBrickId, c as useSelectedSectionId, d as useChatVisible, e as usePanel, f as useDebugMode } from "./use-editor.BcGWPSSE.js";
import * as React from "react";
import { useRef, useEffect, useCallback, useState, useLayoutEffect, useContext, createContext, lazy, Suspense } from "react";
import { t as tw, c as css, a as tx } from "./twind.DdSZmZu6.js";
import { u as useComposedRefs, a as useControllableState, c as createContextScope, P as Primitive, b as composeEventHandlers, d as useSize, y, e as c, O as Oe } from "./index.NovFngrl.js";
import { u as useDraft, a as usePage, b as useSite, c as useSectionsSubscribe, d as usePageLabelSubscribe, e as useSiteLabelSubscribe, f as useDatasourcesSubscribe, g as useDatarecordsSubscribe, h as usePageAttributesSubscribe, i as useSiteAttributesSubscribe, j as useThemeSubscribe, k as useThemesSubscribe, l as useSitemapSubscribe, m as useDraftHelpers, n as useBrick, o as useDraftUndoManager, p as useSections, q as useThemes, r as useGenerationState, s as isEqual, t as createEmptyBrick } from "./use-page-data.CMUQyNAA.js";
import { r as resolvePageAttributes } from "./chunk-SQ6UIR6O.BSGYRT1Y.js";
import "@sinclair/typebox";
import { getThemeCss } from "../get-theme-css.js";
import "lodash-es";
import { D as DragDropProvider } from "./index.C8AMu7HL.js";
import { r, o as o$2, a as r$1, v, b as r$2 } from "./radius.prop.DTamp0tm.js";
import { n } from "./base-button.dY2fIaam.js";
function usePrevious(value) {
  const ref = React.useRef({ value, previous: value });
  return React.useMemo(() => {
    if (ref.current.value !== value) {
      ref.current.previous = ref.current.value;
      ref.current.value = value;
    }
    return ref.current.previous;
  }, [value]);
}
var SWITCH_NAME = "Switch";
var [createSwitchContext, createSwitchScope] = createContextScope(SWITCH_NAME);
var [SwitchProvider, useSwitchContext] = createSwitchContext(SWITCH_NAME);
var Switch = React.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeSwitch,
      name,
      checked: checkedProp,
      defaultChecked,
      required,
      disabled,
      value = "on",
      onCheckedChange,
      form,
      ...switchProps
    } = props;
    const [button, setButton] = React.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setButton(node));
    const hasConsumerStoppedPropagationRef = React.useRef(false);
    const isFormControl = button ? form || !!button.closest("form") : true;
    const [checked, setChecked] = useControllableState({
      prop: checkedProp,
      defaultProp: defaultChecked ?? false,
      onChange: onCheckedChange,
      caller: SWITCH_NAME
    });
    return /* @__PURE__ */ jsxs(SwitchProvider, { scope: __scopeSwitch, checked, disabled, children: [
      /* @__PURE__ */ jsx(
        Primitive.button,
        {
          type: "button",
          role: "switch",
          "aria-checked": checked,
          "aria-required": required,
          "data-state": getState(checked),
          "data-disabled": disabled ? "" : void 0,
          disabled,
          value,
          ...switchProps,
          ref: composedRefs,
          onClick: composeEventHandlers(props.onClick, (event) => {
            setChecked((prevChecked) => !prevChecked);
            if (isFormControl) {
              hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
              if (!hasConsumerStoppedPropagationRef.current) event.stopPropagation();
            }
          })
        }
      ),
      isFormControl && /* @__PURE__ */ jsx(
        SwitchBubbleInput,
        {
          control: button,
          bubbles: !hasConsumerStoppedPropagationRef.current,
          name,
          value,
          checked,
          required,
          disabled,
          form,
          style: { transform: "translateX(-100%)" }
        }
      )
    ] });
  }
);
Switch.displayName = SWITCH_NAME;
var THUMB_NAME = "SwitchThumb";
var SwitchThumb = React.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSwitch, ...thumbProps } = props;
    const context = useSwitchContext(THUMB_NAME, __scopeSwitch);
    return /* @__PURE__ */ jsx(
      Primitive.span,
      {
        "data-state": getState(context.checked),
        "data-disabled": context.disabled ? "" : void 0,
        ...thumbProps,
        ref: forwardedRef
      }
    );
  }
);
SwitchThumb.displayName = THUMB_NAME;
var BUBBLE_INPUT_NAME = "SwitchBubbleInput";
var SwitchBubbleInput = React.forwardRef(
  ({
    __scopeSwitch,
    control,
    checked,
    bubbles = true,
    ...props
  }, forwardedRef) => {
    const ref = React.useRef(null);
    const composedRefs = useComposedRefs(ref, forwardedRef);
    const prevChecked = usePrevious(checked);
    const controlSize = useSize(control);
    React.useEffect(() => {
      const input = ref.current;
      if (!input) return;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(
        inputProto,
        "checked"
      );
      const setChecked = descriptor.set;
      if (prevChecked !== checked && setChecked) {
        const event = new Event("click", { bubbles });
        setChecked.call(input, checked);
        input.dispatchEvent(event);
      }
    }, [prevChecked, checked, bubbles]);
    return /* @__PURE__ */ jsx(
      "input",
      {
        type: "checkbox",
        "aria-hidden": true,
        defaultChecked: checked,
        ...props,
        tabIndex: -1,
        ref: composedRefs,
        style: {
          ...props.style,
          ...controlSize,
          position: "absolute",
          pointerEvents: "none",
          opacity: 0,
          margin: 0
        }
      }
    );
  }
);
SwitchBubbleInput.displayName = BUBBLE_INPUT_NAME;
function getState(checked) {
  return checked ? "checked" : "unchecked";
}
var Root = Switch;
var Thumb = SwitchThumb;
const o$1 = React.forwardRef(({ className: e, ...n$1 }, r2) => React.createElement(n, { ...n$1, ref: r2, className: y("rt-Button", e) }));
o$1.displayName = "Button";
const o = ["1", "2", "3"], t = ["classic", "surface", "soft"], a = { size: { type: "enum", className: "rt-r-size", values: o, default: "2", responsive: true }, variant: { type: "enum", className: "rt-variant", values: t, default: "surface" }, ...r$1, ...o$2, ...r };
const i = React.forwardRef((o2, p) => {
  const { className: s, color: m, radius: c2, ...a$1 } = v(o2, a, r$2);
  return React.createElement(Root, { "data-accent-color": m, "data-radius": c2, ...a$1, asChild: false, ref: p, className: y("rt-reset", "rt-SwitchRoot", s) }, React.createElement(Thumb, { className: y("rt-SwitchThumb", { "rt-high-contrast": o2.highContrast }) }));
});
i.displayName = "Switch";
function useDebounceCallback(callback, delay, deps = [], options = {}) {
  const { leading = false, trailing = true, maxWait } = options;
  const timeoutRef = useRef(null);
  const maxWaitTimeoutRef = useRef(null);
  const lastCallTimeRef = useRef(0);
  const lastInvokeTimeRef = useRef(0);
  const argsRef = useRef([]);
  const callbackRef = useRef(callback);
  useEffect(() => {
    callbackRef.current = callback;
  }, [callback, ...deps]);
  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      if (maxWaitTimeoutRef.current) {
        clearTimeout(maxWaitTimeoutRef.current);
      }
    };
  }, deps);
  const invokeFunction = useCallback(() => {
    const args = argsRef.current;
    const time = Date.now();
    lastInvokeTimeRef.current = time;
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    if (maxWaitTimeoutRef.current) {
      clearTimeout(maxWaitTimeoutRef.current);
      maxWaitTimeoutRef.current = null;
    }
    return callbackRef.current(...args);
  }, []);
  const debouncedCallback = useCallback(
    // biome-ignore lint/suspicious/noExplicitAny: <explanation>
    (...args) => {
      const time = Date.now();
      const timeSinceLastCall = time - lastCallTimeRef.current;
      const timeSinceLastInvoke = time - lastInvokeTimeRef.current;
      lastCallTimeRef.current = time;
      argsRef.current = args;
      if (leading && timeSinceLastCall >= delay) {
        return invokeFunction();
      }
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      if (maxWait !== void 0 && !maxWaitTimeoutRef.current) {
        const timeUntilMaxWait = maxWait - timeSinceLastInvoke;
        if (timeUntilMaxWait > 0) {
          maxWaitTimeoutRef.current = setTimeout(() => {
            maxWaitTimeoutRef.current = null;
            invokeFunction();
          }, timeUntilMaxWait);
        }
      }
      if (trailing) {
        timeoutRef.current = setTimeout(() => {
          timeoutRef.current = null;
          invokeFunction();
        }, delay);
      }
    },
    [delay, leading, trailing, maxWait, invokeFunction]
  );
  return debouncedCallback;
}
const AUTO_SAVE_MIN_INTERVAL = 1e3;
function usePageAutoSave() {
  const draft = useDraft();
  const pageConfig = usePage();
  const site = useSite();
  const { onSavePage, onSaveSite, onPageCreated } = useEditorHelpers();
  const saveSections = useDebounceCallback(
    async (sections) => {
      await onSavePage({
        pageId: pageConfig.id,
        pageVersionId: "latest",
        siteId: site.id,
        data: { sections }
      });
      draft.setLastSaved(/* @__PURE__ */ new Date());
    },
    AUTO_SAVE_MIN_INTERVAL,
    [pageConfig.id]
  );
  useSectionsSubscribe((sections) => {
    console.debug("Sections have changed, updating page version", sections);
    saveSections(sections);
  });
  const savePageLabel = useDebounceCallback(
    async (label) => {
      await onSavePage({
        pageId: pageConfig.id,
        pageVersionId: "latest",
        siteId: site.id,
        data: { label }
      });
      draft.setLastSaved(/* @__PURE__ */ new Date());
    },
    AUTO_SAVE_MIN_INTERVAL,
    [pageConfig.id]
  );
  usePageLabelSubscribe((label) => {
    console.debug("Page label has changed:", label);
    savePageLabel(label);
  });
  const saveSiteLabel = useDebounceCallback(
    async (label) => {
      await onSaveSite({
        siteId: site.id,
        data: { label }
      });
      draft.setLastSaved(/* @__PURE__ */ new Date());
    },
    AUTO_SAVE_MIN_INTERVAL,
    [pageConfig.id]
  );
  useSiteLabelSubscribe((label) => {
    console.debug("Site label has changed:", label);
    saveSiteLabel(label);
  });
  const saveDatasources = useDebounceCallback(async (datasources) => {
    await onSaveSite({
      siteId: site.id,
      data: { datasources }
    });
    draft.setLastSaved(/* @__PURE__ */ new Date());
  }, AUTO_SAVE_MIN_INTERVAL);
  useDatasourcesSubscribe((datasources) => {
    console.debug("Datasources have changed, saving them", datasources);
    saveDatasources(datasources);
  });
  const saveDatarecords = useDebounceCallback(async (datarecords) => {
    await onSaveSite?.({
      siteId: site.id,
      data: { datarecords }
    });
    draft.setLastSaved(/* @__PURE__ */ new Date());
  }, AUTO_SAVE_MIN_INTERVAL);
  useDatarecordsSubscribe((datarecords) => {
    console.debug("Datarecords have changed, saving them", datarecords);
    saveDatarecords(datarecords);
  });
  const savePageAttributes = useDebounceCallback(
    async (attributes) => {
      await onSavePage({
        pageId: pageConfig.id,
        pageVersionId: "latest",
        siteId: site.id,
        data: { attributes }
      });
      draft.setLastSaved(/* @__PURE__ */ new Date());
    },
    AUTO_SAVE_MIN_INTERVAL,
    [pageConfig.id]
  );
  usePageAttributesSubscribe((attributes) => {
    console.debug("Page attributes have changed, saving them", attributes);
    savePageAttributes(attributes);
  });
  const saveSiteAttributes = useDebounceCallback(async (attributes) => {
    await onSaveSite({
      siteId: site.id,
      data: { attributes }
    });
    draft.setLastSaved(/* @__PURE__ */ new Date());
  }, AUTO_SAVE_MIN_INTERVAL);
  useSiteAttributesSubscribe((attributes) => {
    console.debug("Site attributes have changed, saving them", attributes);
    saveSiteAttributes(attributes);
  });
  const saveTheme = useDebounceCallback(async (theme) => {
    await onSaveSite({
      siteId: site.id,
      data: { theme }
    });
    draft.setLastSaved(/* @__PURE__ */ new Date());
  }, AUTO_SAVE_MIN_INTERVAL);
  useThemeSubscribe((theme) => {
    console.debug("theme has changed, saving it", theme);
    saveTheme(theme);
  });
  const saveThemes = useDebounceCallback(async (themes) => {
    await onSaveSite({
      siteId: site.id,
      data: { themes }
    });
    draft.setLastSaved(/* @__PURE__ */ new Date());
  }, AUTO_SAVE_MIN_INTERVAL);
  useThemesSubscribe((themes) => {
    console.debug("themes have changed, saving them", themes);
    saveThemes(themes);
  });
  const saveNewPage = useDebounceCallback(async (newPage) => {
    await onPageCreated(newPage);
  }, AUTO_SAVE_MIN_INTERVAL);
  useSitemapSubscribe((sitemap) => {
    const page = sitemap.at(-1);
    if (page) {
      saveNewPage({
        id: page.id,
        label: page.label,
        sections: [],
        attributes: resolvePageAttributes({ title: page.label, path: page.path })
      });
    }
  });
}
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function(n2) {
    for (var e = 1; e < arguments.length; e++) {
      var t2 = arguments[e];
      for (var r2 in t2) ({}).hasOwnProperty.call(t2, r2) && (n2[r2] = t2[r2]);
    }
    return n2;
  }, _extends.apply(null, arguments);
}
var reservedModifierKeywords = ["shift", "alt", "meta", "mod", "ctrl"];
var mappedKeys = {
  esc: "escape",
  "return": "enter",
  ".": "period",
  ",": "comma",
  "-": "slash",
  " ": "space",
  "`": "backquote",
  "#": "backslash",
  "+": "bracketright",
  ShiftLeft: "shift",
  ShiftRight: "shift",
  AltLeft: "alt",
  AltRight: "alt",
  MetaLeft: "meta",
  MetaRight: "meta",
  OSLeft: "meta",
  OSRight: "meta",
  ControlLeft: "ctrl",
  ControlRight: "ctrl"
};
function mapKey(key) {
  return (key && mappedKeys[key] || key || "").trim().toLowerCase().replace(/key|digit|numpad|arrow/, "");
}
function isHotkeyModifier(key) {
  return reservedModifierKeywords.includes(key);
}
function parseKeysHookInput(keys, splitKey) {
  if (splitKey === void 0) {
    splitKey = ",";
  }
  return keys.split(splitKey);
}
function parseHotkey(hotkey, combinationKey, description) {
  if (combinationKey === void 0) {
    combinationKey = "+";
  }
  var keys = hotkey.toLocaleLowerCase().split(combinationKey).map(function(k) {
    return mapKey(k);
  });
  var modifiers = {
    alt: keys.includes("alt"),
    ctrl: keys.includes("ctrl") || keys.includes("control"),
    shift: keys.includes("shift"),
    meta: keys.includes("meta"),
    mod: keys.includes("mod")
  };
  var singleCharKeys = keys.filter(function(k) {
    return !reservedModifierKeywords.includes(k);
  });
  return _extends({}, modifiers, {
    keys: singleCharKeys,
    description,
    hotkey
  });
}
(function() {
  if (typeof document !== "undefined") {
    document.addEventListener("keydown", function(e) {
      if (e.key === void 0) {
        return;
      }
      pushToCurrentlyPressedKeys([mapKey(e.key), mapKey(e.code)]);
    });
    document.addEventListener("keyup", function(e) {
      if (e.key === void 0) {
        return;
      }
      removeFromCurrentlyPressedKeys([mapKey(e.key), mapKey(e.code)]);
    });
  }
  if (typeof window !== "undefined") {
    window.addEventListener("blur", function() {
      currentlyPressedKeys.clear();
    });
  }
})();
var currentlyPressedKeys = /* @__PURE__ */ new Set();
function isReadonlyArray(value) {
  return Array.isArray(value);
}
function isHotkeyPressed(key, splitKey) {
  if (splitKey === void 0) {
    splitKey = ",";
  }
  var hotkeyArray = isReadonlyArray(key) ? key : key.split(splitKey);
  return hotkeyArray.every(function(hotkey) {
    return currentlyPressedKeys.has(hotkey.trim().toLowerCase());
  });
}
function pushToCurrentlyPressedKeys(key) {
  var hotkeyArray = Array.isArray(key) ? key : [key];
  if (currentlyPressedKeys.has("meta")) {
    currentlyPressedKeys.forEach(function(key2) {
      return !isHotkeyModifier(key2) && currentlyPressedKeys["delete"](key2.toLowerCase());
    });
  }
  hotkeyArray.forEach(function(hotkey) {
    return currentlyPressedKeys.add(hotkey.toLowerCase());
  });
}
function removeFromCurrentlyPressedKeys(key) {
  var hotkeyArray = Array.isArray(key) ? key : [key];
  if (key === "meta") {
    currentlyPressedKeys.clear();
  } else {
    hotkeyArray.forEach(function(hotkey) {
      return currentlyPressedKeys["delete"](hotkey.toLowerCase());
    });
  }
}
function maybePreventDefault(e, hotkey, preventDefault) {
  if (typeof preventDefault === "function" && preventDefault(e, hotkey) || preventDefault === true) {
    e.preventDefault();
  }
}
function isHotkeyEnabled(e, hotkey, enabled) {
  if (typeof enabled === "function") {
    return enabled(e, hotkey);
  }
  return enabled === true || enabled === void 0;
}
function isKeyboardEventTriggeredByInput(ev) {
  return isHotkeyEnabledOnTag(ev, ["input", "textarea", "select"]);
}
function isHotkeyEnabledOnTag(event, enabledOnTags) {
  if (enabledOnTags === void 0) {
    enabledOnTags = false;
  }
  var target = event.target, composed = event.composed;
  var targetTagName = null;
  if (isCustomElement(target) && composed) {
    targetTagName = event.composedPath()[0] && event.composedPath()[0].tagName;
  } else {
    targetTagName = target && target.tagName;
  }
  if (isReadonlyArray(enabledOnTags)) {
    return Boolean(targetTagName && enabledOnTags && enabledOnTags.some(function(tag) {
      var _targetTagName;
      return tag.toLowerCase() === ((_targetTagName = targetTagName) == null ? void 0 : _targetTagName.toLowerCase());
    }));
  }
  return Boolean(targetTagName && enabledOnTags && enabledOnTags);
}
function isCustomElement(element) {
  return !!element.tagName && !element.tagName.startsWith("-") && element.tagName.includes("-");
}
function isScopeActive(activeScopes, scopes) {
  if (activeScopes.length === 0 && scopes) {
    console.warn('A hotkey has the "scopes" option set, however no active scopes were found. If you want to use the global scopes feature, you need to wrap your app in a <HotkeysProvider>');
    return true;
  }
  if (!scopes) {
    return true;
  }
  return activeScopes.some(function(scope) {
    return scopes.includes(scope);
  }) || activeScopes.includes("*");
}
var isHotkeyMatchingKeyboardEvent = function isHotkeyMatchingKeyboardEvent2(e, hotkey, ignoreModifiers) {
  if (ignoreModifiers === void 0) {
    ignoreModifiers = false;
  }
  var alt = hotkey.alt, meta = hotkey.meta, mod = hotkey.mod, shift = hotkey.shift, ctrl = hotkey.ctrl, keys = hotkey.keys;
  var pressedKeyUppercase = e.key, code = e.code, ctrlKey = e.ctrlKey, metaKey = e.metaKey, shiftKey = e.shiftKey, altKey = e.altKey;
  var keyCode = mapKey(code);
  var pressedKey = pressedKeyUppercase.toLowerCase();
  if (!(keys != null && keys.includes(keyCode)) && !(keys != null && keys.includes(pressedKey)) && !["ctrl", "control", "unknown", "meta", "alt", "shift", "os"].includes(keyCode)) {
    return false;
  }
  if (!ignoreModifiers) {
    if (alt === !altKey && pressedKey !== "alt") {
      return false;
    }
    if (shift === !shiftKey && pressedKey !== "shift") {
      return false;
    }
    if (mod) {
      if (!metaKey && !ctrlKey) {
        return false;
      }
    } else {
      if (meta === !metaKey && pressedKey !== "meta" && pressedKey !== "os") {
        return false;
      }
      if (ctrl === !ctrlKey && pressedKey !== "ctrl" && pressedKey !== "control") {
        return false;
      }
    }
  }
  if (keys && keys.length === 1 && (keys.includes(pressedKey) || keys.includes(keyCode))) {
    return true;
  } else if (keys) {
    return isHotkeyPressed(keys);
  } else if (!keys) {
    return true;
  }
  return false;
};
var BoundHotkeysProxyProvider = /* @__PURE__ */ createContext(void 0);
var useBoundHotkeysProxy = function useBoundHotkeysProxy2() {
  return useContext(BoundHotkeysProxyProvider);
};
function deepEqual(x, y2) {
  return x && y2 && typeof x === "object" && typeof y2 === "object" ? Object.keys(x).length === Object.keys(y2).length && //@ts-ignore
  Object.keys(x).reduce(function(isEqual2, key) {
    return isEqual2 && deepEqual(x[key], y2[key]);
  }, true) : x === y2;
}
var HotkeysContext = /* @__PURE__ */ createContext({
  hotkeys: [],
  enabledScopes: [],
  toggleScope: function toggleScope() {
  },
  enableScope: function enableScope() {
  },
  disableScope: function disableScope() {
  }
});
var useHotkeysContext = function useHotkeysContext2() {
  return useContext(HotkeysContext);
};
function useDeepEqualMemo(value) {
  var ref = useRef(void 0);
  if (!deepEqual(ref.current, value)) {
    ref.current = value;
  }
  return ref.current;
}
var stopPropagation = function stopPropagation2(e) {
  e.stopPropagation();
  e.preventDefault();
  e.stopImmediatePropagation();
};
var useSafeLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
function useHotkeys(keys, callback, options, dependencies) {
  var _useState = useState(null), ref = _useState[0], setRef = _useState[1];
  var hasTriggeredRef = useRef(false);
  var _options = !(options instanceof Array) ? options : !(dependencies instanceof Array) ? dependencies : void 0;
  var _keys = isReadonlyArray(keys) ? keys.join(_options == null ? void 0 : _options.splitKey) : keys;
  var _deps = options instanceof Array ? options : dependencies instanceof Array ? dependencies : void 0;
  var memoisedCB = useCallback(callback, _deps != null ? _deps : []);
  var cbRef = useRef(memoisedCB);
  if (_deps) {
    cbRef.current = memoisedCB;
  } else {
    cbRef.current = callback;
  }
  var memoisedOptions = useDeepEqualMemo(_options);
  var _useHotkeysContext = useHotkeysContext(), enabledScopes = _useHotkeysContext.enabledScopes;
  var proxy = useBoundHotkeysProxy();
  useSafeLayoutEffect(function() {
    if ((memoisedOptions == null ? void 0 : memoisedOptions.enabled) === false || !isScopeActive(enabledScopes, memoisedOptions == null ? void 0 : memoisedOptions.scopes)) {
      return;
    }
    var listener = function listener2(e, isKeyUp) {
      var _e$target;
      if (isKeyUp === void 0) {
        isKeyUp = false;
      }
      if (isKeyboardEventTriggeredByInput(e) && !isHotkeyEnabledOnTag(e, memoisedOptions == null ? void 0 : memoisedOptions.enableOnFormTags)) {
        return;
      }
      if (ref !== null) {
        var rootNode = ref.getRootNode();
        if ((rootNode instanceof Document || rootNode instanceof ShadowRoot) && rootNode.activeElement !== ref && !ref.contains(rootNode.activeElement)) {
          stopPropagation(e);
          return;
        }
      }
      if ((_e$target = e.target) != null && _e$target.isContentEditable && !(memoisedOptions != null && memoisedOptions.enableOnContentEditable)) {
        return;
      }
      parseKeysHookInput(_keys, memoisedOptions == null ? void 0 : memoisedOptions.splitKey).forEach(function(key) {
        var _hotkey$keys;
        var hotkey = parseHotkey(key, memoisedOptions == null ? void 0 : memoisedOptions.combinationKey);
        if (isHotkeyMatchingKeyboardEvent(e, hotkey, memoisedOptions == null ? void 0 : memoisedOptions.ignoreModifiers) || (_hotkey$keys = hotkey.keys) != null && _hotkey$keys.includes("*")) {
          if (memoisedOptions != null && memoisedOptions.ignoreEventWhen != null && memoisedOptions.ignoreEventWhen(e)) {
            return;
          }
          if (isKeyUp && hasTriggeredRef.current) {
            return;
          }
          maybePreventDefault(e, hotkey, memoisedOptions == null ? void 0 : memoisedOptions.preventDefault);
          if (!isHotkeyEnabled(e, hotkey, memoisedOptions == null ? void 0 : memoisedOptions.enabled)) {
            stopPropagation(e);
            return;
          }
          cbRef.current(e, hotkey);
          if (!isKeyUp) {
            hasTriggeredRef.current = true;
          }
        }
      });
    };
    var handleKeyDown = function handleKeyDown2(event) {
      if (event.key === void 0) {
        return;
      }
      pushToCurrentlyPressedKeys(mapKey(event.code));
      if ((memoisedOptions == null ? void 0 : memoisedOptions.keydown) === void 0 && (memoisedOptions == null ? void 0 : memoisedOptions.keyup) !== true || memoisedOptions != null && memoisedOptions.keydown) {
        listener(event);
      }
    };
    var handleKeyUp = function handleKeyUp2(event) {
      if (event.key === void 0) {
        return;
      }
      removeFromCurrentlyPressedKeys(mapKey(event.code));
      hasTriggeredRef.current = false;
      if (memoisedOptions != null && memoisedOptions.keyup) {
        listener(event, true);
      }
    };
    var domNode = ref || (_options == null ? void 0 : _options.document) || document;
    domNode.addEventListener("keyup", handleKeyUp);
    domNode.addEventListener("keydown", handleKeyDown);
    if (proxy) {
      parseKeysHookInput(_keys, memoisedOptions == null ? void 0 : memoisedOptions.splitKey).forEach(function(key) {
        return proxy.addHotkey(parseHotkey(key, memoisedOptions == null ? void 0 : memoisedOptions.combinationKey, memoisedOptions == null ? void 0 : memoisedOptions.description));
      });
    }
    return function() {
      domNode.removeEventListener("keyup", handleKeyUp);
      domNode.removeEventListener("keydown", handleKeyDown);
      if (proxy) {
        parseKeysHookInput(_keys, memoisedOptions == null ? void 0 : memoisedOptions.splitKey).forEach(function(key) {
          return proxy.removeHotkey(parseHotkey(key, memoisedOptions == null ? void 0 : memoisedOptions.combinationKey, memoisedOptions == null ? void 0 : memoisedOptions.description));
        });
      }
    };
  }, [ref, _keys, memoisedOptions, enabledScopes]);
  return setRef;
}
function useEditorHotKeys() {
  const editorHelpers = useEditorHelpers();
  const draftHelpers = useDraftHelpers();
  const draft = useDraft();
  const previewMode = usePreviewMode();
  const selectedBrickId = useSelectedBrickId();
  const selectedSectionId = useSelectedSectionId();
  const selectedBrick = useBrick(selectedBrickId);
  const { undo, redo } = useDraftUndoManager();
  useHotkeys("esc", () => {
    editorHelpers.deselectBrick();
    editorHelpers.setSelectedSectionId();
    editorHelpers.hidePanel();
  });
  useHotkeys("mod+c", () => {
    const sel = window.getSelection();
    if (!sel?.rangeCount) {
      console.debug("mod+c pressed");
    }
  });
  useHotkeys(["backspace", "del"], (e) => {
    if (selectedBrickId) {
      e.preventDefault();
      draftHelpers.deleteBrick(selectedBrickId);
      editorHelpers.deselectBrick(selectedBrickId);
      editorHelpers.hidePanel("inspector");
    }
  });
  useHotkeys("s", (e) => {
    e.preventDefault();
    editorHelpers.togglePanel("settings");
  });
  useHotkeys("l", (e) => {
    e.preventDefault();
    editorHelpers.togglePanel("library");
  });
  useHotkeys("t", (e) => {
    e.preventDefault();
    editorHelpers.togglePanel("theme");
  });
  useHotkeys("p", (e) => {
    e.preventDefault();
    editorHelpers.togglePanel();
  });
  useHotkeys(["mod+z", "ctrl+z"], (e) => {
    e.preventDefault();
    undo();
  });
  useHotkeys(["mod+shift+z", "ctrl+shift+z"], (e) => {
    e.preventDefault();
    redo();
  });
  useHotkeys(
    ["up", "left"],
    (e) => {
      if (selectedBrickId) {
        e.preventDefault();
        const parentBrick = draftHelpers.getParentBrick(selectedBrickId);
        if (parentBrick) {
          const direction = parentBrick.props.direction === "flex-row" ? "ArrowLeft" : "ArrowUp";
          if (direction === e.key) {
            draftHelpers.moveBrick(selectedBrickId, "previous");
          }
        } else if (e.key === "ArrowLeft") {
          draftHelpers.moveBrick(selectedBrickId, "previous");
        }
      } else if (selectedSectionId && e.key === "ArrowUp") {
        e.preventDefault();
        draftHelpers.moveSectionUp(selectedSectionId);
        const element = document.getElementById(selectedSectionId);
        if (element) {
          element.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }
    },
    {
      enableOnContentEditable: false
    }
  );
  useHotkeys(
    ["down", "right"],
    (e) => {
      if (selectedBrickId) {
        e.preventDefault();
        const parentBrick = draftHelpers.getParentBrick(selectedBrickId);
        if (parentBrick) {
          const direction = parentBrick.props.direction === "flex-row" ? "ArrowRight" : "ArrowDown";
          if (direction === e.key) {
            draftHelpers.moveBrick(selectedBrickId, "next");
          }
        } else if (e.key === "ArrowRight") {
          draftHelpers.moveBrick(selectedBrickId, "next");
        }
      } else if (selectedSectionId && e.key === "ArrowDown") {
        e.preventDefault();
        draftHelpers.moveSectionDown(selectedSectionId);
        const element = document.getElementById(selectedSectionId);
        if (element) {
          element.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }
    },
    {
      enableOnContentEditable: false
    }
  );
  useHotkeys("mod+d", (e) => {
    e.preventDefault();
    if (selectedBrickId) {
      draftHelpers.duplicateBrick(selectedBrickId);
      c("Brick duplicated", {
        id: "duplicate-brick"
      });
    }
  });
  useHotkeys("mod+j", (e) => {
    e.preventDefault();
    editorHelpers.toggleEditorEnabled();
  });
  useHotkeys("mod+g", (e) => {
    e.preventDefault();
    console.log("Debugging draft:");
    const { page, site } = draft;
    console.log({ page, site });
  });
  useHotkeys(
    "space",
    (e) => {
      const target = e.target;
      if (target.classList.contains("tiptap")) {
        return;
      }
      e.preventDefault();
      e.stopPropagation();
      if (selectedBrick) {
        draftHelpers.updateBrickProps(
          selectedBrick.id,
          {
            grow: !selectedBrick.props.grow
          },
          previewMode === "mobile"
        );
      }
    },
    {
      enableOnContentEditable: true
    }
  );
}
function useIsLocalDev() {
  return globalThis.location?.hostname === "localhost";
}
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a2, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a2, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a2, prop, b[prop]);
    }
  return a2;
};
var __spreadProps = (a2, b) => __defProps(a2, __getOwnPropDescs(b));
function arrayMove(array, from, to) {
  if (from === to) {
    return array;
  }
  const newArray = array.slice();
  newArray.splice(to, 0, newArray.splice(from, 1)[0]);
  return newArray;
}
function mutate(items, event, mutation) {
  var _a, _b;
  const { source, target, canceled } = event.operation;
  if (!source || !target || canceled) {
    if ("preventDefault" in event) event.preventDefault();
    return items;
  }
  const findIndex = (item, id) => item === id || typeof item === "object" && "id" in item && item.id === id;
  if (Array.isArray(items)) {
    const sourceIndex2 = items.findIndex((item) => findIndex(item, source.id));
    const targetIndex2 = items.findIndex((item) => findIndex(item, target.id));
    if (sourceIndex2 === -1 || targetIndex2 === -1) {
      return items;
    }
    if (!canceled && "index" in source && typeof source.index === "number") {
      const projectedSourceIndex = source.index;
      if (projectedSourceIndex !== sourceIndex2) {
        return mutation(items, sourceIndex2, projectedSourceIndex);
      }
    }
    return mutation(items, sourceIndex2, targetIndex2);
  }
  const entries = Object.entries(items);
  let sourceIndex = -1;
  let sourceParent;
  let targetIndex = -1;
  let targetParent;
  for (const [id, children] of entries) {
    if (sourceIndex === -1) {
      sourceIndex = children.findIndex((item) => findIndex(item, source.id));
      if (sourceIndex !== -1) {
        sourceParent = id;
      }
    }
    if (targetIndex === -1) {
      targetIndex = children.findIndex((item) => findIndex(item, target.id));
      if (targetIndex !== -1) {
        targetParent = id;
      }
    }
    if (sourceIndex !== -1 && targetIndex !== -1) {
      break;
    }
  }
  if (!source.manager) return items;
  const { dragOperation } = source.manager;
  const position = (_b = (_a = dragOperation.shape) == null ? void 0 : _a.current.center) != null ? _b : dragOperation.position.current;
  if (targetParent == null) {
    if (target.id in items) {
      const insertionIndex = target.shape && position.y > target.shape.center.y ? items[target.id].length : 0;
      targetParent = target.id;
      targetIndex = insertionIndex;
    }
  }
  if (sourceParent == null || targetParent == null || sourceParent === targetParent && sourceIndex === targetIndex) {
    if ("preventDefault" in event) event.preventDefault();
    return items;
  }
  if (sourceParent === targetParent) {
    return __spreadProps(__spreadValues({}, items), {
      [sourceParent]: mutation(items[sourceParent], sourceIndex, targetIndex)
    });
  }
  const isBelowTarget = target.shape && Math.round(position.y) > Math.round(target.shape.center.y);
  const modifier = isBelowTarget ? 1 : 0;
  const sourceItem = items[sourceParent][sourceIndex];
  return __spreadProps(__spreadValues({}, items), {
    [sourceParent]: [
      ...items[sourceParent].slice(0, sourceIndex),
      ...items[sourceParent].slice(sourceIndex + 1)
    ],
    [targetParent]: [
      ...items[targetParent].slice(0, targetIndex + modifier),
      sourceItem,
      ...items[targetParent].slice(targetIndex + modifier)
    ]
  });
}
function move(items, event) {
  return mutate(items, event, arrayMove);
}
function useBeforeUnload(enabled = true, message) {
  const handler = useCallback(
    (event) => {
      const finalEnabled = typeof enabled === "function" ? enabled() : true;
      if (!finalEnabled) {
        return;
      }
      event.preventDefault();
      {
        event.returnValue = message;
      }
      return message;
    },
    [enabled, message]
  );
  useEffect(() => {
    if (!enabled) {
      return;
    }
    window.addEventListener("beforeunload", handler);
    return () => window.removeEventListener("beforeunload", handler);
  }, [enabled, handler]);
}
let globalConfig = { credits: 0 };
const subscribers = /* @__PURE__ */ new Set();
let fetchPromise = null;
let intervalId = null;
let isInitialized = false;
async function fetchConfig() {
  const url = "/editor/config";
  try {
    const result = await fetch(url);
    if (result.status === 200 && result.headers.get("content-type")?.startsWith("application/json")) {
      const data = await result.json();
      return data ?? {};
    } else {
      console.warn("useConfig: ignoring invalid response");
      return {};
    }
  } catch (error) {
    console.error("useConfig: fetch error", error);
    return {};
  }
}
async function loadConfigGlobally() {
  const fetchedConfig = await fetchConfig();
  globalConfig = {
    ...globalConfig,
    ...fetchedConfig
  };
  subscribers.forEach((callback) => callback(globalConfig));
}
function startPolling() {
  if (intervalId) return;
  intervalId = setInterval(() => {
    loadConfigGlobally().catch((error) => {
      console.error("useConfig: polling error", error);
    });
  }, 2e4);
}
function stopPolling() {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
}
function useUserConfig() {
  const [config, setConfig] = useState(globalConfig);
  const subscriberRef = useRef(null);
  const updateConfig = useCallback((newConfig) => {
    setConfig(newConfig);
  }, []);
  useEffect(() => {
    if (!subscriberRef.current) {
      subscriberRef.current = updateConfig;
    }
    subscribers.add(subscriberRef.current);
    if (!isInitialized) {
      isInitialized = true;
      if (!fetchPromise) {
        fetchPromise = loadConfigGlobally().finally(() => {
          fetchPromise = null;
        });
      }
      startPolling();
    }
    return () => {
      if (subscriberRef.current) {
        subscribers.delete(subscriberRef.current);
      }
      if (subscribers.size === 0) {
        stopPolling();
        isInitialized = false;
      }
    };
  }, [updateConfig]);
  return config;
}
const Tour = lazy(() => import("./Tour.C9Bw9Ra1.js"));
const NavBar = lazy(() => import("./NavBar.DNAA5PXJ.js"));
const Chat = lazy(() => import("./ChatComponent.CXSgWJNA.js").then((n2) => n2.C));
const EditablePage = lazy(() => import("./EditablePage.9y_DTYrA.js"));
const DeviceFrame = lazy(() => import("./DeviceFrame.B0mAFyuM.js"));
const Panel = lazy(() => import("./Panel.Dp63fNGM.js"));
const Modal = lazy(() => import("./Modal.F0BxZS2S.js"));
const ThemesPreviewList = lazy(() => import("./ThemesPreviewList.BiyqScWL.js"));
const BlankWaitPage = lazy(() => import("./BlankWaitPage.BhpzHakO.js"));
function Editor(props) {
  const rootRef = useRef(null);
  const draft = useDraft();
  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) {
      tw(css(getThemeCss(themeUsed)));
    }
  }, [draft.previewTheme, draft.site.theme]);
  return /* @__PURE__ */ 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 = createEmptyBrick(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__ */ jsxs(
        "div",
        {
          id: "editor",
          className: tx(
            "grid relative transition-all mx-auto w-full",
            getEditorCss(generationState, chatVisible),
            "h-[100dvh] min-h-[100dvh] max-h-[100dvh]",
            generationState.isReady === false && css({
              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__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(Tour, {}) }),
            /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(NavBar, {}) }),
            chatVisible && /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(Chat, {}) }),
            /* @__PURE__ */ jsxs(Suspense, { children: [
              /* @__PURE__ */ jsx(Modal, {}),
              /* @__PURE__ */ jsx(Panel, {}),
              !generationState.isReady && debug === true && /* @__PURE__ */ 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__ */ jsx("h2", { className: "text-xl font-bold", children: "Debug Information" }),
                /* @__PURE__ */ jsx("h4", { className: "text-lg font-semibold", children: "Site" }),
                /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(draft.site, null, 2) }),
                /* @__PURE__ */ jsx("h4", { className: "text-lg font-semibold", children: "Page" }),
                /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(draft.page, null, 2) }),
                /* @__PURE__ */ jsx("h4", { className: "text-lg font-semibold", children: "User config" }),
                /* @__PURE__ */ jsx("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(userConfig, null, 2) })
              ] })
            ] }),
            /* @__PURE__ */ jsx(
              Oe,
              {
                toastOptions: {
                  position: "bottom-center",
                  style: {
                    background: "rgba(0, 0, 0, 0.85)",
                    color: "white",
                    fontSize: "0.85rem",
                    fontWeight: "500"
                    // marginBottom: "1rem",
                  },
                  className: tx("last:mb-1 px-1 py-1 rounded-lg"),
                  error: {
                    style: {
                      background: "#880808"
                    }
                  }
                }
              }
            ),
            islocalDev && /* @__PURE__ */ 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__ */ jsxs("div", { className: "px-2", children: [
                    "Selected brick: ",
                    selectedBrickId ?? "none"
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "px-2", children: [
                    "Selected section: ",
                    selectedSectionId ?? "none"
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 px-2", children: [
                    /* @__PURE__ */ jsx(i, { defaultChecked: debug, onCheckedChange: toggleDebugMode, size: "1", id: "debug-mode" }),
                    /* @__PURE__ */ jsxs("label", { htmlFor: "debug-mode", className: "cursor-pointer select-none", children: [
                      "Debug mode",
                      " ",
                      /* @__PURE__ */ jsx("b", { className: tx("font-semibold", debug ? "text-upstart-600" : "text-gray-500"), children: debug ? "on" : "off" })
                    ] })
                  ] })
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              "main",
              {
                className: tx(
                  "flex-1 flex place-content-center z-40 overflow-x-auto overscroll-none",
                  generationState.isReady === false && "!hidden",
                  css({
                    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__ */ jsx(Suspense, { children: /* @__PURE__ */ jsxs(DeviceFrame, { children: [
                    /* @__PURE__ */ jsx(EditablePage, {}),
                    draft.previewTheme && /* @__PURE__ */ jsx(ThemePreviewConfirmButton, {})
                  ] }) }),
                  !generationState.isReady && (themes.length > 0 ? /* @__PURE__ */ jsx(DeviceFrame, { children: /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(ThemesPreviewList, { themes }) }) }) : /* @__PURE__ */ jsx(DeviceFrame, { children: /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(BlankWaitPage, {}) }) }))
                ]
              }
            )
          ]
        }
      )
    }
  );
}
function getEditorCss(generationState, chatVisible) {
  return css({
    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__ */ jsx("div", { className: "fixed bottom-0 left-0 right-0 flex justify-center items-center z-[9999]", children: /* @__PURE__ */ 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__ */ jsx(o$1, { variant: "solid", color: "gray", onClick: () => validatePreviewTheme(false), children: "Revert" }),
    /* @__PURE__ */ jsx(o$1, { onClick: () => validatePreviewTheme(true), variant: "solid", children: "Accept theme" })
  ] }) });
}
export {
  Editor as E,
  usePrevious as a,
  i,
  o$1 as o,
  useUserConfig as u
};
//# sourceMappingURL=Editor.BvI5KhCr.js.map
