class w {
  constructor() {
    this.loadedPlugins = /* @__PURE__ */ new Map(), this.pluginRegistry = /* @__PURE__ */ new Map();
  }
  /**
   * Register a plugin factory (sync or async)
   */
  register(t, e) {
    this.pluginRegistry.set(t, e);
  }
  /**
   * Load a plugin by name (async)
   */
  async load(t, e) {
    if (this.loadedPlugins.has(t))
      return this.loadedPlugins.get(t);
    const o = this.pluginRegistry.get(t);
    if (!o)
      return console.warn(`Plugin not found: ${t}`), null;
    const r = await o();
    return e && this.applyPluginConfig(r, e), this.loadedPlugins.set(t, r), r;
  }
  /**
   * Load multiple plugins
   */
  async loadMultiple(t, e) {
    return (await Promise.all(
      t.map((r) => this.load(r, e))
    )).filter((r) => r !== null);
  }
  /**
   * Parse plugin string "lists link image media"
   */
  async parsePluginString(t, e) {
    const o = t.split(/\s+/).filter(Boolean);
    return this.loadMultiple(o, e);
  }
  /**
   * Apply configuration to plugin
   */
  applyPluginConfig(t, e) {
    t.__pluginConfig = e;
  }
  /**
   * Unload a plugin
   */
  unload(t) {
    this.loadedPlugins.delete(t);
  }
  /**
   * Clear all loaded plugins
   */
  clear() {
    this.loadedPlugins.clear();
  }
  /**
   * Get all loaded plugins
   */
  getLoadedPlugins() {
    return Array.from(this.loadedPlugins.values());
  }
  /**
   * Get all registered plugin names (available for loading)
   */
  getRegisteredPluginNames() {
    return Array.from(this.pluginRegistry.keys());
  }
  /**
   * Check if plugin is loaded
   */
  isLoaded(t) {
    return this.loadedPlugins.has(t);
  }
}
class m {
  constructor(t, e, o) {
    this.doc = t, this.selection = e, this.schema = o;
  }
  static create(t, e) {
    const o = e || t.node("doc", {}, [t.node("paragraph")]);
    return new m(o, { anchor: 0, head: 0 }, t);
  }
  apply(t, e) {
    return new m(t, e || this.selection, this.schema);
  }
}
class C {
  constructor(t, e) {
    this.nodes = new Map(Object.entries(t)), this.marks = new Map(Object.entries(e));
  }
  node(t, e, o) {
    return { type: t, attrs: e, content: o };
  }
  text(t, e) {
    return { type: "text", text: t, marks: e };
  }
}
class k {
  constructor() {
    this.plugins = [], this.pluginConfigs = /* @__PURE__ */ new Map();
  }
  register(t, e) {
    if (this.plugins.push(t), e && this.pluginConfigs.set(t.name, e), t.initialize) {
      const o = this.pluginConfigs.get(t.name) || t.config;
      t.initialize(o);
    }
  }
  unregister(t) {
    const e = this.plugins.findIndex((o) => o.name === t);
    if (e > -1) {
      const o = this.plugins[e];
      o.destroy && o.destroy(), this.plugins.splice(e, 1), this.pluginConfigs.delete(t);
    }
  }
  getPlugin(t) {
    return this.plugins.find((e) => e.name === t);
  }
  getPluginConfig(t) {
    return this.pluginConfigs.get(t);
  }
  buildSchema() {
    const t = {}, e = {};
    return this.plugins.forEach((o) => {
      o.nodes && Object.assign(t, o.nodes), o.marks && Object.assign(e, o.marks);
    }), new C(t, e);
  }
  getCommands() {
    const t = {};
    return this.plugins.forEach((e) => {
      e.commands && Object.assign(t, e.commands);
    }), t;
  }
  getToolbarItems() {
    return this.plugins.flatMap((t) => t.toolbar || []);
  }
  /**
   * Execute plugin command with mode awareness
   */
  async executePluginCommand(t, e, ...o) {
    const r = this.getPlugin(t);
    if (!r)
      throw new Error(`Plugin not found: ${t}`);
    const i = this.getPluginConfig(t) || r.config || {}, a = i.mode || "local";
    try {
      switch (a) {
        case "local":
          return r.executeLocal ? r.executeLocal(e, ...o) : null;
        case "api":
          if (!r.executeAPI)
            throw new Error(`Plugin ${t} does not support API mode`);
          return await r.executeAPI(e, ...o);
        case "hybrid":
          if (r.executeHybrid)
            return await r.executeHybrid(e, ...o);
          try {
            if (r.executeAPI)
              return await r.executeAPI(e, ...o);
          } catch (s) {
            if (console.warn(`API execution failed for ${t}, falling back to local`, s), r.executeLocal && i.fallbackToLocal !== !1)
              return r.executeLocal(e, ...o);
            throw s;
          }
          break;
        default:
          throw new Error(`Unknown plugin mode: ${a}`);
      }
    } catch (s) {
      throw console.error(`Error executing command ${e} on plugin ${t}:`, s), s;
    }
  }
  /**
   * Destroy all plugins
   */
  async destroyAll() {
    const t = this.plugins.filter((e) => e.destroy).map((e) => e.destroy());
    await Promise.all(t), this.plugins = [], this.pluginConfigs.clear();
  }
}
class E {
  constructor(t = {}) {
    this.commands = /* @__PURE__ */ new Map(), Object.entries(t).forEach(([e, o]) => {
      this.register(e, o);
    });
  }
  /**
   * Register a command
   */
  register(t, e) {
    this.commands.has(t) && console.warn(`Command ${t} is being overwritten`), this.commands.set(t, e);
  }
  /**
   * Unregister a command
   */
  unregister(t) {
    this.commands.delete(t);
  }
  /**
   * Get a command handler
   */
  get(t) {
    return this.commands.get(t);
  }
  /**
   * Check if command exists
   */
  has(t) {
    return this.commands.has(t);
  }
  /**
   * Get all command names
   */
  getCommandNames() {
    return Array.from(this.commands.keys());
  }
  /**
   * Clear all commands
   */
  clear() {
    this.commands.clear();
  }
}
class v {
  constructor(t = {}) {
    this.listeners = /* @__PURE__ */ new Map(), this.isReadonly = !1, this.isDestroyed = !1, this.isReadonly = t.readonly || !1, this.pluginManager = new k(), t.plugins && Array.isArray(t.plugins) && t.plugins.forEach((o) => this.pluginManager.register(o));
    const e = this.pluginManager.buildSchema();
    this.state = m.create(e), this.commandRegistry = new E(this.pluginManager.getCommands());
  }
  /**
   * Execute a command
   */
  execCommand(t, e) {
    if (this.isReadonly)
      return console.warn("Cannot execute commands in readonly mode"), !1;
    if (this.isDestroyed)
      return console.warn("Cannot execute commands on destroyed editor"), !1;
    const o = this.commandRegistry.get(t);
    if (!o)
      return console.warn(`Command not found: ${t}`), !1;
    let r;
    return e !== void 0 ? r = o(this.state, e) : r = o(this.state), r ? (this.setState(r), this.emit("change", this.state), !0) : !1;
  }
  /**
   * Update editor state
   */
  setState(t) {
    this.isDestroyed || (this.state = t, this.emit("stateChange", t));
  }
  /**
   * Get current state
   */
  getState() {
    return this.state;
  }
  /**
   * Set readonly mode
   */
  setReadonly(t) {
    this.isReadonly = t, this.emit("readonlyChange", t);
  }
  /**
   * Check if readonly
   */
  isReadOnly() {
    return this.isReadonly;
  }
  /**
   * Event emitter
   */
  on(t, e) {
    return this.listeners.has(t) || this.listeners.set(t, []), this.listeners.get(t).push(e), () => {
      const o = this.listeners.get(t);
      if (o) {
        const r = o.indexOf(e);
        r > -1 && o.splice(r, 1);
      }
    };
  }
  /**
   * Emit event
   */
  emit(t, ...e) {
    const o = this.listeners.get(t);
    o && o.forEach((r) => {
      try {
        r(...e);
      } catch (i) {
        console.error(`Error in ${t} handler:`, i);
      }
    });
  }
  /**
   * Destroy editor instance
   */
  destroy() {
    this.isDestroyed || (this.isDestroyed = !0, this.listeners.clear(), this.emit("destroy"));
  }
  /**
   * Check if destroyed
   */
  isEditorDestroyed() {
    return this.isDestroyed;
  }
}
class L {
  // PluginLoader instance to get all registered plugins
  constructor(t, e, o) {
    this.config = t, this.plugins = e, this.pluginLoader = o;
  }
  /**
   * Set command handler for toolbar buttons
   */
  setCommandHandler(t) {
    this.commandHandler = t;
  }
  /**
   * Parse toolbar string into button groups
   */
  parseToolbarString(t) {
    const e = [], o = t.split("|").map((s) => s.trim()), r = this.getAvailableToolbarItems(), i = /* @__PURE__ */ new Map();
    r.forEach((s) => {
      s.command && i.set(s.command, s), s.type === "group" && s.label && i.set(s.label, s);
    });
    const a = {
      bold: "toggleBold",
      italic: "toggleItalic",
      underline: "toggleUnderline",
      strikethrough: "toggleStrikethrough",
      bullist: "toggleBulletList",
      numlist: "toggleOrderedList",
      checklist: "toggleChecklist",
      link: "openLinkDialog",
      image: "openImageDialog",
      table: "insertTable",
      anchor: "insertAnchor",
      code: "toggleSourceView",
      blockquote: "toggleBlockquote",
      undo: "undo",
      redo: "redo",
      textColor: "openTextColorPicker",
      backgroundColor: "openBackgroundColorPicker",
      fontSize: "fontSize",
      fontFamily: "setFontFamily",
      lineHeight: "setLineHeight",
      heading: "setBlockType",
      paragraph: "setParagraph",
      textAlignment: "setTextAlignment",
      direction: "setDirectionLTR",
      indent: "increaseIndent",
      outdent: "decreaseIndent",
      capitalization: "setCapitalization",
      math: "insertMath",
      specialCharacters: "insertSpecialCharacter",
      emojis: "openEmojiDialog",
      embedIframe: "openEmbedIframeDialog",
      fullscreen: "toggleFullscreen",
      preview: "togglePreview",
      print: "print",
      a11yChecker: "toggleA11yChecker",
      spellCheck: "toggleSpellCheck",
      comments: "addComment",
      showHideComments: "toggleComments",
      toggleComments: "toggleComments",
      footnote: "insertFootnote",
      mergeTags: "insertMergeTag",
      pageBreak: "insertPageBreak",
      template: "insertTemplate",
      importWord: "importWord",
      exportWord: "exportWord",
      exportPdf: "exportPdf",
      insertImage: "insertImage",
      insertVideo: "insertVideo",
      codeBlock: "insertCodeBlock"
    };
    return o.forEach((s) => {
      const l = [];
      s.split(/\s+/).filter(Boolean).forEach((g) => {
        if (g === "direction") {
          const c = i.get("setDirectionLTR"), h = i.get("setDirectionRTL");
          c && l.push({
            id: "directionLTR",
            label: c.label,
            command: c.command,
            icon: c.icon,
            type: c.type || "button",
            options: c.options
          }), h && l.push({
            id: "directionRTL",
            label: h.label,
            command: h.command,
            icon: h.icon,
            type: h.type || "button",
            options: h.options
          });
          return;
        }
        if (g === "comments") {
          const c = i.get("addComment"), h = i.get("toggleComments");
          c && l.push({
            id: "addComment",
            label: c.label,
            command: c.command,
            icon: c.icon,
            type: c.type || "button",
            options: c.options
          }), h && l.push({
            id: "toggleComments",
            label: h.label,
            command: h.command,
            icon: h.icon,
            type: h.type || "button",
            options: h.options
          });
          return;
        }
        const p = a[g] || g;
        let d = i.get(p);
        d || (d = i.get(g)), d && l.push({
          id: g,
          label: d.label,
          command: d.command,
          icon: d.icon,
          type: d.type === "separator" ? "separator" : d.type || "button",
          options: d.options,
          items: d.items
        });
      }), l.length > 0 && e.push(l);
    }), e;
  }
  /**
   * Get all available toolbar items from plugins
   */
  getAvailableToolbarItems() {
    return this.plugins.flatMap((e) => e.toolbar || []);
  }
  /**
   * Render toolbar to DOM element
   */
  render(t) {
    this.container = t, t.innerHTML = "", t.className = "editora-toolbar", this.config.sticky && t.classList.add("editora-toolbar-sticky"), this.config.position && t.classList.add(`editora-toolbar-${this.config.position}`);
    const e = this.config.items || this.getDefaultToolbarString(), o = this.parseToolbarString(e);
    o.forEach((r, i) => {
      const a = document.createElement("div");
      if (a.className = "editora-toolbar-group", r.forEach((s) => {
        this.appendToolbarButton(a, s);
      }), t.appendChild(a), i < o.length - 1) {
        const s = document.createElement("div");
        s.className = "editora-toolbar-separator", t.appendChild(s);
      }
    });
  }
  /**
   * Append a toolbar button or group to a parent element
   */
  appendToolbarButton(t, e) {
    if (e.type === "separator") {
      const o = document.createElement("div");
      o.className = "editora-toolbar-separator", t.appendChild(o);
    } else if (e.type === "dropdown") {
      const o = this.createDropdown(e);
      t.appendChild(o);
    } else if (e.type === "inline-menu") {
      const o = this.createInlineMenu(e);
      t.appendChild(o);
    } else if (e.type === "group" && e.items && e.items.length) {
      const o = this.createGroupButton(e);
      t.appendChild(o);
    } else if (e.type === "input") {
      const o = this.createInput(e);
      t.appendChild(o);
    } else {
      const o = this.createButton(e);
      t.appendChild(o);
    }
  }
  /**
   * Create a toolbar button element
   */
  createGroupButton(t) {
    const e = document.createElement("div");
    if (e.className = "editora-toolbar-group-button", e.title = t.label, t.icon)
      if (t.icon.startsWith("<svg") && t.icon.endsWith("</svg>")) {
        const o = document.createElement("span");
        o.className = "editora-toolbar-icon", o.innerHTML = t.icon, e.appendChild(o);
      } else
        e.innerHTML = t.icon;
    if (t.items && t.items.length) {
      const o = document.createElement("div");
      o.className = "editora-toolbar-group-items", t.items.forEach((r) => {
        this.appendToolbarButton(o, r);
      }), e.appendChild(o);
    }
    return e;
  }
  /**
   * Create a toolbar button element
   */
  createInput(t) {
    const e = document.createElement("input");
    return e.className = `editora-toolbar-input ${t.label.toLowerCase().replace(/\s+/g, "-")}`, e.type = "text", e.title = t.label, e.placeholder = t.placeholder || "", e.setAttribute("data-command", t.command), t.active && e.classList.add("active"), t.disabled && (e.disabled = !0), e.addEventListener("click", (o) => {
      o.preventDefault(), this.commandHandler && this.commandHandler(t.command);
    }), e;
  }
  /**
   * Create a toolbar button element
   */
  createButton(t) {
    const e = document.createElement("button");
    if (e.className = "editora-toolbar-button", e.type = "button", e.title = t.label, e.setAttribute("data-command", t.command), t.icon)
      if (t.icon.startsWith("<svg") && t.icon.endsWith("</svg>")) {
        const o = document.createElement("span");
        o.className = "editora-toolbar-icon", o.innerHTML = t.icon, e.appendChild(o);
      } else
        e.innerHTML = t.icon;
    else
      e.textContent = t.label;
    return t.active && e.classList.add("active"), t.disabled && (e.disabled = !0), e.addEventListener("click", (o) => {
      o.preventDefault(), this.commandHandler && this.commandHandler(t.command);
    }), e;
  }
  /**
   * Create a dropdown element
   */
  createDropdown(t) {
    const e = document.createElement("div");
    e.className = "editora-toolbar-dropdown";
    const o = document.createElement("button");
    o.className = "editora-toolbar-button editora-toolbar-dropdown-trigger", o.type = "button", o.textContent = t.label;
    const r = document.createElement("div");
    r.className = "editora-toolbar-dropdown-menu", r.style.display = "none", t.options && t.options.forEach((a) => {
      const s = document.createElement("button");
      s.className = "editora-toolbar-dropdown-item", s.type = "button", s.textContent = a.label, s.setAttribute("data-value", a.value), s.addEventListener("click", (l) => {
        l.preventDefault(), this.commandHandler && this.commandHandler(t.command, a.value), r.style.display = "none";
      }), r.appendChild(s);
    }), o.addEventListener("click", (a) => {
      a.preventDefault(), a.stopPropagation();
      const s = r.style.display === "block";
      r.style.display = s ? "none" : "block";
    });
    const i = (a) => {
      e.contains(a.target) || (r.style.display = "none");
    };
    return document.addEventListener("click", i), e._cleanupDropdown = () => {
      document.removeEventListener("click", i);
    }, e.appendChild(o), e.appendChild(r), e;
  }
  /**
   * Create an inline menu element (like dropdown but triggered by button click)
   */
  createInlineMenu(t) {
    const e = document.createElement("div");
    e.className = "editora-toolbar-dropdown editora-toolbar-inline-menu";
    const o = document.createElement("button");
    if (o.className = "editora-toolbar-button", o.type = "button", o.title = t.label, t.icon)
      if (t.icon.startsWith("<svg") && t.icon.endsWith("</svg>")) {
        const i = document.createElement("span");
        i.className = "editora-toolbar-icon", i.innerHTML = t.icon, o.appendChild(i);
      } else
        o.innerHTML = t.icon;
    else
      o.textContent = t.label;
    const r = document.createElement("div");
    return r.className = "editora-toolbar-dropdown-menu", r.style.display = "none", t.options && t.options.forEach((i) => {
      const a = document.createElement("button");
      a.className = "editora-toolbar-dropdown-item", a.type = "button", a.textContent = i.label, a.setAttribute("data-value", i.value), a.addEventListener("click", (s) => {
        s.preventDefault(), s.stopPropagation(), this.commandHandler && this.commandHandler(t.command, i.value), r.style.display = "none";
      }), r.appendChild(a);
    }), o.addEventListener("click", (i) => {
      var s;
      i.preventDefault(), i.stopPropagation();
      const a = (s = this.container) == null ? void 0 : s.querySelectorAll(
        ".editora-toolbar-dropdown-menu"
      );
      a == null || a.forEach((l) => {
        l !== r && (l.style.display = "none");
      }), r.style.display = r.style.display === "none" ? "block" : "none";
    }), document.addEventListener("click", (i) => {
      e.contains(i.target) || (r.style.display = "none");
    }), e.appendChild(o), e.appendChild(r), e;
  }
  /**
   * Get default toolbar string if none provided
   */
  getDefaultToolbarString() {
    return this.getAvailableToolbarItems().map((e) => e.command).join(" ");
  }
  /**
   * Update button state
   */
  updateButtonState(t, e) {
    if (!this.container) return;
    const o = this.container.querySelector(
      `[data-command="${t}"]`
    );
    o && (e.active !== void 0 && o.classList.toggle("active", e.active), e.disabled !== void 0 && (o.disabled = e.disabled));
  }
  /**
   * Destroy toolbar
   */
  destroy() {
    this.container && (this.container.querySelectorAll(".editora-toolbar-dropdown").forEach((e) => {
      const o = e._cleanupDropdown;
      o && o();
    }), this.container.innerHTML = ""), this.commandHandler = void 0;
  }
}
class P {
  constructor(t) {
    this.visible = !1, this.config = t;
  }
  /**
   * Create and mount floating toolbar
   */
  create(t) {
    const e = document.createElement("div");
    return e.className = "editora-floating-toolbar", e.style.display = "none", e.style.position = "absolute", e.style.zIndex = "1000", this.container = e, t.appendChild(e), e;
  }
  /**
   * Show toolbar at position
   */
  show(t, e) {
    this.container && (this.container.style.display = "block", this.container.style.left = `${t}px`, this.container.style.top = `${e}px`, this.visible = !0);
  }
  /**
   * Hide toolbar
   */
  hide() {
    this.container && (this.container.style.display = "none", this.visible = !1);
  }
  /**
   * Update position
   */
  updatePosition(t, e) {
    !this.container || !this.visible || (this.container.style.left = `${t}px`, this.container.style.top = `${e}px`);
  }
  /**
   * Check if visible
   */
  isVisible() {
    return this.visible;
  }
  /**
   * Destroy floating toolbar
   */
  destroy() {
    this.container && this.container.parentNode && this.container.parentNode.removeChild(this.container), this.container = void 0, this.visible = !1;
  }
}
class T {
  constructor(t = {}) {
    this.statusInfo = {}, this.config = t;
  }
  /**
   * Create and mount status bar
   */
  create(t) {
    const e = document.createElement("div");
    return e.className = "editora-statusbar", this.config.position && e.classList.add(`editora-statusbar-${this.config.position}`), this.container = e, t.appendChild(e), e;
  }
  /**
   * Update status information
   */
  update(t) {
    this.statusInfo = { ...this.statusInfo, ...t }, this.render();
  }
  /**
   * Render status bar content
   */
  render() {
    if (!this.container) return;
    this.container.innerHTML = "";
    const t = document.createElement("div");
    t.className = "editora-statusbar-left";
    const e = document.createElement("div");
    e.className = "editora-statusbar-right";
    const o = [];
    if (this.statusInfo.selectionInfo) {
      const i = this.statusInfo.selectionInfo;
      i.startLine === i.endLine && i.startColumn === i.endColumn ? o.push(`Ln ${i.startLine}, Col ${i.startColumn}`) : (i.startLine === i.endLine ? o.push(`Ln ${i.startLine}, Col ${i.startColumn}-${i.endColumn}`) : o.push(`Ln ${i.startLine}:${i.startColumn} - ${i.endLine}:${i.endColumn}`), o.push(`${i.selectedChars} chars selected`));
    } else if (this.statusInfo.cursorPosition) {
      const i = this.statusInfo.cursorPosition;
      o.push(`Ln ${i.line}, Col ${i.column}`);
    }
    this.statusInfo.language && o.push(this.statusInfo.language);
    const r = [];
    this.statusInfo.wordCount !== void 0 && r.push(`${this.statusInfo.wordCount} words`), this.statusInfo.charCount !== void 0 && r.push(`${this.statusInfo.charCount} chars`), this.statusInfo.lineCount !== void 0 && r.push(`${this.statusInfo.lineCount} lines`), this.statusInfo.custom && Object.entries(this.statusInfo.custom).forEach(([i, a]) => {
      r.push(`${i}: ${a}`);
    }), o.forEach((i, a) => {
      const s = document.createElement("span");
      if (s.className = "editora-statusbar-item", s.textContent = i, t.appendChild(s), a < o.length - 1) {
        const l = document.createElement("span");
        l.className = "editora-statusbar-separator", l.textContent = "|", t.appendChild(l);
      }
    }), r.forEach((i, a) => {
      const s = document.createElement("span");
      if (s.className = "editora-statusbar-item", s.textContent = i, e.appendChild(s), a < r.length - 1) {
        const l = document.createElement("span");
        l.className = "editora-statusbar-separator", l.textContent = "|", e.appendChild(l);
      }
    }), this.container.appendChild(t), this.container.appendChild(e);
  }
  /**
   * Destroy status bar
   */
  destroy() {
    this.container && this.container.parentNode && this.container.parentNode.removeChild(this.container), this.container = void 0;
  }
}
function I(n, t) {
  const e = n.textContent || "", o = A(n, t.startContainer, t.startOffset), i = e.substring(0, o).split(`
`), a = i.length, s = i[i.length - 1].length + 1;
  return { line: a, column: s };
}
function A(n, t, e) {
  var a;
  let o = 0;
  const r = document.createTreeWalker(
    n,
    NodeFilter.SHOW_TEXT,
    null
  );
  let i = r.firstChild();
  for (; i; ) {
    if (i === t) {
      o += e;
      break;
    } else i.nodeType === Node.TEXT_NODE && (o += ((a = i.textContent) == null ? void 0 : a.length) || 0);
    i = r.nextNode();
  }
  return o;
}
function S(n) {
  var o, r;
  const t = n.querySelectorAll("div, p, br, h1, h2, h3, h4, h5, h6, blockquote, li, pre");
  let e = 1;
  if (t.length > 0) {
    e = t.length;
    const i = t[t.length - 1];
    (i.tagName === "BR" || ((o = i.innerHTML) == null ? void 0 : o.trim()) === "" || ((r = i.textContent) == null ? void 0 : r.trim()) === "") && e++;
  } else {
    const a = (n.textContent || "").split(`
`).length;
    e = Math.max(1, a);
  }
  return e;
}
function M(n) {
  const t = n.trim() ? n.trim().split(/\s+/).length : 0, e = n.length;
  return { words: t, chars: e };
}
function N(n, t) {
  const e = n.toString();
  return {
    startLine: t.line,
    startColumn: t.column,
    endLine: t.line,
    // For now, assuming single line selections
    endColumn: t.column + e.length,
    selectedChars: e.length,
    selectedWords: e.trim().split(/\s+/).filter(Boolean).length
  };
}
const y = class y {
  /**
   * Resolve configuration from multiple sources with priority
   */
  static resolve(t) {
    const e = {};
    if (Object.assign(e, this.EDITOR_DEFAULTS), t.pluginDefaults && Object.assign(e, t.pluginDefaults), t.attributes) {
      const o = this.parseAttributes(t.attributes);
      Object.assign(e, o);
    }
    return t.jsConfig && Object.assign(e, t.jsConfig), e;
  }
  /**
   * Parse web component attributes
   */
  static parseAttributes(t) {
    const e = {};
    for (const [o, r] of Object.entries(t)) {
      const i = this.kebabToCamel(o);
      e[i] = this.parseAttributeValue(r);
    }
    return e;
  }
  /**
   * Parse attribute value to appropriate type
   */
  static parseAttributeValue(t) {
    if (t === "true") return !0;
    if (t === "false") return !1;
    if (/^\d+$/.test(t)) return parseInt(t, 10);
    if (/^\d+\.\d+$/.test(t)) return parseFloat(t);
    if (t.startsWith("{") || t.startsWith("["))
      try {
        return JSON.parse(t);
      } catch (e) {
        return t;
      }
    return t;
  }
  /**
   * Convert kebab-case to camelCase
   */
  static kebabToCamel(t) {
    return t.replace(/-([a-z])/g, (e, o) => o.toUpperCase());
  }
  /**
   * Validate configuration
   */
  static validate(t) {
    const e = [];
    return t.height !== void 0 && typeof t.height == "number" && t.height < 0 && e.push("height must be a positive number"), t.width !== void 0 && typeof t.width == "number" && t.width < 0 && e.push("width must be a positive number"), t.plugins !== void 0 && !Array.isArray(t.plugins) && typeof t.plugins != "string" && e.push("plugins must be an array or string"), t.theme !== void 0 && typeof t.theme != "string" && e.push("theme must be a string"), {
      valid: e.length === 0,
      errors: e
    };
  }
  /**
   * Get default configuration
   */
  static getDefaults() {
    return { ...this.EDITOR_DEFAULTS };
  }
  /**
   * Merge configurations (deep merge)
   */
  static merge(...t) {
    const e = {};
    for (const o of t)
      for (const [r, i] of Object.entries(o))
        i != null && (typeof i == "object" && !Array.isArray(i) && e[r] ? e[r] = this.merge(e[r], i) : e[r] = i);
    return e;
  }
};
y.EDITOR_DEFAULTS = {
  height: 400,
  width: "100%",
  readonly: !1,
  disabled: !1,
  menubar: !0,
  toolbar: !0,
  plugins: [],
  theme: "light",
  content: "",
  placeholder: "Start typing...",
  autofocus: !1,
  autosave: !1,
  spellcheck: !1,
  language: "en"
};
let x = y;
const H = '.editora-editor{display:flex;flex-direction:column;border:1px solid #ddd;border-radius:4px;background:#fff;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;font-size:14px;overflow:hidden}.editora-editor *{box-sizing:border-box}.editora-theme-light{background:#fff;color:#333}.editora-theme-dark{background:#1e1e1e;color:#d4d4d4;border-color:#3c3c3c}.editora-toolbar{display:flex;align-items:center;gap:4px;padding:8px;background:#f5f5f5;border-bottom:1px solid #ddd;flex-wrap:wrap}.editora-theme-dark .editora-toolbar{background:#252526;border-bottom-color:#3c3c3c}.editora-toolbar-sticky{position:sticky;top:0;z-index:100;position:-webkit-sticky}.editora-toolbar-group{display:flex;align-items:center;gap:2px}.editora-toolbar-button{padding:6px 12px;border:1px solid #ccc;background:#fff;cursor:pointer;border-radius:3px;font-weight:600;font-size:14px;height:30px;display:flex;align-items:center;white-space:nowrap}.editora-toolbar-input.font-size{width:40px;padding:.25rem;text-align:center;font-size:14px;background:#fff;border:1px solid var(--rte-color-border-light);border-radius:var(--rte-radius-sm)}.editora-toolbar-group-items{display:flex;align-items:center;border:1px solid #ccc;.editora-toolbar-button{border:none;border-radius:0;&:first-child{border-right:1px solid #ccc;border-top-left-radius:3px;border-bottom-left-radius:3px}&:last-child{border-left:1px solid #ccc;border-top-right-radius:3px;border-bottom-right-radius:3px}}}.editora-theme-dark .editora-toolbar-button{color:#d4d4d4}.editora-toolbar-button:hover{background:#e0e0e0;border-color:#ccc}.editora-theme-dark .editora-toolbar-button:hover{background:#37373d;border-color:#555}.editora-toolbar-button:active,.editora-toolbar-button.active{background:#d0d0d0;border-color:#999}.editora-theme-dark .editora-toolbar-button:active,.editora-theme-dark .editora-toolbar-button.active{background:#2a2d2e;border-color:#666}.editora-toolbar-button:disabled{opacity:.5;cursor:not-allowed}.editora-toolbar-icon{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;line-height:1}.editora-toolbar-button svg,.editora-toolbar-icon svg{width:24px;height:24px;display:block}.editora-toolbar-separator{width:1px;height:24px;background:#ddd;margin:0 4px}.editora-theme-dark .editora-toolbar-separator{background:#3c3c3c}.editora-toolbar-dropdown{position:relative}.editora-toolbar-dropdown-menu{position:absolute;top:100%;left:0;min-width:150px;margin-top:4px;padding:4px 0;background:#fff;border:1px solid #ddd;border-radius:4px;box-shadow:0 2px 8px #00000026;z-index:1000}.editora-theme-dark .editora-toolbar-dropdown-menu{background:#252526;border-color:#3c3c3c;box-shadow:0 2px 8px #00000080}.editora-toolbar-dropdown-item{display:block;width:100%;padding:8px 12px;border:none;background:transparent;color:#333;text-align:left;cursor:pointer;font-size:13px;transition:background .15s ease}.editora-theme-dark .editora-toolbar-dropdown-item{color:#d4d4d4}.editora-toolbar-dropdown-item:hover{background:#f5f5f5}.editora-theme-dark .editora-toolbar-dropdown-item:hover{background:#37373d}.editora-content{flex:1;min-height:200px;padding:16px;outline:none;overflow-y:auto;line-height:1.6}.editora-content:empty:before{content:attr(data-placeholder);color:#999;pointer-events:none}.editora-theme-dark .editora-content:empty:before{color:#6a6a6a}.editora-content h1{font-size:2em;margin:.67em 0;font-weight:600}.editora-content h2{font-size:1.5em;margin:.75em 0;font-weight:600}.editora-content h3{font-size:1.17em;margin:.83em 0;font-weight:600}.editora-content p{margin:1em 0}.editora-content ul,.editora-content ol{margin:1em 0;padding-left:2em}.editora-content a{color:#06c;text-decoration:underline}.editora-theme-dark .editora-content a{color:#4db8ff}.editora-content code{padding:2px 4px;background:#f5f5f5;border-radius:3px;font-family:Monaco,Menlo,Consolas,monospace;font-size:.9em}.editora-theme-dark .editora-content code{background:#1e1e1e}.editora-content pre{padding:12px;background:#f5f5f5;border-radius:4px;overflow-x:auto;margin:1em 0}.editora-theme-dark .editora-content pre{background:#1e1e1e}.editora-content blockquote{margin:1em 0;padding-left:1em;border-left:4px solid #ddd;color:#666}.editora-theme-dark .editora-content blockquote{border-left-color:#3c3c3c;color:#9a9a9a}.editora-floating-toolbar{position:absolute;padding:4px;background:#fff;border:1px solid #ddd;border-radius:4px;box-shadow:0 2px 8px #00000026;z-index:1000}.editora-theme-dark .editora-floating-toolbar{background:#252526;border-color:#3c3c3c;box-shadow:0 2px 8px #00000080}.editora-statusbar-container{display:flex;flex-direction:column}.editora-statusbar-left{display:flex;align-items:center;gap:8px}.editora-statusbar-right{display:flex;align-items:center;gap:8px;margin-left:auto}.editora-statusbar{display:flex;align-items:center;gap:12px;padding:6px 12px;background:#f5f5f5;border-top:1px solid #ddd;font-size:12px;color:#666}.editora-theme-dark .editora-statusbar{background:#252526;border-top-color:#3c3c3c;color:#9a9a9a}.editora-statusbar-item{white-space:nowrap}.editora-statusbar-separator{color:#ddd}.editora-theme-dark .editora-statusbar-separator{color:#3c3c3c}.editora-editor[readonly] .editora-content{background:#fafafa;cursor:not-allowed}.editora-theme-dark.editora-editor[readonly] .editora-content{background:#1a1a1a}.editora-editor:focus-within{border-color:#06c;box-shadow:0 0 0 3px #0066cc1a}.editora-theme-dark.editora-editor:focus-within{border-color:#4db8ff;box-shadow:0 0 0 3px #4db8ff1a}.editora-editor[disabled]{opacity:.6;pointer-events:none}@media(max-width:768px){.editora-toolbar{padding:4px}.editora-toolbar-button{min-width:28px;min-height:28px;padding:4px 8px;font-size:12px}.editora-content{padding:12px}}.editora-content ::selection{background:#06c3}.editora-theme-dark .editora-content ::selection{background:#4db8ff33}.editora-content table{border-collapse:collapse;width:100%;margin:1em 0}.editora-content th,.editora-content td{border:1px solid #ddd;padding:8px 12px;text-align:left}.editora-theme-dark .editora-content th,.editora-theme-dark .editora-content td{border-color:#3c3c3c}.editora-content th{background:#f5f5f5;font-weight:600}.editora-theme-dark .editora-content th{background:#252526}.editora-content img{max-width:100%;height:auto;border-radius:4px;display:block}.editora-content video{max-width:100%;height:auto;border-radius:4px;display:block}.editora-editor.loading{opacity:.7;pointer-events:none}.editora-editor.loading:after{content:"";position:absolute;top:50%;left:50%;width:24px;height:24px;margin:-12px 0 0 -12px;border:3px solid #ddd;border-top-color:#06c;border-radius:50%;animation:editora-spin .8s linear infinite}@keyframes editora-spin{to{transform:rotate(360deg)}}.toolbar-container-wrapper{display:flex;align-items:center;background:#fff;border-bottom:1px solid #e0e0e0;padding:0;margin:0;width:100%;box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;font-size:14px;line-height:1.5;position:relative}.toolbar-container-wrapper[data-toolbar-sticky=true]{position:sticky;top:0;z-index:999;box-shadow:0 2px 4px #0000001a}.toolbar-container-wrapper[data-toolbar-floating=true]{position:fixed;top:0;left:0;right:0;z-index:1000;box-shadow:0 4px 12px #00000026}.toolbar-container-wrapper[data-toolbar-position=bottom]{border-bottom:none;border-top:1px solid #e0e0e0}.toolbar-container-wrapper .toolbar-wrapper{display:flex;width:100%;padding:8px;gap:4px;flex-wrap:wrap;align-items:center}.toolbar-container-wrapper .toolbar{display:flex;width:100%;gap:4px;flex-wrap:wrap;align-items:center}.toolbar-container-wrapper .toolbar-container{display:flex;gap:4px;flex-wrap:wrap;align-items:center;flex:1;position:relative}.toolbar-container-wrapper .toolbar-item{display:flex;align-items:center;gap:2px}.toolbar-container-wrapper .toolbar-button{padding:6px 10px;border:1px solid #d1d5db;background:#fff;border-radius:4px;cursor:pointer;font-size:13px;display:flex;align-items:center;justify-content:center;gap:4px;transition:all .15s ease;min-height:32px;white-space:nowrap}.toolbar-container-wrapper .toolbar-button:hover{background-color:#f3f4f6;border-color:#9ca3af}.toolbar-container-wrapper .toolbar-button:active,.toolbar-container-wrapper .toolbar-button[data-active=true]{background-color:#06c;color:#fff;border-color:#0052a3;box-shadow:inset 0 1px 3px #0000001a}.toolbar-container-wrapper .toolbar-button:disabled{opacity:.5;cursor:not-allowed;background-color:#f9fafb}.toolbar-container-wrapper .toolbar-more-button{padding:6px 8px;font-size:16px;font-weight:500;line-height:1}.toolbar-container-wrapper .toolbar-separator{width:1px;height:24px;background-color:#d1d5db;margin:0 4px}.toolbar-container-wrapper .toolbar-icon{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;flex-shrink:0}.toolbar-container-wrapper .toolbar-icon svg{width:100%;height:100%}.toolbar-container-wrapper .toolbar-dropdown{position:relative;display:flex;align-items:center}.toolbar-container-wrapper .toolbar-dropdown-arrow{font-size:10px;margin-left:2px;line-height:1}.toolbar-container-wrapper .toolbar-dropdown-menu{position:absolute;top:100%;left:0;background:#fff;border:1px solid #d1d5db;border-radius:6px;box-shadow:0 4px 12px #00000026;z-index:1000;min-width:160px;padding:4px 0;margin-top:4px;display:none}.toolbar-container-wrapper .toolbar-dropdown-menu.show{display:block}.toolbar-container-wrapper .toolbar-dropdown-item{display:block;width:100%;padding:8px 12px;border:none;background:transparent;text-align:left;cursor:pointer;font-size:13px;color:#1f2937;transition:background-color .15s ease;font-family:inherit}.toolbar-container-wrapper .toolbar-dropdown-item:hover{background-color:#f3f4f6}.toolbar-container-wrapper .toolbar-dropdown-item:active{background-color:#e5e7eb}.toolbar-container-wrapper .toolbar-input{padding:6px 8px;border:1px solid #d1d5db;border-radius:4px;font-size:13px;font-family:inherit;background-color:#fff;color:#1f2937;transition:all .15s ease}.toolbar-container-wrapper .toolbar-input:focus{outline:none;border-color:#06c;box-shadow:0 0 0 3px #0066cc1a;background-color:#fff}.toolbar-container-wrapper .toolbar-input::placeholder{color:#9ca3af}.toolbar-overflow-menu{animation:slideDown .2s ease-out}@keyframes slideDown{0%{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}.toolbar-overflow-item{transition:background-color .15s ease}.floating-toolbar{user-select:none;-webkit-user-select:none;font-family:system-ui,-apple-system,sans-serif;font-size:14px;animation:fadeInUp .15s ease-out}@keyframes fadeInUp{0%{opacity:0;transform:translate(-50%) translateY(10px)}to{opacity:1;transform:translate(-50%) translateY(0)}}.floating-toolbar-btn{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border:none;background:transparent;border-radius:4px;color:#495057;cursor:pointer;font-size:14px;font-weight:500;transition:all .15s ease;outline:none}.floating-toolbar-btn:hover{background:#f8f9fa;color:#212529}.floating-toolbar-btn:active{background:#e9ecef;transform:scale(.95)}.floating-toolbar-btn.floating-toolbar-toggle{color:#dc3545;font-weight:700}.floating-toolbar-btn.floating-toolbar-toggle:hover{background:#f8d7da;color:#721c24}.floating-toolbar-separator{width:1px;height:20px;background:#e1e5e9;margin:0 2px}@media(max-width:768px){.toolbar-container-wrapper .toolbar-button{padding:5px 8px;font-size:12px;min-height:28px}.toolbar-container-wrapper .toolbar-icon{width:16px;height:16px}.toolbar-container-wrapper .toolbar-dropdown-menu{min-width:140px}.toolbar-container-wrapper .toolbar-dropdown-item{padding:6px 10px;font-size:12px}.floating-toolbar{padding:4px;gap:2px}.floating-toolbar-btn{width:28px;height:28px;font-size:12px}}@media(max-width:480px){.toolbar-container-wrapper{padding:4px}.toolbar-container-wrapper .toolbar-wrapper{padding:4px;gap:2px}.toolbar-container-wrapper .toolbar-button{padding:4px 6px;font-size:11px;min-height:24px}.toolbar-container-wrapper .toolbar-icon{width:14px;height:14px}}.floating-toolbar{pointer-events:auto}.floating-toolbar{max-width:calc(100vw - 20px);overflow-x:auto}@media(prefers-color-scheme:dark){.floating-toolbar{background:#2d3748;border-color:#4a5568;color:#e2e8f0}.floating-toolbar-btn:hover{background:#4a5568;color:#f7fafc}.floating-toolbar-btn:active{background:#718096}.floating-toolbar-separator{background:#4a5568}}';
function z() {
  const n = "editora-webcomponent-styles";
  if (!document.getElementById(n)) {
    const t = document.createElement("style");
    t.id = n, t.textContent = H, document.head.appendChild(t);
  }
}
class u extends HTMLElement {
  constructor() {
    if (super(), this.config = {}, this.isInitialized = !1, z(), !this.hasAttribute("data-initial-content")) {
      const t = this.innerHTML.trim();
      t && this.setAttribute("data-initial-content", t);
    }
  }
  // Observed attributes for reactive updates
  static get observedAttributes() {
    return [
      "height",
      "width",
      "menubar",
      "plugins",
      "toolbar",
      "toolbar-items",
      "readonly",
      "disabled",
      "theme",
      "placeholder",
      "autofocus",
      "language",
      "spellcheck",
      "statusbar"
    ];
  }
  /**
   * Called when element is added to DOM
   */
  connectedCallback() {
    this.config = this.resolveConfig(), this.waitForPluginLoader().then(() => {
      setTimeout(async () => {
        await this.initialize();
      }, 0);
    });
  }
  /**
   * Wait for the global plugin loader to be available
   */
  async waitForPluginLoader() {
    if (u.__globalPluginLoader) {
      this.pluginLoader = u.__globalPluginLoader;
      return;
    }
    return new Promise((t) => {
      const e = () => {
        u.__globalPluginLoader ? (this.pluginLoader = u.__globalPluginLoader, t()) : setTimeout(e, 0);
      };
      e();
    });
  }
  /**
   * Called when element is removed from DOM
   */
  disconnectedCallback() {
    this.destroy();
  }
  /**
   * Called when an observed attribute changes
   */
  attributeChangedCallback(t, e, o) {
    e !== o && (this.config = this.resolveConfig(), this.handleAttributeChange(t, o));
  }
  /**
   * Set configuration via JavaScript API
   */
  async setConfig(t) {
    this.jsConfig = t, this.config = this.resolveConfig(), this.isConnected && (this.destroy(), await this.waitForPluginLoader(), await this.initialize());
  }
  /**
   * Initialize the editor
   */
  async initialize() {
    if (this.querySelector(".editora-toolbar") || this.isInitialized) return;
    this.setAttribute("data-editora-editor", "true"), this.config.height && (this.style.height = typeof this.config.height == "number" ? `${this.config.height}px` : this.config.height), this.config.width && (this.style.width = typeof this.config.width == "number" ? `${this.config.width}px` : this.config.width), this.classList.add("editora-editor"), this.config.theme && this.classList.add(`editora-theme-${this.config.theme}`);
    const t = await this.loadPlugins();
    t.forEach((o) => {
      if (o.init && typeof o.init == "function")
        try {
          o.init({ editorElement: this });
        } catch (r) {
          console.error(`[RichTextEditor] Error initializing plugin ${o.name}:`, r);
        }
    });
    const e = this.getAttribute("data-initial-content") || "";
    this.engine = new v({
      content: e,
      plugins: t,
      readonly: this.config.readonly
    }), this.createUI(t, e), this.setupEventListeners(), this.isInitialized = !0, this.dispatchEvent(new CustomEvent("editor-ready", {
      detail: { api: this.getAPI() },
      bubbles: !0
    }));
  }
  /**
   * Get initial content from slot or attribute
   */
  getInitialContent() {
    if (this.config.content)
      return this.config.content;
    const t = this.querySelector("[slot]");
    return t ? t.innerHTML : this.hasChildNodes() ? Array.from(this.childNodes).map((o) => o.nodeType === Node.TEXT_NODE ? o.textContent : o.nodeType === Node.ELEMENT_NODE ? o.outerHTML : "").join("").trim() : "";
  }
  /**
   * Load plugins based on configuration
   */
  async loadPlugins() {
    this.pluginLoader || await this.waitForPluginLoader();
    const t = [];
    if (this.config.plugins && (typeof this.config.plugins == "string" && this.config.plugins.length > 0 || Array.isArray(this.config.plugins) && this.config.plugins.length > 0)) {
      if (typeof this.config.plugins == "string") {
        const o = await this.pluginLoader.parsePluginString(this.config.plugins);
        t.push(...o);
      } else if (Array.isArray(this.config.plugins))
        for (const o of this.config.plugins)
          if (typeof o == "string") {
            const r = await this.pluginLoader.load(o);
            r && t.push(r);
          } else
            t.push(o);
    } else {
      const o = this.pluginLoader.getRegisteredPluginNames(), r = await this.pluginLoader.loadMultiple(o);
      t.push(...r);
    }
    return t;
  }
  /**
   * Create UI elements
   */
  createUI(t, e) {
    const o = this.querySelector('[slot="toolbar"]'), r = this.querySelector('[slot="statusbar"]');
    if (this.innerHTML = "", this.config.toolbar !== !1 && !o) {
      this.toolbarElement = document.createElement("div"), this.toolbarElement.className = "editora-toolbar-container", this.appendChild(this.toolbarElement);
      const i = this.config.toolbarItems || this.config.toolbar;
      this.toolbar = new L(
        {
          items: typeof i == "string" ? i : void 0,
          sticky: this.config.toolbar && typeof this.config.toolbar == "object" ? this.config.toolbar.sticky : !1,
          position: "top"
        },
        t,
        this.pluginLoader
        // Pass plugin loader to get all registered plugins
      ), this.toolbar.setCommandHandler((a, s) => {
        var b, g;
        if (this.contentElement) {
          this.contentElement.focus();
          const p = window.getSelection();
          if (!p || p.rangeCount === 0 || !this.contentElement.contains(p.anchorNode)) {
            const d = document.createRange(), c = this.contentElement.lastChild || this.contentElement;
            c.nodeType === Node.TEXT_NODE ? d.setStart(c, ((b = c.textContent) == null ? void 0 : b.length) || 0) : c.nodeType === Node.ELEMENT_NODE ? (d.selectNodeContents(c), d.collapse(!1)) : d.setStart(this.contentElement, 0), d.collapse(!0), p == null || p.removeAllRanges(), p == null || p.addRange(d);
          }
        }
        const l = t.find((p) => p.commands && p.commands[a]);
        if (l && l.commands) {
          const p = l.commands[a];
          if (typeof p == "function")
            try {
              return p(a === "toggleFullscreen" ? this : s);
            } catch (d) {
              return console.error(`[RichTextEditor] Error executing native command ${a}:`, d), !1;
            }
        }
        return ((g = this.engine) == null ? void 0 : g.execCommand(a, s)) || !1;
      }), this.toolbar.render(this.toolbarElement);
    } else o && this.appendChild(o);
    this.contentElement = document.createElement("div"), this.contentElement.className = "editora-content rte-content", this.contentElement.contentEditable = this.config.readonly ? "false" : "true", this.contentElement.setAttribute("role", "textbox"), this.contentElement.setAttribute("aria-multiline", "true"), this.config.placeholder && this.contentElement.setAttribute("data-placeholder", this.config.placeholder);
    try {
      document.execCommand("defaultParagraphSeparator", !1, "p");
    } catch (i) {
      console.warn("defaultParagraphSeparator not supported:", i);
    }
    if (e) {
      const i = document.createElement("div");
      i.innerHTML = e.trim(), !Array.from(i.childNodes).some((s) => {
        if (s.nodeType === Node.ELEMENT_NODE) {
          const l = s.tagName;
          return ["P", "DIV", "H1", "H2", "H3", "H4", "H5", "H6", "UL", "OL", "BLOCKQUOTE", "PRE"].includes(l);
        }
        return !1;
      }) && e.trim() ? this.contentElement.innerHTML = `<p>${e.trim()}</p>` : this.contentElement.innerHTML = e;
    } else
      this.config.placeholder ? this.contentElement.innerHTML = "" : this.contentElement.innerHTML = "<p><br></p>";
    this.appendChild(this.contentElement), this.config.toolbar && typeof this.config.toolbar == "object" && this.config.toolbar.floating && (this.floatingToolbar = new P({ enabled: !0 }), this.floatingToolbar.create(this)), r ? this.appendChild(r) : this.config.statusbar && (this.statusBarElement = document.createElement("div"), this.statusBarElement.className = "editora-statusbar-container", this.appendChild(this.statusBarElement), this.statusBar = new T({ position: "bottom" }), this.statusBar.create(this.statusBarElement)), this.config.autofocus && setTimeout(() => {
      var i;
      return (i = this.contentElement) == null ? void 0 : i.focus();
    }, 0);
  }
  /**
   * Setup event listeners
   */
  setupEventListeners() {
    if (!this.contentElement || !this.engine) return;
    this.contentElement.addEventListener("input", () => {
      const e = this.contentElement.innerHTML;
      this.dispatchEvent(new CustomEvent("content-change", {
        detail: { html: e },
        bubbles: !0
      })), this.updateStatusBar();
    }), this.contentElement.addEventListener("focus", () => {
      this.dispatchEvent(new Event("editor-focus", { bubbles: !0 }));
    }), this.contentElement.addEventListener("blur", () => {
      this.dispatchEvent(new Event("editor-blur", { bubbles: !0 }));
    });
    const t = () => {
      this.updateFloatingToolbar(), this.updateStatusBar();
    };
    document.addEventListener("selectionchange", t);
  }
  /**
   * Update floating toolbar position
   */
  updateFloatingToolbar() {
    if (!this.floatingToolbar) return;
    const t = window.getSelection();
    if (!t || t.rangeCount === 0) {
      this.floatingToolbar.hide();
      return;
    }
    const e = t.getRangeAt(0);
    if (e.collapsed) {
      this.floatingToolbar.hide();
      return;
    }
    const o = e.getBoundingClientRect();
    this.floatingToolbar.show(o.left, o.top - 40);
  }
  /**
   * Update status bar with selection and cursor information
   */
  /**
   * Update status bar with current content and cursor information
   */
  updateStatusBar() {
    if (!this.statusBar || !this.contentElement) return;
    const t = this.contentElement.textContent || "", { words: e, chars: o } = M(t), r = S(this.contentElement), i = window.getSelection();
    let a, s;
    if (i && i.rangeCount > 0) {
      const l = i.getRangeAt(0);
      a = I(this.contentElement, l), l.collapsed || (s = N(l, a), a = void 0);
    }
    this.statusBar.update({
      wordCount: e,
      charCount: o,
      lineCount: r,
      cursorPosition: a,
      selectionInfo: s
    });
  }
  /**
   * Handle attribute changes
   */
  handleAttributeChange(t, e) {
    switch (t) {
      case "readonly":
        this.contentElement && (this.contentElement.contentEditable = e === "true" ? "false" : "true"), this.engine && this.engine.setReadonly(e === "true");
        break;
      case "theme":
        this.classList.forEach((o) => {
          o.startsWith("editora-theme-") && this.classList.remove(o);
        }), e && this.classList.add(`editora-theme-${e}`);
        break;
      case "placeholder":
        this.contentElement && this.contentElement.setAttribute("data-placeholder", e);
        break;
      case "toolbar":
      case "plugins":
        this.isConnected && (this.destroy(), this.waitForPluginLoader().then(() => {
          this.initialize().catch((o) => {
            console.error("[RichTextEditor] Error during attribute change re-initialization:", o);
          });
        }));
        break;
    }
  }
  /**
   * Resolve configuration from all sources
   */
  resolveConfig() {
    const t = {};
    for (let e = 0; e < this.attributes.length; e++) {
      const o = this.attributes[e];
      t[o.name] = o.value;
    }
    return x.resolve({
      jsConfig: this.jsConfig,
      attributes: t
    });
  }
  /**
   * Get public API
   */
  getAPI() {
    return {
      getContent: () => {
        var t;
        return ((t = this.contentElement) == null ? void 0 : t.innerHTML) || "";
      },
      setContent: (t) => {
        this.contentElement && (this.contentElement.innerHTML = t);
      },
      execCommand: (t, e) => {
        var o;
        return ((o = this.engine) == null ? void 0 : o.execCommand(t, e)) || !1;
      },
      focus: () => {
        var t;
        (t = this.contentElement) == null || t.focus();
      },
      blur: () => {
        var t;
        (t = this.contentElement) == null || t.blur();
      },
      destroy: () => {
        this.destroy();
      },
      on: (t, e) => (this.addEventListener(t, e), () => this.removeEventListener(t, e)),
      getConfig: () => ({ ...this.config }),
      setReadonly: (t) => {
        this.setAttribute("readonly", t.toString());
      }
    };
  }
  /**
   * Destroy the editor
   */
  destroy() {
    var t, e, o, r;
    (t = this.engine) == null || t.destroy(), (e = this.toolbar) == null || e.destroy(), (o = this.floatingToolbar) == null || o.destroy(), (r = this.statusBar) == null || r.destroy(), this.innerHTML = "", this.isInitialized = !1, this.dispatchEvent(new Event("editor-destroy", { bubbles: !0 }));
  }
  // Public API methods
  getContent() {
    var t;
    return ((t = this.contentElement) == null ? void 0 : t.innerHTML) || "";
  }
  setContent(t) {
    this.contentElement && (this.contentElement.innerHTML = t);
  }
  execCommand(t, e) {
    var o;
    return ((o = this.engine) == null ? void 0 : o.execCommand(t, e)) || !1;
  }
  focus() {
    var t;
    (t = this.contentElement) == null || t.focus();
  }
  blur() {
    var t;
    (t = this.contentElement) == null || t.blur();
  }
}
const f = new w();
u.__globalPluginLoader = f;
const B = {
  // Core editing plugins (always loaded)
  bold: () => import("./BoldPlugin.native-BAzzoqU5.mjs").then((n) => n.BoldPlugin()),
  italic: () => import("./ItalicPlugin.native-CQjjDyUL.mjs").then((n) => n.ItalicPlugin()),
  underline: () => import("./UnderlinePlugin.native-QpIcK4L2.mjs").then((n) => n.UnderlinePlugin()),
  strikethrough: () => import("./StrikethroughPlugin.native-ChaZLaXw.mjs").then((n) => n.StrikethroughPlugin()),
  clearFormatting: () => import("./ClearFormattingPlugin.native-BZPDHswo.mjs").then((n) => n.ClearFormattingPlugin()),
  heading: () => import("./HeadingPlugin.native-DrLYwQnQ.mjs").then((n) => n.HeadingPlugin()),
  blockquote: () => import("./BlockquotePlugin.native-JFmOLsxN.mjs").then((n) => n.BlockquotePlugin()),
  code: () => import("./CodePlugin.native-DD9xFIid.mjs").then((n) => n.CodePlugin()),
  codeSample: () => import("./CodeSamplePlugin.native-DMbEdO9j.mjs").then((n) => n.CodeSamplePlugin()),
  list: () => import("./ListPlugin.native-CLFU5AUQ.mjs").then((n) => n.ListPlugin()),
  checklist: () => import("./ChecklistPlugin.native-Dccs3nLe.mjs").then((n) => n.ChecklistPlugin()),
  textAlignment: () => import("./TextAlignmentPlugin.native-CQIs1m7R.mjs").then((n) => n.TextAlignmentPlugin()),
  indent: () => import("./IndentPlugin.native-CbFugPoi.mjs").then((n) => n.IndentPlugin()),
  direction: () => import("./DirectionPlugin.native-Be7wCzkI.mjs").then((n) => n.DirectionPlugin()),
  textColor: () => import("./TextColorPlugin.native-D6SmTglm.mjs").then((n) => n.TextColorPlugin()),
  backgroundColor: () => import("./BackgroundColorPlugin.native-Dip5uqTg.mjs").then((n) => n.BackgroundColorPlugin()),
  fontSize: () => import("./FontSizePlugin.native-DkLMLPue.mjs").then((n) => n.FontSizePlugin()),
  fontFamily: () => import("./FontFamilyPlugin.native-BzS_9qbM.mjs").then((n) => n.FontFamilyPlugin()),
  lineHeight: () => import("./LineHeightPlugin.native-CWQT2FIa.mjs").then((n) => n.LineHeightPlugin()),
  capitalization: () => import("./CapitalizationPlugin.native-DOMsh5R7.mjs").then((n) => n.CapitalizationPlugin()),
  history: () => import("./HistoryPlugin.native-DoDRifCf.mjs").then((n) => n.HistoryPlugin()),
  // Advanced plugins (lazy loaded)
  link: () => import("./LinkPlugin.native-BdAOV-iu.mjs").then((n) => n.LinkPlugin()),
  table: () => import("./TablePlugin.native-EEWXn1-s.mjs").then((n) => n.TablePlugin()),
  anchor: () => import("./AnchorPlugin.native-7es9PVZ9.mjs").then((n) => n.AnchorPlugin()),
  embedIframe: () => import("./EmbedIframePlugin.native-ifr9KLdN.mjs").then((n) => n.EmbedIframePlugin()),
  math: () => import("./MathPlugin.native-DE_ii-LA.mjs").then((n) => n.MathPlugin()),
  image: () => import("./MediaManagerPlugin.native-DaYFDzNM.mjs").then((n) => n.MediaManagerPlugin()),
  mergeTag: () => import("./MergeTagPlugin.native-CrxyThyn.mjs").then((n) => n.MergeTagPlugin()),
  pageBreak: () => import("./PageBreakPlugin.native-DDjcDyRW.mjs").then((n) => n.PageBreakPlugin()),
  print: () => import("./PrintPlugin.native-BUpm52VJ.mjs").then((n) => n.PrintPlugin()),
  preview: () => import("./PreviewPlugin.native-DBvfpmIv.mjs").then((n) => n.PreviewPlugin()),
  specialCharacters: () => import("./SpecialCharactersPlugin.native-x7a2SWXc.mjs").then((n) => n.SpecialCharactersPlugin()),
  spellCheck: () => import("./SpellCheckPlugin.native-B7yTh0iE.mjs").then((n) => n.SpellCheckPlugin()),
  emojis: () => import("./EmojisPlugin.native-D6mJSnSR.mjs").then((n) => n.EmojisPlugin()),
  a11yChecker: () => import("./A11yCheckerPlugin.native-CZKpi3uF.mjs").then((n) => n.A11yCheckerPlugin()),
  comments: () => import("./CommentsPlugin.native-2zQV8Ia4.mjs").then((n) => n.CommentsPlugin()),
  "document-manager": () => import("./DocumentManagerPlugin.native-BvZL5CSG.mjs").then((n) => n.DocumentManagerPlugin()),
  fullscreen: () => import("./FullscreenPlugin.native-ChXyxeNw.mjs").then((n) => n.FullscreenPlugin()),
  template: () => import("./TemplatePlugin.native-BlSn1c9h.mjs").then((n) => n.TemplatePlugin()),
  footnote: () => import("./FootnotePlugin.native-BciVc9W6.mjs").then((n) => n.FootnotePlugin())
};
async function D() {
  return Object.entries(B).forEach(([n, t]) => {
    f.register(n, t);
  }), f;
}
typeof window != "undefined" && D().then((n) => {
  u.__globalPluginLoader = n, customElements.get("editora-editor") || customElements.define("editora-editor", u);
  const t = document.querySelectorAll("editora-editor:not([data-initial-content])"), e = [];
  t.forEach((i) => {
    const a = i.innerHTML.trim();
    e.push(a), a && i.setAttribute("data-initial-content", a);
  });
  const o = document.querySelectorAll("editora-editor");
  Array.from(o).filter((i) => !i.hasAttribute("data-initial-content")).forEach((i) => {
    const a = Array.from(o).indexOf(i);
    e[a] && i.setAttribute("data-initial-content", e[a]);
  }), window.Editora = {
    version: "1.0.0",
    plugins: f.getRegisteredPluginNames(),
    WebComponent: u,
    init: async (i, a) => {
      const s = document.querySelector(i);
      return s instanceof u ? (a && await s.setConfig(a), s.getAPI()) : null;
    }
  };
});
export {
  u as RichTextEditorElement,
  D as initWebComponent
};
//# sourceMappingURL=webcomponent.js.map
