import { jsxs as D, jsx as m } from "react/jsx-runtime";
import { u as re, a as Ne, b as fe, c as pe, d as Re, e as Ae, f as Te } from "./use-editor.CLs27I-R.js";
import * as C from "react";
import { useRef as B, useEffect as j, useCallback as z, useState as me, useLayoutEffect as _e, useContext as ge, createContext as ve, lazy as T, Suspense as K } from "react";
import { t as Oe, c as $, a as W } from "./twind.Cg2g8xBZ.js";
import { u as he, a as He, c as Ke, P as be, b as je, d as Me, y as Z, e as ze, O as Ue } from "./index.D1n9HtNk.js";
import { u as ne, a as We, b as $e, c as qe, d as Ve, e as Fe, f as Ge, g as Je, h as Xe, i as Ye, j as Qe, k as Ze, l as et, m as oe, n as tt, o as rt, p as nt, q as ot, r as at, s as ie, t as it } from "./use-page-data.BYLN5MSa.js";
import { r as st } from "./attributes.C0ljq_Tf.js";
import { getThemeCss as ct } from "../get-theme-css.js";
import { D as lt } from "./index.BTcesXu3.js";
import { r as ut, o as dt, a as ft, v as pt, b as mt } from "./radius.prop.CaJVv35S.js";
import { n as gt } from "./base-button.DeoDB8N9.js";
function vt(e) {
  const t = C.useRef({ value: e, previous: e });
  return C.useMemo(() => (t.current.value !== e && (t.current.previous = t.current.value, t.current.value = e), t.current.previous), [e]);
}
var F = "Switch", [ht] = Ke(F), [bt, yt] = ht(F), ye = C.forwardRef(
  (e, t) => {
    const {
      __scopeSwitch: r,
      name: a,
      checked: s,
      defaultChecked: l,
      required: u,
      disabled: f,
      value: p = "on",
      onCheckedChange: o,
      form: c,
      ...h
    } = e, [b, n] = C.useState(null), i = he(t, (g) => n(g)), w = C.useRef(!1), S = b ? c || !!b.closest("form") : !0, [y, P] = He({
      prop: s,
      defaultProp: l ?? !1,
      onChange: o,
      caller: F
    });
    return /* @__PURE__ */ D(bt, { scope: r, checked: y, disabled: f, children: [
      /* @__PURE__ */ m(
        be.button,
        {
          type: "button",
          role: "switch",
          "aria-checked": y,
          "aria-required": u,
          "data-state": Pe(y),
          "data-disabled": f ? "" : void 0,
          disabled: f,
          value: p,
          ...h,
          ref: i,
          onClick: je(e.onClick, (g) => {
            P((d) => !d), S && (w.current = g.isPropagationStopped(), w.current || g.stopPropagation());
          })
        }
      ),
      S && /* @__PURE__ */ m(
        Se,
        {
          control: b,
          bubbles: !w.current,
          name: a,
          value: p,
          checked: y,
          required: u,
          disabled: f,
          form: c,
          style: { transform: "translateX(-100%)" }
        }
      )
    ] });
  }
);
ye.displayName = F;
var we = "SwitchThumb", ke = C.forwardRef(
  (e, t) => {
    const { __scopeSwitch: r, ...a } = e, s = yt(we, r);
    return /* @__PURE__ */ m(
      be.span,
      {
        "data-state": Pe(s.checked),
        "data-disabled": s.disabled ? "" : void 0,
        ...a,
        ref: t
      }
    );
  }
);
ke.displayName = we;
var wt = "SwitchBubbleInput", Se = C.forwardRef(
  ({
    __scopeSwitch: e,
    control: t,
    checked: r,
    bubbles: a = !0,
    ...s
  }, l) => {
    const u = C.useRef(null), f = he(u, l), p = vt(r), o = Me(t);
    return C.useEffect(() => {
      const c = u.current;
      if (!c) return;
      const h = window.HTMLInputElement.prototype, n = Object.getOwnPropertyDescriptor(
        h,
        "checked"
      ).set;
      if (p !== r && n) {
        const i = new Event("click", { bubbles: a });
        n.call(c, r), c.dispatchEvent(i);
      }
    }, [p, r, a]), /* @__PURE__ */ m(
      "input",
      {
        type: "checkbox",
        "aria-hidden": !0,
        defaultChecked: r,
        ...s,
        tabIndex: -1,
        ref: f,
        style: {
          ...s.style,
          ...o,
          position: "absolute",
          pointerEvents: "none",
          opacity: 0,
          margin: 0
        }
      }
    );
  }
);
Se.displayName = wt;
function Pe(e) {
  return e ? "checked" : "unchecked";
}
var kt = ye, St = ke;
const ee = C.forwardRef(({ className: e, ...t }, r) => C.createElement(gt, { ...t, ref: r, className: Z("rt-Button", e) }));
ee.displayName = "Button";
const Pt = ["1", "2", "3"], xt = ["classic", "surface", "soft"], Ct = { size: { type: "enum", className: "rt-r-size", values: Pt, default: "2", responsive: !0 }, variant: { type: "enum", className: "rt-variant", values: xt, default: "surface" }, ...ft, ...dt, ...ut }, xe = C.forwardRef((e, t) => {
  const { className: r, color: a, radius: s, ...l } = pt(e, Ct, mt);
  return C.createElement(kt, { "data-accent-color": a, "data-radius": s, ...l, asChild: !1, ref: t, className: Z("rt-reset", "rt-SwitchRoot", r) }, C.createElement(St, { className: Z("rt-SwitchThumb", { "rt-high-contrast": e.highContrast }) }));
});
xe.displayName = "Switch";
function I(e, t, r = [], a = {}) {
  const { leading: s = !1, trailing: l = !0, maxWait: u } = a, f = B(null), p = B(null), o = B(0), c = B(0), h = B([]), b = B(e);
  j(() => {
    b.current = e;
  }, [e, ...r]), j(() => () => {
    f.current && clearTimeout(f.current), p.current && clearTimeout(p.current);
  }, r);
  const n = z(() => {
    const w = h.current, S = Date.now();
    return c.current = S, f.current && (clearTimeout(f.current), f.current = null), p.current && (clearTimeout(p.current), p.current = null), b.current(...w);
  }, []);
  return z(
    // biome-ignore lint/suspicious/noExplicitAny: <explanation>
    (...w) => {
      const S = Date.now(), y = S - o.current, P = S - c.current;
      if (o.current = S, h.current = w, s && y >= t)
        return n();
      if (f.current && clearTimeout(f.current), u !== void 0 && !p.current) {
        const g = u - P;
        g > 0 && (p.current = setTimeout(() => {
          p.current = null, n();
        }, g));
      }
      l && (f.current = setTimeout(() => {
        f.current = null, n();
      }, t));
    },
    [t, s, l, u, n]
  );
}
const L = 1e3;
function Et() {
  const e = ne(), t = We(), r = $e(), { onSaveSite: a } = re(), s = I(
    async (i) => {
      e.setLastSaved(/* @__PURE__ */ new Date());
    },
    L,
    [t.id]
  );
  qe((i) => {
    console.debug("Sections have changed, updating page version", i), s(i);
  });
  const l = I(
    async (i) => {
      e.setLastSaved(/* @__PURE__ */ new Date());
    },
    L,
    [t.id]
  );
  Ve((i) => {
    console.debug("Page label has changed:", i), l(i);
  });
  const u = I(
    async (i) => {
      await a({
        siteId: r.id,
        data: { label: i }
      }), e.setLastSaved(/* @__PURE__ */ new Date());
    },
    L,
    [t.id]
  );
  Fe((i) => {
    console.debug("Site label has changed:", i), u(i);
  });
  const f = I(async (i) => {
    await a({
      siteId: r.id,
      data: { datasources: i }
    }), e.setLastSaved(/* @__PURE__ */ new Date());
  }, L);
  Ge((i) => {
    console.debug("Datasources have changed, saving them", i), f(i);
  });
  const p = I(async (i) => {
    await a?.({
      siteId: r.id,
      data: { datarecords: i }
    }), e.setLastSaved(/* @__PURE__ */ new Date());
  }, L);
  Je((i) => {
    console.debug("Datarecords have changed, saving them", i), p(i);
  });
  const o = I(
    async (i) => {
      e.setLastSaved(/* @__PURE__ */ new Date());
    },
    L,
    [t.id]
  );
  Xe((i) => {
    console.debug("Page attributes have changed, saving them", i), o(i);
  });
  const c = I(async (i) => {
    await a({
      siteId: r.id,
      data: { attributes: i }
    }), e.setLastSaved(/* @__PURE__ */ new Date());
  }, L);
  Ye((i) => {
    console.debug("Site attributes have changed, saving them", i), c(i);
  });
  const h = I(async (i) => {
    await a({
      siteId: r.id,
      data: { theme: i }
    }), e.setLastSaved(/* @__PURE__ */ new Date());
  }, L);
  Qe((i) => {
    console.debug("theme has changed, saving it", i), h(i);
  });
  const b = I(async (i) => {
    await a({
      siteId: r.id,
      data: { themes: i }
    }), e.setLastSaved(/* @__PURE__ */ new Date());
  }, L);
  Ze((i) => {
    console.debug("themes have changed, saving them", i), b(i);
  });
  const n = I(async (i) => {
  }, L);
  et((i) => {
    const w = i.at(-1);
    w && n({
      id: w.id,
      label: w.label,
      sections: [],
      attributes: st({ title: w.label, path: w.path })
    });
  });
}
function te() {
  return te = Object.assign ? Object.assign.bind() : function(e) {
    for (var t = 1; t < arguments.length; t++) {
      var r = arguments[t];
      for (var a in r) ({}).hasOwnProperty.call(r, a) && (e[a] = r[a]);
    }
    return e;
  }, te.apply(null, arguments);
}
var Ce = ["shift", "alt", "meta", "mod", "ctrl"], Dt = {
  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 O(e) {
  return (e && Dt[e] || e || "").trim().toLowerCase().replace(/key|digit|numpad|arrow/, "");
}
function Bt(e) {
  return Ce.includes(e);
}
function G(e, t) {
  return t === void 0 && (t = ","), e.split(t);
}
function J(e, t, r) {
  t === void 0 && (t = "+");
  var a = e.toLocaleLowerCase().split(t).map(function(u) {
    return O(u);
  }), s = {
    alt: a.includes("alt"),
    ctrl: a.includes("ctrl") || a.includes("control"),
    shift: a.includes("shift"),
    meta: a.includes("meta"),
    mod: a.includes("mod")
  }, l = a.filter(function(u) {
    return !Ce.includes(u);
  });
  return te({}, s, {
    keys: l,
    description: r,
    hotkey: e
  });
}
(function() {
  typeof document < "u" && (document.addEventListener("keydown", function(e) {
    e.key !== void 0 && Ee([O(e.key), O(e.code)]);
  }), document.addEventListener("keyup", function(e) {
    e.key !== void 0 && De([O(e.key), O(e.code)]);
  })), typeof window < "u" && window.addEventListener("blur", function() {
    H.clear();
  });
})();
var H = /* @__PURE__ */ new Set();
function ae(e) {
  return Array.isArray(e);
}
function It(e, t) {
  t === void 0 && (t = ",");
  var r = ae(e) ? e : e.split(t);
  return r.every(function(a) {
    return H.has(a.trim().toLowerCase());
  });
}
function Ee(e) {
  var t = Array.isArray(e) ? e : [e];
  H.has("meta") && H.forEach(function(r) {
    return !Bt(r) && H.delete(r.toLowerCase());
  }), t.forEach(function(r) {
    return H.add(r.toLowerCase());
  });
}
function De(e) {
  var t = Array.isArray(e) ? e : [e];
  e === "meta" ? H.clear() : t.forEach(function(r) {
    return H.delete(r.toLowerCase());
  });
}
function Lt(e, t, r) {
  (typeof r == "function" && r(e, t) || r === !0) && e.preventDefault();
}
function Nt(e, t, r) {
  return typeof r == "function" ? r(e, t) : r === !0 || r === void 0;
}
function Rt(e) {
  return Be(e, ["input", "textarea", "select"]);
}
function Be(e, t) {
  t === void 0 && (t = !1);
  var r = e.target, a = e.composed, s = null;
  return At(r) && a ? s = e.composedPath()[0] && e.composedPath()[0].tagName : s = r && r.tagName, ae(t) ? !!(s && t && t.some(function(l) {
    var u;
    return l.toLowerCase() === ((u = s) == null ? void 0 : u.toLowerCase());
  })) : !!(s && t && t);
}
function At(e) {
  return !!e.tagName && !e.tagName.startsWith("-") && e.tagName.includes("-");
}
function Tt(e, t) {
  return e.length === 0 && t ? (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>'), !0) : t ? e.some(function(r) {
    return t.includes(r);
  }) || e.includes("*") : !0;
}
var _t = function(t, r, a) {
  a === void 0 && (a = !1);
  var s = r.alt, l = r.meta, u = r.mod, f = r.shift, p = r.ctrl, o = r.keys, c = t.key, h = t.code, b = t.ctrlKey, n = t.metaKey, i = t.shiftKey, w = t.altKey, S = O(h), y = c.toLowerCase();
  if (!(o != null && o.includes(S)) && !(o != null && o.includes(y)) && !["ctrl", "control", "unknown", "meta", "alt", "shift", "os"].includes(S))
    return !1;
  if (!a) {
    if (s === !w && y !== "alt" || f === !i && y !== "shift")
      return !1;
    if (u) {
      if (!n && !b)
        return !1;
    } else if (l === !n && y !== "meta" && y !== "os" || p === !b && y !== "ctrl" && y !== "control")
      return !1;
  }
  return o && o.length === 1 && (o.includes(y) || o.includes(S)) ? !0 : o ? It(o) : !o;
}, Ot = /* @__PURE__ */ ve(void 0), Ht = function() {
  return ge(Ot);
};
function Ie(e, t) {
  return e && t && typeof e == "object" && typeof t == "object" ? Object.keys(e).length === Object.keys(t).length && //@ts-ignore
  Object.keys(e).reduce(function(r, a) {
    return r && Ie(e[a], t[a]);
  }, !0) : e === t;
}
var Kt = /* @__PURE__ */ ve({
  hotkeys: [],
  enabledScopes: [],
  toggleScope: function() {
  },
  enableScope: function() {
  },
  disableScope: function() {
  }
}), jt = function() {
  return ge(Kt);
};
function Mt(e) {
  var t = B(void 0);
  return Ie(t.current, e) || (t.current = e), t.current;
}
var se = function(t) {
  t.stopPropagation(), t.preventDefault(), t.stopImmediatePropagation();
}, zt = typeof window < "u" ? _e : j;
function x(e, t, r, a) {
  var s = me(null), l = s[0], u = s[1], f = B(!1), p = r instanceof Array ? a instanceof Array ? void 0 : a : r, o = ae(e) ? e.join(p?.splitKey) : e, c = r instanceof Array ? r : a instanceof Array ? a : void 0, h = z(t, c ?? []), b = B(h);
  c ? b.current = h : b.current = t;
  var n = Mt(p), i = jt(), w = i.enabledScopes, S = Ht();
  return zt(function() {
    if (!(n?.enabled === !1 || !Tt(w, n?.scopes))) {
      var y = function(k, _) {
        var E;
        if (_ === void 0 && (_ = !1), !(Rt(k) && !Be(k, n?.enableOnFormTags))) {
          if (l !== null) {
            var N = l.getRootNode();
            if ((N instanceof Document || N instanceof ShadowRoot) && N.activeElement !== l && !l.contains(N.activeElement)) {
              se(k);
              return;
            }
          }
          (E = k.target) != null && E.isContentEditable && !(n != null && n.enableOnContentEditable) || G(o, n?.splitKey).forEach(function(R) {
            var U, A = J(R, n?.combinationKey);
            if (_t(k, A, n?.ignoreModifiers) || (U = A.keys) != null && U.includes("*")) {
              if (n != null && n.ignoreEventWhen != null && n.ignoreEventWhen(k) || _ && f.current)
                return;
              if (Lt(k, A, n?.preventDefault), !Nt(k, A, n?.enabled)) {
                se(k);
                return;
              }
              b.current(k, A), _ || (f.current = !0);
            }
          });
        }
      }, P = function(k) {
        k.key !== void 0 && (Ee(O(k.code)), (n?.keydown === void 0 && n?.keyup !== !0 || n != null && n.keydown) && y(k));
      }, g = function(k) {
        k.key !== void 0 && (De(O(k.code)), f.current = !1, n != null && n.keyup && y(k, !0));
      }, d = l || p?.document || document;
      return d.addEventListener("keyup", g), d.addEventListener("keydown", P), S && G(o, n?.splitKey).forEach(function(v) {
        return S.addHotkey(J(v, n?.combinationKey, n?.description));
      }), function() {
        d.removeEventListener("keyup", g), d.removeEventListener("keydown", P), S && G(o, n?.splitKey).forEach(function(v) {
          return S.removeHotkey(J(v, n?.combinationKey, n?.description));
        });
      };
    }
  }, [l, o, n, w]), u;
}
function Ut() {
  const e = re(), t = oe(), r = ne(), a = Ne(), s = fe(), l = pe(), u = tt(s), { undo: f, redo: p } = rt();
  x("esc", () => {
    e.deselectBrick(), e.setSelectedSectionId(), e.hidePanel();
  }), x("mod+c", () => {
    window.getSelection()?.rangeCount || console.debug("mod+c pressed");
  }), x(["backspace", "del"], (o) => {
    s && (o.preventDefault(), t.deleteBrick(s), e.deselectBrick(s), e.hidePanel("inspector"));
  }), x("s", (o) => {
    o.preventDefault(), e.togglePanel("settings");
  }), x("l", (o) => {
    o.preventDefault(), e.togglePanel("library");
  }), x("t", (o) => {
    o.preventDefault(), e.togglePanel("theme");
  }), x("p", (o) => {
    o.preventDefault(), e.togglePanel();
  }), x(["mod+z", "ctrl+z"], (o) => {
    o.preventDefault(), f();
  }), x(["mod+shift+z", "ctrl+shift+z"], (o) => {
    o.preventDefault(), p();
  }), x(
    ["up", "left"],
    (o) => {
      if (s) {
        o.preventDefault();
        const c = t.getParentBrick(s);
        c ? (c.props.direction === "flex-row" ? "ArrowLeft" : "ArrowUp") === o.key && t.moveBrick(s, "previous") : o.key === "ArrowLeft" && t.moveBrick(s, "previous");
      } else if (l && o.key === "ArrowUp") {
        o.preventDefault(), t.moveSectionUp(l);
        const c = document.getElementById(l);
        c && c.scrollIntoView({ behavior: "smooth", block: "center" });
      }
    },
    {
      enableOnContentEditable: !1
    }
  ), x(
    ["down", "right"],
    (o) => {
      if (s) {
        o.preventDefault();
        const c = t.getParentBrick(s);
        c ? (c.props.direction === "flex-row" ? "ArrowRight" : "ArrowDown") === o.key && t.moveBrick(s, "next") : o.key === "ArrowRight" && t.moveBrick(s, "next");
      } else if (l && o.key === "ArrowDown") {
        o.preventDefault(), t.moveSectionDown(l);
        const c = document.getElementById(l);
        c && c.scrollIntoView({ behavior: "smooth", block: "center" });
      }
    },
    {
      enableOnContentEditable: !1
    }
  ), x("mod+d", (o) => {
    o.preventDefault(), s && (t.duplicateBrick(s), ze("Brick duplicated", {
      id: "duplicate-brick"
    }));
  }), x("mod+j", (o) => {
    o.preventDefault(), e.toggleEditorEnabled();
  }), x("mod+g", (o) => {
    o.preventDefault(), console.log("Debugging draft:");
    const { page: c, site: h } = r;
    console.log({ page: c, site: h });
  }), x(
    "space",
    (o) => {
      o.target.classList.contains("tiptap") || (o.preventDefault(), o.stopPropagation(), u && t.updateBrickProps(
        u.id,
        {
          grow: !u.props.grow
        },
        a === "mobile"
      ));
    },
    {
      enableOnContentEditable: !0
    }
  );
}
function Wt() {
  return globalThis.location?.hostname === "localhost";
}
var $t = Object.defineProperty, qt = Object.defineProperties, Vt = Object.getOwnPropertyDescriptors, ce = Object.getOwnPropertySymbols, Ft = Object.prototype.hasOwnProperty, Gt = Object.prototype.propertyIsEnumerable, le = (e, t, r) => t in e ? $t(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r, ue = (e, t) => {
  for (var r in t || (t = {}))
    Ft.call(t, r) && le(e, r, t[r]);
  if (ce)
    for (var r of ce(t))
      Gt.call(t, r) && le(e, r, t[r]);
  return e;
}, de = (e, t) => qt(e, Vt(t));
function Jt(e, t, r) {
  if (t === r)
    return e;
  const a = e.slice();
  return a.splice(r, 0, a.splice(t, 1)[0]), a;
}
function Xt(e, t, r) {
  var a, s;
  const { source: l, target: u, canceled: f } = t.operation;
  if (!l || !u || f)
    return "preventDefault" in t && t.preventDefault(), e;
  const p = (g, d) => g === d || typeof g == "object" && "id" in g && g.id === d;
  if (Array.isArray(e)) {
    const g = e.findIndex((v) => p(v, l.id)), d = e.findIndex((v) => p(v, u.id));
    if (g === -1 || d === -1)
      return e;
    if (!f && "index" in l && typeof l.index == "number") {
      const v = l.index;
      if (v !== g)
        return r(e, g, v);
    }
    return r(e, g, d);
  }
  const o = Object.entries(e);
  let c = -1, h, b = -1, n;
  for (const [g, d] of o)
    if (c === -1 && (c = d.findIndex((v) => p(v, l.id)), c !== -1 && (h = g)), b === -1 && (b = d.findIndex((v) => p(v, u.id)), b !== -1 && (n = g)), c !== -1 && b !== -1)
      break;
  if (!l.manager) return e;
  const { dragOperation: i } = l.manager, w = (s = (a = i.shape) == null ? void 0 : a.current.center) != null ? s : i.position.current;
  if (n == null && u.id in e) {
    const g = u.shape && w.y > u.shape.center.y ? e[u.id].length : 0;
    n = u.id, b = g;
  }
  if (h == null || n == null || h === n && c === b)
    return "preventDefault" in t && t.preventDefault(), e;
  if (h === n)
    return de(ue({}, e), {
      [h]: r(e[h], c, b)
    });
  const y = u.shape && Math.round(w.y) > Math.round(u.shape.center.y) ? 1 : 0, P = e[h][c];
  return de(ue({}, e), {
    [h]: [
      ...e[h].slice(0, c),
      ...e[h].slice(c + 1)
    ],
    [n]: [
      ...e[n].slice(0, b + y),
      P,
      ...e[n].slice(b + y)
    ]
  });
}
function Yt(e, t) {
  return Xt(e, t, Jt);
}
function Qt(e = !0, t) {
  const r = z(
    (a) => {
      if (typeof e != "function" || e())
        return a.preventDefault(), a.returnValue = t, t;
    },
    [e, t]
  );
  j(() => {
    if (e)
      return window.addEventListener("beforeunload", r), () => window.removeEventListener("beforeunload", r);
  }, [e, r]);
}
let q = { credits: 0, config: {} };
const V = /* @__PURE__ */ new Set();
let X = null, M = null, Y = !1;
async function Zt() {
  const e = "/editor/config";
  try {
    const t = await fetch(e);
    return t.status === 200 && t.headers.get("content-type")?.startsWith("application/json") ? await t.json() ?? {} : (console.warn("useConfig: ignoring invalid response"), {});
  } catch (t) {
    return console.error("useConfig: fetch error", t), {};
  }
}
async function Le() {
  const e = await Zt();
  q = {
    ...q,
    ...e
  }, V.forEach((t) => t(q));
}
function er() {
  M || (M = setInterval(() => {
    Le().catch((e) => {
      console.error("useConfig: polling error", e);
    });
  }, 2e4));
}
function tr() {
  M && (clearInterval(M), M = null);
}
function rr() {
  const [e, t] = me(q), r = B(null), a = z((s) => {
    t(s);
  }, []);
  return j(() => (r.current || (r.current = a), V.add(r.current), Y || (Y = !0, X || (X = Le().finally(() => {
    X = null;
  })), er()), () => {
    r.current && V.delete(r.current), V.size === 0 && (tr(), Y = !1);
  }), [a]), e;
}
const nr = T(() => import("./Tour.DYXtm8fv.js")), or = T(() => import("./NavBar.CD9LB0Is.js")), ar = T(() => import("./ChatComponent.DuJivMsp.js").then((e) => e.C)), ir = T(() => import("./EditablePage.BUTWtpla.js")), Q = T(() => import("./DeviceFrame.BKZoqOb2.js")), sr = T(() => import("./Panel.CxSxXbvF.js")), cr = T(() => import("./Modal.CNs6H_oE.js")), lr = T(() => import("./ThemesPreviewList.D-6GKnJh.js")), ur = T(() => import("./BlankWaitPage.4WhOQreu.js"));
function xr(e) {
  const t = B(null), r = ne(), a = Re(), s = nt(), { panelPosition: l } = Ae(), u = ot(), f = at(), p = oe(), { setDraggingBrickType: o, toggleDebugMode: c, hidePanel: h } = re(), b = fe(), n = pe(), i = Wt(), w = Te(), S = rr(), y = B(null);
  return Et(), Ut(), Qt(() => !!r.dirty, "You have unsaved changes. Are you sure you want to leave?"), j(() => {
    const P = r.previewTheme ?? r.site.theme;
    P && Oe($(ct(P)));
  }, [r.previewTheme, r.site.theme]), /* @__PURE__ */ m(
    lt,
    {
      onDragStart: (P, g) => {
        const { operation: d } = P;
        if (d.source?.type === "library") {
          const v = d.source.data.manifest.type;
          o(v);
          return;
        }
        if (console.log(`Started dragging ${d.source?.id}`), d.source?.id) {
          const v = document.getElementById(d.source.id);
          if (!v)
            return;
          console.log(`adding class ${d.source.id}`), v?.classList.add("moving"), v.style.setProperty("box-shadow", "0 4px 8px rgba(0, 0, 0, 0.2)", "important"), v.style.setProperty("outline", "2px solid var(--violet-8)", "important"), v.style.setProperty("outline-offset", "0px", "important"), window.getComputedStyle(v).getPropertyValue("background-color") === "rgba(0, 0, 0, 0)" && (console.log("Changing background color to upstart-200"), v.style.setProperty("background-color", "var(--violet-a5)", "important"));
        }
      },
      onDragOver: (P, g) => {
        const { operation: d } = P, v = d.source?.type === "library";
        if (d.canceled || !d.target)
          return;
        if (d.target?.data?.manifest?.isContainer && d.activatorEvent?.metaKey) {
          console.log("operation.activatorEvent", d.activatorEvent), console.error("Dropping over a container, disable reordering"), P.preventDefault();
          return;
        }
        const k = s.reduce(
          (E, N) => (E[N.id] = N.bricks.filter((R) => !p.getParentBrick(R.id)).map((R) => R.id), E),
          {}
        );
        v && (k.$library$ = y.current ? [] : [d.source.id]);
        const _ = Yt(k, P);
        if (ie(k, _))
          console.debug("Items are equal, no changes made");
        else
          for (const E of s)
            if (!ie(k[E.id], _[E.id])) {
              console.log("Rebuilding section", E.id);
              const N = {
                ...E,
                bricks: _[E.id].map((R, U) => {
                  if (v && R === d.source.id && !p.getBrick(R)) {
                    const A = it(d.source.data?.manifest.type, !0);
                    return y.current = A.id, p.addBrick(A, E.id, U, null), A;
                  }
                  return p.getBrick(R);
                })
              };
              p.updateSection(E.id, N);
            }
      },
      onDragEnd: (P) => {
        console.log("Ended dragging", P);
        const {
          operation: { source: g }
        } = P;
        y.current && p.updateBrickProps(y.current, { ghost: !1 }), o(null), y.current = null, g?.id && setTimeout(() => {
          const d = document.getElementById(g.id);
          d && (d.classList.remove("moving"), d.style.removeProperty("box-shadow"), d.style.removeProperty("outline"), d.style.removeProperty("outline-offset"), d.style.removeProperty("background-color"));
        }, 200);
      },
      children: /* @__PURE__ */ D(
        "div",
        {
          id: "editor",
          className: W(
            "grid relative transition-all mx-auto w-full",
            dr(f, a),
            "h-[100dvh] min-h-[100dvh] max-h-[100dvh]",
            f.isReady === !1 && $({
              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)
          )`
            }),
            f.isReady === !1 && "transition-all duration-500 ease-in-out"
          ),
          ...e,
          ref: t,
          children: [
            s.length > 0 && f.isReady && /* @__PURE__ */ m(K, { children: /* @__PURE__ */ m(nr, {}) }),
            /* @__PURE__ */ m(K, { children: /* @__PURE__ */ m(or, {}) }),
            a && /* @__PURE__ */ m(K, { children: /* @__PURE__ */ m(ar, {}) }),
            /* @__PURE__ */ D(K, { children: [
              /* @__PURE__ */ m(cr, {}),
              /* @__PURE__ */ m(sr, {}),
              !f.isReady && w === !0 && /* @__PURE__ */ D("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__ */ m("h2", { className: "text-xl font-bold", children: "Debug Information" }),
                /* @__PURE__ */ m("h4", { className: "text-lg font-semibold", children: "Site" }),
                /* @__PURE__ */ m("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(r.site, null, 2) }),
                /* @__PURE__ */ m("h4", { className: "text-lg font-semibold", children: "Page" }),
                /* @__PURE__ */ m("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(r.page, null, 2) }),
                /* @__PURE__ */ m("h4", { className: "text-lg font-semibold", children: "User config" }),
                /* @__PURE__ */ m("pre", { className: "whitespace-pre-wrap break-words text-[75%]", children: JSON.stringify(S, null, 2) })
              ] })
            ] }),
            /* @__PURE__ */ m(
              Ue,
              {
                toastOptions: {
                  position: "bottom-center",
                  style: {
                    background: "rgba(0, 0, 0, 0.85)",
                    color: "white",
                    fontSize: "0.85rem",
                    fontWeight: "500"
                    // marginBottom: "1rem",
                  },
                  className: W("last:mb-1 px-1 py-1 rounded-lg"),
                  error: {
                    style: {
                      background: "#880808"
                    }
                  }
                }
              }
            ),
            i && /* @__PURE__ */ D(
              "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__ */ D("div", { className: "px-2", children: [
                    "Selected brick: ",
                    b ?? "none"
                  ] }),
                  /* @__PURE__ */ D("div", { className: "px-2", children: [
                    "Selected section: ",
                    n ?? "none"
                  ] }),
                  /* @__PURE__ */ D("div", { className: "flex items-center gap-1 px-2", children: [
                    /* @__PURE__ */ m(xe, { defaultChecked: w, onCheckedChange: c, size: "1", id: "debug-mode" }),
                    /* @__PURE__ */ D("label", { htmlFor: "debug-mode", className: "cursor-pointer select-none", children: [
                      "Debug mode",
                      " ",
                      /* @__PURE__ */ m("b", { className: W("font-semibold", w ? "text-upstart-600" : "text-gray-500"), children: w ? "on" : "off" })
                    ] })
                  ] })
                ]
              }
            ),
            /* @__PURE__ */ D(
              "main",
              {
                className: W(
                  "flex-1 flex place-content-center z-40 overflow-x-auto overscroll-none",
                  f.isReady === !1 && "!hidden",
                  $({
                    gridArea: "main",
                    scrollbarColor: "var(--violet-4) var(--violet-2)",
                    scrollBehavior: "smooth",
                    scrollbarGutter: "stable",
                    scrollbarWidth: l === "left" ? "thin" : "none",
                    "&:hover": {
                      scrollbarColor: "var(--violet-7) var(--violet-3)"
                    }
                  })
                ),
                children: [
                  f.isReady && /* @__PURE__ */ m(K, { children: /* @__PURE__ */ D(Q, { children: [
                    /* @__PURE__ */ m(ir, {}),
                    r.previewTheme && /* @__PURE__ */ m(fr, {})
                  ] }) }),
                  !f.isReady && (u.length > 0 ? /* @__PURE__ */ m(Q, { children: /* @__PURE__ */ m(K, { children: /* @__PURE__ */ m(lr, { themes: u }) }) }) : /* @__PURE__ */ m(Q, { children: /* @__PURE__ */ m(K, { children: /* @__PURE__ */ m(ur, {}) }) }))
                ]
              }
            )
          ]
        }
      )
    }
  );
}
function dr(e, t) {
  return $({
    gridTemplateAreas: t ? '"navbar navbar" "chat main"' : '"navbar" "main"',
    gridTemplateRows: "64px 1fr",
    gridTemplateColumns: e.isReady === !1 ? "1fr 0px" : t ? "360px 1fr" : "1fr"
    // maxWidth: generationState.isReady === false ? "clamp(500px, 40dvw, 650px)" : "none",
  });
}
function fr() {
  const { validatePreviewTheme: e } = oe();
  return /* @__PURE__ */ m("div", { className: "fixed bottom-0 left-0 right-0 flex justify-center items-center z-[9999]", children: /* @__PURE__ */ D("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__ */ m(ee, { variant: "solid", color: "gray", onClick: () => e(!1), children: "Revert" }),
    /* @__PURE__ */ m(ee, { onClick: () => e(!0), variant: "solid", children: "Accept theme" })
  ] }) });
}
export {
  xr as E,
  vt as a,
  xe as i,
  ee as o,
  rr as u
};
