const A = ".rte-content, .editora-content", C = '.rte-data-binding[data-binding="true"]', it = "rte-data-binding-styles", g = "rte-data-binding-dialog-overlay", f = ':is([data-theme="dark"], .dark, .editora-theme-dark, .rte-theme-dark)', yt = {
  dialogTitleInsert: "Insert Data Binding",
  dialogTitleEdit: "Edit Data Binding",
  keyLabel: "Data Key",
  keyPlaceholder: "user.firstName",
  fallbackLabel: "Fallback Text",
  fallbackPlaceholder: "Guest",
  formatLabel: "Format",
  currencyLabel: "Currency",
  currencyPlaceholder: "USD",
  saveText: "Save",
  cancelText: "Cancel",
  previewOnText: "Preview On",
  previewOffText: "Preview Off",
  tokenAriaPrefix: "Data binding token"
}, x = /* @__PURE__ */ new WeakMap(), W = /* @__PURE__ */ new WeakMap(), b = /* @__PURE__ */ new WeakMap(), K = /* @__PURE__ */ new WeakMap(), G = /* @__PURE__ */ new WeakMap();
let N = null, h = null, U = 0, P = null, O = null, M = null, z = null;
function ht(t) {
  return {
    ...yt,
    ...t || {}
  };
}
function ot(t = {}) {
  const n = (t.locale || (typeof navigator < "u" ? navigator.language : "en-US")).trim() || "en-US";
  return {
    data: t.data,
    getData: t.getData,
    api: t.api,
    cacheTtlMs: Math.max(0, Number(t.cacheTtlMs ?? 3e4)),
    labels: ht(t.labels),
    defaultFormat: t.defaultFormat || "text",
    defaultFallback: t.defaultFallback || "",
    locale: n,
    numberFormatOptions: t.numberFormatOptions || {},
    dateFormatOptions: t.dateFormatOptions || { year: "numeric", month: "short", day: "2-digit" }
  };
}
function y(t) {
  return t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
function dt(t) {
  return t ? t.nodeType === Node.ELEMENT_NODE ? t : t.parentElement : null;
}
function j(t) {
  return t.closest("[data-editora-editor], .rte-editor, .editora-editor, editora-editor") || t;
}
function q(t) {
  return t ? (t.getAttribute("data-theme") || t.getAttribute("theme") || "").toLowerCase() === "dark" ? !0 : t.classList.contains("dark") || t.classList.contains("editora-theme-dark") || t.classList.contains("rte-theme-dark") : !1;
}
function kt(t) {
  const n = j(t);
  if (q(n)) return !0;
  const a = n.closest("[data-theme], [theme], .dark, .editora-theme-dark, .rte-theme-dark");
  return q(a) ? !0 : q(document.documentElement) || q(document.body);
}
function D(t, n = !0) {
  if (t?.contentElement instanceof HTMLElement) return t.contentElement;
  if (t?.editorElement instanceof HTMLElement) {
    const e = t.editorElement;
    if (e.matches(A)) return e;
    const i = e.querySelector(A);
    if (i instanceof HTMLElement) return i;
  }
  const a = window.getSelection();
  if (a && a.rangeCount > 0) {
    const e = a.getRangeAt(0).startContainer, o = dt(e)?.closest(A);
    if (o) return o;
  }
  const r = document.activeElement;
  if (r) {
    if (r.matches(A)) return r;
    const e = r.closest(A);
    if (e) return e;
  }
  return h && h.isConnected ? h : n ? document.querySelector(A) : null;
}
function R(t) {
  return t.getAttribute("contenteditable") === "false" || t.getAttribute("data-readonly") === "true";
}
function lt(t) {
  const n = window.getSelection();
  if (!n || n.rangeCount === 0) return null;
  const a = n.getRangeAt(0);
  return t.contains(a.commonAncestorContainer) ? a.cloneRange() : null;
}
function st(t, n) {
  const a = window.getSelection();
  a && (a.removeAllRanges(), a.addRange(n), t.focus({ preventScroll: !0 }));
}
function xt(t, n) {
  const a = (n || "").trim();
  if (a)
    return a.split(".").filter(Boolean).reduce((r, e) => {
      if (!(r == null || typeof r != "object"))
        return r[e];
    }, t);
}
function vt() {
  if (typeof document > "u" || document.getElementById(it)) return;
  const t = document.createElement("style");
  t.id = it, t.textContent = `
    .rte-data-binding {
      display: inline-flex;
      align-items: center;
      max-width: 100%;
      gap: 5px;
      padding: 2px 8px 2px 7px;
      border-radius: 999px;
      border: 1px dashed #8b5cf6;
      background: linear-gradient(180deg, #f9f7ff 0%, #f1edff 100%);
      color: #4c1d95;
      font-size: 0.88em;
      font-weight: 600;
      line-height: 1.3;
      vertical-align: baseline;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      user-select: all;
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
      cursor: pointer;
    }

    .rte-data-binding::before {
      content: '{}';
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 14px;
      height: 14px;
      border-radius: 999px;
      background: rgba(139, 92, 246, 0.16);
      color: #5b21b6;
      font-size: 10px;
      font-weight: 700;
      line-height: 1;
      letter-spacing: -0.2px;
      flex: 0 0 auto;
    }

    .rte-data-binding.rte-data-binding-preview {
      border-style: solid;
      background: #ecfdf5;
      border-color: #34d399;
      color: #065f46;
      user-select: text;
    }

    .rte-data-binding.rte-data-binding-preview::before {
      content: '=';
      background: rgba(16, 185, 129, 0.15);
      color: #047857;
      letter-spacing: 0;
    }

    .rte-data-binding.rte-data-binding-missing {
      border-style: dashed;
      border-color: #f87171;
      background: #fef2f2;
      color: #991b1b;
    }

    .rte-data-binding-dialog-overlay {
      position: fixed;
      inset: 0;
      z-index: 2147483646;
      background: rgba(15, 23, 42, 0.54);
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
    }

    .rte-data-binding-dialog {
      width: min(560px, 96vw);
      max-height: min(86vh, 720px);
      border: 1px solid #dbe3ec;
      border-radius: 8px;
      background: #ffffff;
      box-shadow: 0 24px 50px rgba(15, 23, 42, 0.26);
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    .rte-data-binding-header,
    .rte-data-binding-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      padding: 12px 14px;
      background: #f8fafc;
      border-bottom: 1px solid #e2e8f0;
    }

    .rte-data-binding-footer {
      justify-content: flex-end;
      border-bottom: 0;
      border-top: 1px solid #e2e8f0;
    }

    .rte-data-binding-title {
      margin: 0;
      font-size: 16px;
      font-weight: 700;
      color: #0f172a;
    }

    .rte-data-binding-body {
      padding: 14px;
      overflow: auto;
      display: grid;
      gap: 12px;
      grid-template-columns: 1fr;
    }

    .rte-data-binding-field {
      display: grid;
      gap: 6px;
    }

    .rte-data-binding-field label {
      font-size: 12px;
      font-weight: 600;
      color: #334155;
    }

    .rte-data-binding-field input,
    .rte-data-binding-field select {
      width: 100%;
      min-height: 36px;
      border: 1px solid #cbd5e1;
      border-radius: 6px;
      padding: 8px 10px;
      font-size: 13px;
      line-height: 1.4;
      color: #0f172a;
      background: #ffffff;
      box-sizing: border-box;
    }

    .rte-data-binding-help {
      margin: 0;
      font-size: 12px;
      color: #64748b;
    }

    .rte-data-binding-btn {
      border: 1px solid #cbd5e1;
      border-radius: 6px;
      min-height: 34px;
      padding: 6px 12px;
      background: #ffffff;
      color: #0f172a;
      font-size: 13px;
      cursor: pointer;
    }

    .rte-data-binding-btn-primary {
      background: #2563eb;
      border-color: #2563eb;
      color: #ffffff;
    }

    .rte-data-binding-btn-primary:hover {
      background: #1d4ed8;
    }

    .rte-toolbar-group-items.data-binding,
    .editora-toolbar-group-items.data-binding {
      display: flex;
      border: 1px solid #cbd5e1;
      border-radius: 6px;
      overflow: hidden;
      background: #ffffff;
    }

    .rte-toolbar-group-items.data-binding .rte-toolbar-item,
    .editora-toolbar-group-items.data-binding .editora-toolbar-item {
      display: flex;
    }

    .rte-toolbar-group-items.data-binding .rte-toolbar-button,
    .editora-toolbar-group-items.data-binding .editora-toolbar-button {
      border: 0;
      border-radius: 0;
      border-right: 1px solid #cbd5e1;
    }

    .rte-toolbar-group-items.data-binding .rte-toolbar-item:last-child .rte-toolbar-button,
    .editora-toolbar-group-items.data-binding .editora-toolbar-item:last-child .editora-toolbar-button {
      border-right: 0;
    }

    .rte-data-binding-btn:focus-visible,
    .rte-data-binding-field input:focus-visible,
    .rte-data-binding-field select:focus-visible {
      outline: none;
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
    }

    ${f} .rte-data-binding,
    .${g}.rte-data-binding-theme-dark .rte-data-binding {
      background: linear-gradient(180deg, #3b0764 0%, #2e1065 100%);
      border-color: #a78bfa;
      color: #ede9fe;
    }

    ${f} .rte-data-binding::before,
    .${g}.rte-data-binding-theme-dark .rte-data-binding::before {
      background: rgba(167, 139, 250, 0.22);
      color: #ddd6fe;
    }

    ${f} .rte-data-binding.rte-data-binding-preview,
    .${g}.rte-data-binding-theme-dark .rte-data-binding.rte-data-binding-preview {
      background: #064e3b;
      border-color: #10b981;
      color: #d1fae5;
    }

    ${f} .rte-data-binding.rte-data-binding-missing,
    .${g}.rte-data-binding-theme-dark .rte-data-binding.rte-data-binding-missing {
      background: #7f1d1d;
      border-color: #ef4444;
      color: #fee2e2;
    }

    ${f} .rte-toolbar-group-items.data-binding,
    ${f} .editora-toolbar-group-items.data-binding {
      display: flex;
      border: 1px solid #566275;
      border-radius: 6px;
      overflow: hidden;
    }

    ${f} .rte-toolbar-group-items.data-binding .rte-toolbar-button,
    ${f} .editora-toolbar-group-items.data-binding .editora-toolbar-button {
      border-right-color: #566275;
    }

    ${f} .rte-data-binding-dialog,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-dialog {
      background: #1f2937;
      border-color: #334155;
    }

    ${f} .rte-data-binding-header,
    ${f} .rte-data-binding-footer,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-header,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-footer {
      background: #111827;
      border-color: #334155;
    }

    ${f} .rte-data-binding-title,
    ${f} .rte-data-binding-field label,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-title,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-field label {
      color: #e2e8f0;
    }

    ${f} .rte-data-binding-help,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-help {
      color: #94a3b8;
    }

    ${f} .rte-data-binding-field input,
    ${f} .rte-data-binding-field select,
    ${f} .rte-data-binding-btn,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-field input,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-field select,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-btn {
      background: #0f172a;
      border-color: #475569;
      color: #e2e8f0;
    }

    ${f} .rte-data-binding-btn-primary,
    .${g}.rte-data-binding-theme-dark .rte-data-binding-btn-primary {
      background: #2563eb;
      border-color: #2563eb;
      color: #ffffff;
    }
  `, document.head.appendChild(t);
}
function J(t) {
  t.dispatchEvent(new Event("input", { bubbles: !0 }));
}
function Y(t, n) {
  if (n === t.innerHTML) return;
  const a = window.execEditorCommand || window.executeEditorCommand;
  if (typeof a == "function")
    try {
      a("recordDomTransaction", t, n, t.innerHTML);
    } catch {
    }
}
function H(t, n) {
  return {
    key: String(t.key || "").trim(),
    fallback: String(t.fallback ?? n.defaultFallback ?? ""),
    format: t.format || n.defaultFormat || "text",
    currency: String(t.currency || "USD").trim().toUpperCase() || "USD"
  };
}
function ct(t) {
  return `{{${t.key}}}`;
}
function ut(t, n) {
  const a = document.createElement("span");
  return a.className = "rte-data-binding", a.setAttribute("data-binding", "true"), a.setAttribute("data-binding-key", t.key), a.setAttribute("data-binding-fallback", t.fallback || ""), a.setAttribute("data-binding-format", t.format || "text"), a.setAttribute("data-binding-currency", t.currency || "USD"), a.setAttribute("contenteditable", "false"), a.setAttribute("spellcheck", "false"), a.setAttribute("draggable", "false"), a.setAttribute("tabindex", "0"), a.setAttribute("role", "button"), a.setAttribute("aria-label", `${n.tokenAriaPrefix}: ${t.key}. Press Enter to edit.`), a.textContent = ct(t), a;
}
function Z(t, n) {
  return H(
    {
      key: t.getAttribute("data-binding-key") || "",
      fallback: t.getAttribute("data-binding-fallback") || n.defaultFallback,
      format: t.getAttribute("data-binding-format") || n.defaultFormat,
      currency: t.getAttribute("data-binding-currency") || "USD"
    },
    n
  );
}
function X(t, n, a) {
  t.classList.add("rte-data-binding"), t.setAttribute("data-binding", "true"), t.setAttribute("data-binding-key", n.key), t.setAttribute("data-binding-fallback", n.fallback || ""), t.setAttribute("data-binding-format", n.format || "text"), t.setAttribute("data-binding-currency", n.currency || "USD"), t.setAttribute("contenteditable", "false"), t.setAttribute("spellcheck", "false"), t.setAttribute("draggable", "false"), t.setAttribute("tabindex", "0"), t.setAttribute("role", "button"), t.setAttribute("aria-label", `${a.tokenAriaPrefix}: ${n.key}. Press Enter to edit.`);
}
function V(t, n) {
  const a = Array.from(t.querySelectorAll(C));
  return a.forEach((r) => {
    const e = Z(r, n);
    X(r, e, n.labels);
  }), a;
}
function Q(t) {
  const n = window.getSelection();
  if (n && n.rangeCount > 0) {
    const e = n.getRangeAt(0).startContainer, o = dt(e)?.closest(C);
    if (o && t.contains(o)) return o;
  }
  const r = document.activeElement?.closest(C);
  return r && t.contains(r) ? r : null;
}
function ft() {
  N && (N.cleanup(), N = null);
}
function tt(t, n, a) {
  const r = j(t);
  Array.from(r.querySelectorAll('[data-command="toggleDataBindingPreview"]')).forEach((i) => {
    if (i.setAttribute("data-active", n ? "true" : "false"), i.classList.toggle("active", n), i.setAttribute("aria-pressed", n ? "true" : "false"), a) {
      const o = n ? a.labels.previewOnText : a.labels.previewOffText;
      i.setAttribute("title", o), i.setAttribute("aria-label", o);
    }
  });
}
function wt(t, n, a) {
  const r = n.format || "text";
  if (t == null) return n.fallback || "";
  if (r === "json") {
    if (typeof t == "string") return t;
    try {
      return JSON.stringify(t);
    } catch {
      return String(t);
    }
  }
  if (r === "date") {
    const e = t instanceof Date ? t : new Date(String(t));
    if (Number.isNaN(e.getTime())) return String(t);
    try {
      return new Intl.DateTimeFormat(a.locale, a.dateFormatOptions).format(e);
    } catch {
      return e.toISOString();
    }
  }
  if (r === "number" || r === "currency") {
    const e = typeof t == "number" ? t : Number(t);
    if (!Number.isFinite(e)) return String(t);
    const i = { ...a.numberFormatOptions };
    if (r === "currency") {
      const o = (n.currency || "USD").toUpperCase();
      Object.assign(i, { style: "currency", currency: o });
    }
    try {
      return new Intl.NumberFormat(a.locale, i).format(e);
    } catch {
      return String(e);
    }
  }
  return String(t);
}
function T(t, n, a, r) {
  const e = Z(t, n), i = e.key;
  if (t.classList.remove("rte-data-binding-preview", "rte-data-binding-missing"), !a) {
    t.textContent = ct(e), t.setAttribute("aria-label", `${n.labels.tokenAriaPrefix}: ${i}. Press Enter to edit.`);
    return;
  }
  const o = xt(r, i), l = o == null, d = l ? e.fallback || "" : wt(o, e, n);
  t.textContent = d || e.fallback || "", t.classList.add("rte-data-binding-preview"), l && !(e.fallback || "").trim() && t.classList.add("rte-data-binding-missing"), t.setAttribute("aria-label", `${n.labels.tokenAriaPrefix}: ${i} = ${t.textContent || ""}. Press Enter to edit.`);
}
function v(t) {
  return typeof t == "object" && t !== null && !Array.isArray(t);
}
function Et(t, n) {
  return n ? n.split(".").filter(Boolean).reduce((a, r) => {
    if (!(!v(a) && !Array.isArray(a)))
      return a[r];
  }, t) : t;
}
function Dt(t, n, a) {
  const r = n.api, e = j(t), i = { editor: t, editorRoot: e, signal: a };
  if (r.buildRequest) {
    const p = r.buildRequest(i);
    return { url: p.url, init: { ...p.init || {}, signal: a } };
  }
  const o = (r.method || "GET").toUpperCase(), l = typeof r.headers == "function" ? r.headers(i) : r.headers || {}, d = typeof r.params == "function" ? r.params(i) : r.params, c = new URL(r.url, window.location.origin);
  d && Object.entries(d).forEach(([p, m]) => {
    m != null && c.searchParams.set(p, String(m));
  });
  const u = {
    method: o,
    headers: { ...l },
    credentials: r.credentials,
    mode: r.mode,
    cache: r.cache,
    signal: a
  };
  if (o !== "GET" && o !== "HEAD") {
    const p = typeof r.body == "function" ? r.body(i) : r.body;
    if (p != null)
      if (v(p)) {
        u.body = JSON.stringify(p);
        const m = u.headers;
        !m["Content-Type"] && !m["content-type"] && (m["Content-Type"] = "application/json");
      } else
        u.body = p;
  }
  return { url: c.toString(), init: u };
}
async function At(t, n) {
  const a = n.api;
  if (!a) return {};
  const r = new AbortController(), e = j(t), i = { editor: t, editorRoot: e, signal: r.signal }, o = Math.max(0, Number(a.timeoutMs ?? 1e4));
  let l = null;
  o > 0 && (l = window.setTimeout(() => r.abort(), o));
  try {
    const { url: d, init: c } = Dt(t, n, r.signal), u = await fetch(d, { ...c, signal: r.signal });
    if (!u.ok)
      throw new Error(`Data binding API request failed: ${u.status}`);
    const m = (a.responseType || "json") === "text" ? await u.text() : await u.json();
    if (a.transformResponse) {
      const B = a.transformResponse(m, i);
      return v(B) ? B : {};
    }
    const $ = Et(m, a.responsePath);
    return v($) ? $ : v(m) ? m : { value: $ };
  } catch (d) {
    return d?.name !== "AbortError" && a.onError?.(d, i), {};
  } finally {
    l !== null && window.clearTimeout(l);
  }
}
async function I(t, n) {
  const a = W.get(t);
  if (a) return a;
  const r = K.get(t), e = Date.now();
  if (r && e - r.timestamp <= n.cacheTtlMs)
    return r.data;
  const i = G.get(t);
  if (i) return i;
  const o = (async () => {
    try {
      if (typeof n.getData == "function") {
        const d = await Promise.resolve(n.getData({ editor: t, editorRoot: j(t) }));
        if (v(d)) return d;
      }
      if (n.api) {
        const d = await At(t, n);
        if (v(d)) return d;
      }
      if (typeof n.data == "function") {
        const d = await Promise.resolve(n.data());
        if (v(d)) return d;
      }
      return v(n.data) ? n.data : {};
    } finally {
      G.delete(t);
    }
  })();
  G.set(t, o);
  const l = await o;
  return K.set(t, { timestamp: e, data: l }), l;
}
async function _(t, n, a) {
  const r = V(t, n);
  if (x.set(t, a), tt(t, a, n), !a) {
    r.forEach((i) => T(i, n, !1));
    return;
  }
  const e = await I(t, n);
  r.forEach((i) => T(i, n, !0, e));
}
function bt(t, n) {
  let a = lt(t);
  a || (a = document.createRange(), a.selectNodeContents(t), a.collapse(!1)), a.collapsed || a.deleteContents(), a.insertNode(n);
  const r = document.createTextNode(" ");
  n.after(r);
  const e = document.createRange();
  e.setStart(r, 1), e.collapse(!0), st(t, e), t.normalize();
}
function gt(t) {
  return typeof t.key == "string" ? t.key.toLowerCase() : "";
}
function St(t) {
  const n = t.metaKey || t.ctrlKey, a = gt(t), r = n && t.altKey && t.shiftKey && a === "d", e = !t.metaKey && !t.ctrlKey && !t.altKey && !t.shiftKey && a === "f7";
  return r || e;
}
function Tt(t) {
  const n = t.metaKey || t.ctrlKey, a = gt(t), r = n && t.altKey && t.shiftKey && a === "b", e = !t.metaKey && !t.ctrlKey && !t.altKey && !t.shiftKey && a === "f8";
  return r || e;
}
function S(t, n, a, r, e) {
  ft();
  const i = a === "insert" ? lt(t) : null, o = n.labels, l = e ? Z(e, n) : H(r || {}, n), d = document.createElement("div");
  d.className = g, kt(t) && d.classList.add("rte-data-binding-theme-dark");
  const c = document.createElement("section");
  c.className = "rte-data-binding-dialog", c.setAttribute("role", "dialog"), c.setAttribute("aria-modal", "true"), c.setAttribute("aria-labelledby", "rte-data-binding-dialog-title"), c.innerHTML = `
    <header class="rte-data-binding-header">
      <h2 id="rte-data-binding-dialog-title" class="rte-data-binding-title">${y(
    a === "edit" ? o.dialogTitleEdit : o.dialogTitleInsert
  )}</h2>
      <button type="button" class="rte-data-binding-btn" data-action="cancel" aria-label="${y(o.cancelText)}">✕</button>
    </header>
    <div class="rte-data-binding-body">
      <div class="rte-data-binding-field">
        <label for="rte-data-binding-key">${y(o.keyLabel)}</label>
        <input id="rte-data-binding-key" class="rte-data-binding-key" type="text" value="${y(l.key)}" placeholder="${y(
    o.keyPlaceholder
  )}" />
      </div>
      <div class="rte-data-binding-field">
        <label for="rte-data-binding-fallback">${y(o.fallbackLabel)}</label>
        <input id="rte-data-binding-fallback" class="rte-data-binding-fallback" type="text" value="${y(
    l.fallback || ""
  )}" placeholder="${y(o.fallbackPlaceholder)}" />
      </div>
      <div class="rte-data-binding-field">
        <label for="rte-data-binding-format">${y(o.formatLabel)}</label>
        <select id="rte-data-binding-format" class="rte-data-binding-format">
          <option value="text" ${l.format === "text" ? "selected" : ""}>Text</option>
          <option value="number" ${l.format === "number" ? "selected" : ""}>Number</option>
          <option value="currency" ${l.format === "currency" ? "selected" : ""}>Currency</option>
          <option value="date" ${l.format === "date" ? "selected" : ""}>Date</option>
          <option value="json" ${l.format === "json" ? "selected" : ""}>JSON</option>
        </select>
      </div>
      <div class="rte-data-binding-field">
        <label for="rte-data-binding-currency">${y(o.currencyLabel)}</label>
        <input id="rte-data-binding-currency" class="rte-data-binding-currency" type="text" maxlength="3" value="${y(
    l.currency || "USD"
  )}" placeholder="${y(o.currencyPlaceholder)}" />
      </div>
      <p class="rte-data-binding-help">Use dot paths like <code>user.name</code> or <code>order.total</code>.</p>
    </div>
    <footer class="rte-data-binding-footer">
      <button type="button" class="rte-data-binding-btn" data-action="cancel">${y(o.cancelText)}</button>
      <button type="button" class="rte-data-binding-btn rte-data-binding-btn-primary" data-action="save">${y(o.saveText)}</button>
    </footer>
  `, d.appendChild(c), document.body.appendChild(d);
  const u = c.querySelector(".rte-data-binding-key"), p = c.querySelector(".rte-data-binding-fallback"), m = c.querySelector(".rte-data-binding-format"), $ = c.querySelector(".rte-data-binding-currency"), B = () => {
    const s = m?.value === "currency", k = $?.closest(".rte-data-binding-field");
    k && (k.style.display = s ? "grid" : "none");
  };
  B(), m?.addEventListener("change", B);
  const L = () => {
    d.removeEventListener("click", nt), d.removeEventListener("keydown", rt, !0), document.removeEventListener("keydown", et, !0), d.parentNode && d.parentNode.removeChild(d), N = null, t.focus({ preventScroll: !0 });
  }, et = (s) => {
    s.key === "Escape" && (s.preventDefault(), s.stopPropagation(), L());
  }, nt = (s) => {
    s.target === d && L();
  }, mt = (s) => {
    if (s.key !== "Tab") return;
    const k = Array.from(
      c.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')
    );
    if (k.length === 0) return;
    const w = k[0], E = k[k.length - 1], F = document.activeElement;
    if (s.shiftKey && F === w) {
      s.preventDefault(), E.focus();
      return;
    }
    !s.shiftKey && F === E && (s.preventDefault(), w.focus());
  }, at = async () => {
    const s = (u?.value || "").trim();
    if (!s) {
      u?.focus();
      return;
    }
    const k = H(
      {
        key: s,
        fallback: (p?.value || "").trim(),
        format: m?.value || n.defaultFormat,
        currency: ($?.value || "USD").trim().toUpperCase()
      },
      n
    ), w = t.innerHTML;
    if (e) {
      X(e, k, o);
      const E = x.get(t) === !0, F = E ? await I(t, n) : void 0;
      T(e, n, E, F);
    } else {
      if (i)
        try {
          st(t, i);
        } catch {
        }
      const E = ut(k, o);
      if (bt(t, E), x.get(t) === !0) {
        const pt = await I(t, n);
        T(E, n, !0, pt);
      }
    }
    J(t), Y(t, w), L();
  }, rt = (s) => {
    if (s.key === "Escape") {
      s.preventDefault(), L();
      return;
    }
    mt(s), s.key === "Enter" && !s.shiftKey && s.target instanceof HTMLInputElement && (s.preventDefault(), at());
  };
  c.addEventListener("click", (s) => {
    const w = s.target?.getAttribute("data-action");
    if (w) {
      if (w === "cancel") {
        L();
        return;
      }
      w === "save" && at();
    }
  }), d.addEventListener("click", nt), d.addEventListener("keydown", rt, !0), document.addEventListener("keydown", et, !0), N = { cleanup: L }, u?.focus();
}
function $t(t) {
  z = t, O || (O = (n) => {
    const r = n.target?.closest(A);
    if (!r) return;
    h = r, b.has(r) || b.set(r, t);
    const e = b.get(r) || t;
    V(r, e);
    const i = x.get(r) === !0;
    tt(r, i, e), i || Array.from(r.querySelectorAll(C)).forEach((l) => T(l, e, !1));
  }, document.addEventListener("focusin", O, !0)), P || (P = (n) => {
    if (document.querySelector(`.${g}`)) return;
    const a = n.target;
    if (a?.closest("input, textarea, select")) return;
    const r = D(void 0, !1);
    if (!r || R(r)) return;
    const e = b.get(r) || z || t, i = a?.closest(C);
    if (i && (n.key === "Enter" || n.key === " ")) {
      n.preventDefault(), n.stopPropagation(), h = r, S(r, e, "edit", void 0, i);
      return;
    }
    if (St(n)) {
      n.preventDefault(), n.stopPropagation();
      const o = Q(r);
      o ? S(r, e, "edit", void 0, o) : S(r, e, "insert");
      return;
    }
    if (Tt(n)) {
      n.preventDefault(), n.stopPropagation();
      const o = x.get(r) !== !0;
      _(r, e, o);
    }
  }, document.addEventListener("keydown", P, !0)), M || (M = (n) => {
    if (document.querySelector(`.${g}`) || n.defaultPrevented || n.button !== 0 || n.metaKey || n.ctrlKey || n.altKey || n.shiftKey) return;
    const r = n.target?.closest(C);
    if (!r) return;
    const e = r.closest(A);
    if (!e || R(e)) return;
    const i = b.get(e) || z || t;
    b.set(e, i), h = e, n.preventDefault(), n.stopPropagation(), r.focus({ preventScroll: !0 }), S(e, i, "edit", void 0, r);
  }, document.addEventListener("click", M, !0));
}
function Lt() {
  O && (document.removeEventListener("focusin", O, !0), O = null), P && (document.removeEventListener("keydown", P, !0), P = null), M && (document.removeEventListener("click", M, !0), M = null), z = null, h = null;
}
const Ct = (t = {}) => {
  const n = ot(t);
  return vt(), {
    name: "dataBinding",
    toolbar: [
      {
        id: "dataBindingTools",
        label: "Data Binding",
        type: "group",
        command: "openDataBindingDialog",
        items: [
          {
            id: "dataBinding",
            label: "Data Binding",
            command: "openDataBindingDialog",
            icon: '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" focusable="false" aria-hidden="true"><path d="M7 4a3 3 0 0 0-3 3v3h2V7a1 1 0 0 1 1-1h3V4H7Zm10 0h-3v2h3a1 1 0 0 1 1 1v3h2V7a3 3 0 0 0-3-3ZM4 14v3a3 3 0 0 0 3 3h3v-2H7a1 1 0 0 1-1-1v-3H4Zm14 0v3a1 1 0 0 1-1 1h-3v2h3a3 3 0 0 0 3-3v-3h-2ZM8.5 12a1.5 1.5 0 1 1 0-3h7a1.5 1.5 0 0 1 0 3h-7Zm0 4a1.5 1.5 0 1 1 0-3h4a1.5 1.5 0 0 1 0 3h-4Z" fill="currentColor"></path></svg>'
          },
          {
            id: "dataBindingPreview",
            label: "Data Preview",
            command: "toggleDataBindingPreview",
            icon: '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" focusable="false" aria-hidden="true"><path d="M12 3c-4.4 0-8 1.3-8 3v12c0 1.7 3.6 3 8 3s8-1.3 8-3V6c0-1.7-3.6-3-8-3Zm0 2c3.9 0 6 .9 6 1s-2.1 1-6 1-6-.9-6-1 2.1-1 6-1Zm0 4c3 0 5.6-.5 7-1.3V11c0 .9-2.7 2-7 2s-7-1.1-7-2V7.7C6.4 8.5 9 9 12 9Zm0 6c-4.3 0-7-1.1-7-2v3c0 .9 2.7 2 7 2s7-1.1 7-2v-3c0 .9-2.7 2-7 2Z" fill="currentColor"></path><path d="M16.5 9.4a1 1 0 0 1 1.4 0l1.1 1.1 1.8-1.8a1 1 0 1 1 1.4 1.4l-2.5 2.5a1 1 0 0 1-1.4 0l-1.8-1.8a1 1 0 0 1 0-1.4Z" fill="currentColor"></path></svg>'
          }
        ]
      }
    ],
    commands: {
      openDataBindingDialog: (a, r) => {
        const e = D(r);
        if (!e || R(e)) return !1;
        h = e;
        const i = b.get(e) || n;
        b.set(e, i), V(e, i);
        const o = a?.target;
        if (o === "insert")
          return S(e, i, "insert", a), !0;
        const l = Q(e);
        return o === "edit" || l ? !l && o === "edit" ? !1 : (S(e, i, "edit", a, l || void 0), !0) : (S(e, i, "insert", a), !0);
      },
      insertDataBindingToken: async (a, r) => {
        const e = D(r);
        if (!e || R(e)) return !1;
        h = e;
        const i = b.get(e) || n;
        b.set(e, i);
        const o = H(a || {}, i);
        if (!o.key) return !1;
        const l = e.innerHTML, d = ut(o, i.labels);
        if (bt(e, d), x.get(e) === !0) {
          const u = await I(e, i);
          T(d, i, !0, u);
        }
        return J(e), Y(e, l), !0;
      },
      editDataBindingToken: async (a, r) => {
        const e = D(r);
        if (!e || R(e)) return !1;
        h = e;
        const i = b.get(e) || n;
        b.set(e, i);
        const o = Q(e);
        if (!o) return !1;
        const l = Z(o, i), d = H({ ...l, ...a || {} }, i);
        if (!d.key) return !1;
        const c = e.innerHTML;
        X(o, d, i.labels);
        const u = x.get(e) === !0, p = u ? await I(e, i) : void 0;
        return T(o, i, u, p), J(e), Y(e, c), !0;
      },
      toggleDataBindingPreview: async (a, r) => {
        const e = D(r);
        if (!e) return !1;
        h = e;
        const i = b.get(e) || n;
        b.set(e, i);
        const o = typeof a == "boolean" ? a : x.get(e) !== !0;
        return await _(e, i, o), !0;
      },
      setDataBindingData: async (a, r) => {
        const e = D(r);
        if (!e) return !1;
        if (h = e, a && typeof a == "object" ? (W.set(e, a), K.set(e, { timestamp: Date.now(), data: a })) : (W.delete(e), K.delete(e)), x.get(e) === !0) {
          const i = b.get(e) || n;
          await _(e, i, !0);
        }
        return !0;
      },
      refreshDataBindings: async (a, r) => {
        const e = D(r);
        if (!e) return !1;
        h = e, K.delete(e);
        const i = b.get(e) || n;
        b.set(e, i);
        const o = x.get(e) === !0;
        return await _(e, i, o), !0;
      }
    },
    keymap: {
      "Mod-Alt-Shift-d": "openDataBindingDialog",
      "Mod-Alt-Shift-D": "openDataBindingDialog",
      "Mod-Alt-Shift-b": "toggleDataBindingPreview",
      "Mod-Alt-Shift-B": "toggleDataBindingPreview",
      F7: "openDataBindingDialog",
      F8: "toggleDataBindingPreview"
    },
    init: function(r) {
      U += 1;
      const e = this && typeof this.__pluginConfig == "object" ? ot({ ...n, ...this.__pluginConfig }) : n;
      $t(e);
      const i = D(
        r && r.editorElement ? { editorElement: r.editorElement } : void 0,
        !1
      );
      if (i) {
        h = i, b.set(i, e), V(i, e);
        const o = x.get(i) === !0;
        tt(i, o, e);
      }
    },
    destroy: () => {
      U = Math.max(0, U - 1), U === 0 && (ft(), Lt());
    }
  };
};
export {
  Ct as DataBindingPlugin
};
