class v {
  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 v(o, { anchor: 0, head: 0 }, t);
  }
  apply(t, e) {
    return new v(t, e || this.selection, this.schema);
  }
}
class P {
  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 N {
  constructor() {
    this.plugins = [], this.pluginConfigs = /* @__PURE__ */ new Map();
  }
  register(t, e) {
    this.plugins.push(t), e && this.pluginConfigs.set(t.name, e);
    const o = this.pluginConfigs.get(t.name) || t.config;
    if (t.initialize)
      try {
        t.initialize(o);
      } catch (n) {
        console.error(`Failed to initialize plugin "${t.name}":`, n);
      }
    if (t.init && t.init !== t.initialize)
      try {
        t.init(o);
      } catch (n) {
        console.error(`Failed to run init hook for plugin "${t.name}":`, n);
      }
  }
  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 P(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 n = this.getPlugin(t);
    if (!n)
      throw new Error(`Plugin not found: ${t}`);
    const i = this.getPluginConfig(t) || n.config || {}, r = i.mode || "local";
    try {
      switch (r) {
        case "local":
          return n.executeLocal ? n.executeLocal(e, ...o) : null;
        case "api":
          if (!n.executeAPI)
            throw new Error(`Plugin ${t} does not support API mode`);
          return await n.executeAPI(e, ...o);
        case "hybrid":
          if (n.executeHybrid)
            return await n.executeHybrid(e, ...o);
          try {
            if (n.executeAPI)
              return await n.executeAPI(e, ...o);
          } catch (a) {
            if (console.warn(`API execution failed for ${t}, falling back to local`, a), n.executeLocal && i.fallbackToLocal !== !1)
              return n.executeLocal(e, ...o);
            throw a;
          }
          break;
        default:
          throw new Error(`Unknown plugin mode: ${r}`);
      }
    } catch (a) {
      throw console.error(`Error executing command ${e} on plugin ${t}:`, a), a;
    }
  }
  /**
   * 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 O {
  constructor(t) {
    this.shortcuts = /* @__PURE__ */ new Map(), this.enabled = !0, this.isMac = typeof navigator != "undefined" && navigator.platform.toUpperCase().indexOf("MAC") >= 0, (t == null ? void 0 : t.enabled) === !1 && (this.enabled = !1), this.registerDefaultShortcuts(), t != null && t.shortcuts && t.shortcuts.forEach((e) => this.registerShortcut(e)), t != null && t.customShortcuts && Object.values(t.customShortcuts).forEach((e) => {
      this.registerShortcut(e);
    });
  }
  registerDefaultShortcuts() {
    this.registerShortcut({
      key: "b",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "toggleBold",
      description: "Bold",
      preventDefault: !0
    }), this.registerShortcut({
      key: "i",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "toggleItalic",
      description: "Italic",
      preventDefault: !0
    }), this.registerShortcut({
      key: "u",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "toggleUnderline",
      description: "Underline",
      preventDefault: !0
    }), this.registerShortcut({
      key: "d",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "toggleStrikethrough",
      description: "Strikethrough",
      preventDefault: !0
    }), this.registerShortcut({
      key: "z",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "undo",
      description: "Undo",
      preventDefault: !0
    }), this.registerShortcut({
      key: "z",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "redo",
      description: "Redo",
      preventDefault: !0
    }), this.registerShortcut({
      key: "y",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "redo",
      description: "Redo",
      preventDefault: !0
    });
    for (let t = 1; t <= 6; t++)
      this.registerShortcut({
        key: String(t),
        ctrl: !this.isMac,
        meta: this.isMac,
        alt: !0,
        command: "setBlockType",
        params: `h${t}`,
        description: `Heading ${t}`,
        preventDefault: !0
      });
    this.registerShortcut({
      key: "7",
      ctrl: !this.isMac,
      meta: this.isMac,
      alt: !0,
      command: "setBlockType",
      params: "p",
      description: "Paragraph",
      preventDefault: !0
    }), this.registerShortcut({
      key: "7",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "toggleOrderedList",
      description: "Numbered List",
      preventDefault: !0
    }), this.registerShortcut({
      key: "8",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "toggleBulletList",
      description: "Bullet List",
      preventDefault: !0
    }), this.registerShortcut({
      key: "k",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "openLinkDialog",
      description: "Insert/Edit Link",
      preventDefault: !0
    }), this.registerShortcut({
      key: "e",
      ctrl: !this.isMac,
      meta: this.isMac,
      alt: !0,
      command: "insertCodeBlock",
      description: "Code Block",
      preventDefault: !0
    }), this.registerShortcut({
      key: "q",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "toggleBlockquote",
      description: "Blockquote",
      preventDefault: !0
    }), this.registerShortcut({
      key: "l",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "setTextAlignment",
      params: "left",
      description: "Align Left",
      preventDefault: !0
    }), this.registerShortcut({
      key: "e",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      alt: !0,
      command: "setTextAlignment",
      params: "center",
      description: "Align Center",
      preventDefault: !0
    }), this.registerShortcut({
      key: "r",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "setTextAlignment",
      params: "right",
      description: "Align Right",
      preventDefault: !0
    }), this.registerShortcut({
      key: "j",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "setTextAlignment",
      params: "justify",
      description: "Justify",
      preventDefault: !0
    }), this.registerShortcut({
      key: "\\",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "clearFormatting",
      description: "Clear Formatting",
      preventDefault: !0
    }), this.registerShortcut({
      key: "]",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "increaseIndent",
      description: "Indent",
      preventDefault: !0
    }), this.registerShortcut({
      key: "[",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "decreaseIndent",
      description: "Outdent",
      preventDefault: !0
    }), this.registerShortcut({
      key: "g",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "insertImage",
      description: "Insert Image",
      preventDefault: !0
    }), this.registerShortcut({
      key: "t",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      alt: !0,
      command: "insertTable",
      description: "Insert Table",
      preventDefault: !0
    }), this.registerShortcut({
      key: "f11",
      command: "toggleFullscreen",
      description: "Toggle Fullscreen",
      preventDefault: !0
    }), this.registerShortcut({
      key: "p",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "togglePreview",
      description: "Preview",
      preventDefault: !0
    }), this.registerShortcut({
      key: "p",
      ctrl: !this.isMac,
      meta: this.isMac,
      command: "print",
      description: "Print",
      preventDefault: !0
    }), this.registerShortcut({
      key: "s",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      alt: !0,
      command: "insertSpecialCharacter",
      description: "Insert Special Character",
      preventDefault: !0
    }), this.registerShortcut({
      key: "m",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "insertEmoji",
      description: "Insert Emoji",
      preventDefault: !0
    }), this.registerShortcut({
      key: "9",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      command: "toggleChecklist",
      description: "Checklist",
      preventDefault: !0
    }), this.registerShortcut({
      key: "a",
      ctrl: !this.isMac,
      meta: this.isMac,
      shift: !0,
      alt: !0,
      command: "toggleA11yChecker",
      description: "Accessibility Checker",
      preventDefault: !0
    }), this.registerShortcut({
      key: "F7",
      command: "toggleSpellCheck",
      description: "Spell Check",
      preventDefault: !0
    }), this.registerShortcut({
      key: "m",
      ctrl: !this.isMac,
      meta: this.isMac,
      alt: !0,
      command: "insertMath",
      description: "Insert Math",
      preventDefault: !0
    }), this.registerShortcut({
      key: "f",
      ctrl: !this.isMac,
      meta: this.isMac,
      alt: !0,
      command: "insertFootnote",
      description: "Insert Footnote",
      preventDefault: !0
    });
  }
  registerShortcut(t) {
    const e = this.getShortcutKey(t);
    this.shortcuts.set(e, t);
  }
  unregisterShortcut(t) {
    const e = this.getShortcutKey(t);
    this.shortcuts.delete(e);
  }
  getShortcutKey(t) {
    const e = [];
    return t.ctrl && e.push("ctrl"), t.alt && e.push("alt"), t.shift && e.push("shift"), t.meta && e.push("meta"), e.push(t.key.toLowerCase()), e.join("+");
  }
  getEventKey(t) {
    const e = [];
    return t.ctrlKey && e.push("ctrl"), t.altKey && e.push("alt"), t.shiftKey && e.push("shift"), t.metaKey && e.push("meta"), e.push(t.key.toLowerCase()), e.join("+");
  }
  handleKeyDown(t, e) {
    if (!this.enabled) return !1;
    const o = this.getEventKey(t), n = this.shortcuts.get(o);
    return n ? (n.preventDefault !== !1 && (t.preventDefault(), t.stopPropagation()), e(n.command, n.params), !0) : !1;
  }
  enable() {
    this.enabled = !0;
  }
  disable() {
    this.enabled = !1;
  }
  isEnabled() {
    return this.enabled;
  }
  getAllShortcuts() {
    return Array.from(this.shortcuts.values());
  }
  getShortcutForCommand(t) {
    return Array.from(this.shortcuts.values()).find((e) => e.command === t);
  }
  getShortcutDescription(t) {
    const e = [];
    this.isMac ? (t.meta && e.push("⌘"), t.ctrl && e.push("⌃"), t.alt && e.push("⌥"), t.shift && e.push("⇧")) : (t.ctrl && e.push("Ctrl"), t.alt && e.push("Alt"), t.shift && e.push("Shift"));
    const o = t.key.length === 1 ? t.key.toUpperCase() : t.key;
    return e.push(o), e.join("+");
  }
  getShortcutsHelp() {
    const t = this.getAllShortcuts(), e = /* @__PURE__ */ new Map();
    t.forEach((n) => {
      const i = this.getShortcutCategory(n.command);
      e.has(i) || e.set(i, []), e.get(i).push(n);
    });
    let o = `# Keyboard Shortcuts

`;
    return e.forEach((n, i) => {
      o += `## ${i}

`, n.forEach((r) => {
        const a = this.getShortcutDescription(r);
        o += `- **${a}**: ${r.description || r.command}
`;
      }), o += `
`;
    }), o;
  }
  getShortcutCategory(t) {
    return t.includes("toggle") && (t.includes("Bold") || t.includes("Italic") || t.includes("Underline") || t.includes("Strike") || t.includes("Code") || t.includes("Super") || t.includes("Sub")) ? "Text Formatting" : t.includes("Heading") || t.includes("Paragraph") ? "Block Formatting" : t.includes("List") || t.includes("Checklist") ? "Lists" : t.includes("Alignment") || t.includes("Indent") ? "Alignment & Indentation" : t.includes("undo") || t.includes("redo") ? "History" : t.includes("insert") ? "Insert" : t.includes("find") || t.includes("replace") ? "Find & Replace" : t.includes("Accessibility") || t.includes("spell") ? "Tools" : "Other";
  }
}
class B {
  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 z {
  constructor(t = {}) {
    this.listeners = /* @__PURE__ */ new Map(), this.isReadonly = !1, this.isDestroyed = !1, this.isReadonly = t.readonly || !1, this.pluginManager = new N(), t.plugins && Array.isArray(t.plugins) && t.plugins.forEach((o) => this.pluginManager.register(o));
    const e = this.pluginManager.buildSchema();
    this.state = v.create(e), this.commandRegistry = new B(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 n;
    return e !== void 0 ? n = o(this.state, e) : n = o(this.state), n instanceof Promise ? (n.then((i) => {
      i && typeof i == "object" && "doc" in i && "selection" in i && (this.setState(i), this.emit("change", this.state));
    }).catch((i) => {
      console.error(`Async command failed: ${t}`, i);
    }), !0) : n && typeof n == "object" && "doc" in n && "selection" in n ? (this.setState(n), this.emit("change", this.state), !0) : n !== !1 && n != null;
  }
  /**
   * 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 n = o.indexOf(e);
        n > -1 && o.splice(n, 1);
      }
    };
  }
  /**
   * Emit event
   */
  emit(t, ...e) {
    const o = this.listeners.get(t);
    o && o.forEach((n) => {
      try {
        n(...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 R {
  // PluginLoader instance to get all registered plugins
  setLastCommandTrigger(t, e) {
    if (typeof window == "undefined" || !t) return;
    const o = e || t.getAttribute("data-command") || void 0;
    o && (window.__editoraLastCommandButton = t, window.__editoraLastCommand = o);
  }
  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((a) => a.trim()), n = this.getAvailableToolbarItems(), i = /* @__PURE__ */ new Map();
    n.forEach((a) => {
      a.command && i.set(a.command, a), a.type === "group" && a.label && i.set(a.label, a);
    });
    const r = {
      bold: "toggleBold",
      italic: "toggleItalic",
      underline: "toggleUnderline",
      strikethrough: "toggleStrikethrough",
      bullist: "toggleBulletList",
      numlist: "toggleOrderedList",
      checklist: "toggleChecklist",
      link: "openLinkDialog",
      image: "openImageDialog",
      table: "insertTable",
      trackChanges: "toggleTrackChanges",
      acceptTrackChanges: "acceptAllTrackChanges",
      rejectTrackChanges: "rejectAllTrackChanges",
      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",
      dataBinding: "openDataBindingDialog",
      dataBindingPreview: "openDataBindingDialog",
      contentRules: "toggleContentRulesPanel",
      contentRulesAudit: "runContentRulesAudit",
      contentRulesRealtime: "toggleContentRulesRealtime",
      mention: "insertMention",
      slash: "openSlashCommands",
      slashCommands: "openSlashCommands",
      pageBreak: "insertPageBreak",
      template: "insertTemplate",
      importWord: "importWord",
      exportWord: "exportWord",
      exportPdf: "exportPdf",
      insertImage: "insertImage",
      insertVideo: "insertVideo",
      codeBlock: "insertCodeBlock"
    };
    return o.forEach((a) => {
      const l = [];
      a.split(/\s+/).filter(Boolean).forEach((d) => {
        if (d === "direction") {
          const u = i.get("setDirectionLTR"), f = i.get("setDirectionRTL");
          u && l.push({
            id: "directionLTR",
            label: u.label,
            command: u.command,
            icon: u.icon,
            type: u.type || "button",
            options: u.options
          }), f && l.push({
            id: "directionRTL",
            label: f.label,
            command: f.command,
            icon: f.icon,
            type: f.type || "button",
            options: f.options
          });
          return;
        }
        if (d === "comments") {
          const u = i.get("addComment"), f = i.get("toggleComments");
          u && l.push({
            id: "addComment",
            label: u.label,
            command: u.command,
            icon: u.icon,
            type: u.type || "button",
            options: u.options
          }), f && l.push({
            id: "toggleComments",
            label: f.label,
            command: f.command,
            icon: f.icon,
            type: f.type || "button",
            options: f.options
          });
          return;
        }
        const h = r[d] || d;
        let p = i.get(h);
        p || (p = i.get(d)), p && l.push({
          id: d,
          label: p.label,
          command: p.command,
          icon: p.icon,
          type: p.type === "separator" ? "separator" : p.type || "button",
          options: p.options,
          items: p.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((n, i) => {
      const r = document.createElement("div");
      if (r.className = "editora-toolbar-group", n.forEach((a) => {
        this.appendToolbarButton(r, a);
      }), t.appendChild(r), i < o.length - 1) {
        const a = document.createElement("div");
        a.className = "editora-toolbar-separator", t.appendChild(a);
      }
    });
  }
  /**
   * 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"), o = t.label.toLowerCase().replace(/\s+/g, "-");
    if (e.className = `editora-toolbar-group-button ${o}`, e.title = t.label, t.icon)
      if (t.icon.startsWith("<svg") && t.icon.endsWith("</svg>")) {
        const n = document.createElement("span");
        n.className = "editora-toolbar-icon", n.innerHTML = t.icon, e.appendChild(n);
      } else
        e.innerHTML = t.icon;
    if (t.items && t.items.length) {
      const n = document.createElement("div");
      n.className = `editora-toolbar-group-items ${o}`, t.items.forEach((i) => {
        this.appendToolbarButton(n, i);
      }), e.appendChild(n);
    }
    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 || "", t.command && e.setAttribute("data-command", t.command), t.active && e.classList.add("active"), t.disabled && (e.disabled = !0), e.addEventListener("click", (o) => {
      o.preventDefault(), this.setLastCommandTrigger(e, t.command), this.commandHandler && t.command && 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, t.command && 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 && t.command && 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 n = document.createElement("div");
    n.className = "editora-toolbar-dropdown-menu", n.style.display = "none", t.options && t.options.forEach((a) => {
      const l = document.createElement("button");
      l.className = "editora-toolbar-dropdown-item", l.type = "button", l.textContent = a.label, l.setAttribute("data-value", a.value), l.addEventListener("click", (c) => {
        c.preventDefault(), this.setLastCommandTrigger(o, t.command), this.commandHandler && t.command && this.commandHandler(t.command, a.value), n.style.display = "none";
      }), n.appendChild(l);
    }), o.addEventListener("click", (a) => {
      a.preventDefault(), a.stopPropagation(), this.setLastCommandTrigger(o, t.command);
      const l = n.style.display === "block";
      n.style.display = l ? "none" : "block";
    });
    const i = (a) => {
      e.contains(a.target) || (n.style.display = "none");
    }, r = (a) => {
      a.key === "Escape" && (n.style.display = "none");
    };
    return document.addEventListener("mousedown", i, !0), document.addEventListener("keydown", r), e._cleanupDropdown = () => {
      document.removeEventListener("mousedown", i, !0), document.removeEventListener("keydown", r);
    }, e.appendChild(o), e.appendChild(n), 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 a = document.createElement("span");
        a.className = "editora-toolbar-icon", a.innerHTML = t.icon, o.appendChild(a);
      } else
        o.innerHTML = t.icon;
    else
      o.textContent = t.label;
    const n = document.createElement("div");
    n.className = "editora-toolbar-dropdown-menu", n.style.display = "none", t.options && t.options.forEach((a) => {
      const l = document.createElement("button");
      l.className = "editora-toolbar-dropdown-item", l.type = "button", l.textContent = a.label, l.setAttribute("data-value", a.value), l.addEventListener("click", (c) => {
        c.preventDefault(), c.stopPropagation(), this.setLastCommandTrigger(o, t.command), this.commandHandler && t.command && this.commandHandler(t.command, a.value), n.style.display = "none";
      }), n.appendChild(l);
    }), o.addEventListener("click", (a) => {
      var c;
      a.preventDefault(), a.stopPropagation(), this.setLastCommandTrigger(o, t.command);
      const l = (c = this.container) == null ? void 0 : c.querySelectorAll(
        ".editora-toolbar-dropdown-menu"
      );
      l == null || l.forEach((d) => {
        d !== n && (d.style.display = "none");
      }), n.style.display = n.style.display === "none" ? "block" : "none";
    });
    const i = (a) => {
      e.contains(a.target) || (n.style.display = "none");
    }, r = (a) => {
      a.key === "Escape" && (n.style.display = "none");
    };
    return document.addEventListener("mousedown", i, !0), document.addEventListener("keydown", r), e._cleanupDropdown = () => {
      document.removeEventListener("mousedown", i, !0), document.removeEventListener("keydown", r);
    }, e.appendChild(o), e.appendChild(n), 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 H {
  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 j {
  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 n = [];
    this.statusInfo.wordCount !== void 0 && n.push(`${this.statusInfo.wordCount} words`), this.statusInfo.charCount !== void 0 && n.push(`${this.statusInfo.charCount} chars`), this.statusInfo.lineCount !== void 0 && n.push(`${this.statusInfo.lineCount} lines`), this.statusInfo.custom && Object.entries(this.statusInfo.custom).forEach(([i, r]) => {
      n.push(`${i}: ${r}`);
    }), o.forEach((i, r) => {
      const a = document.createElement("span");
      if (a.className = "editora-statusbar-item", a.textContent = i, t.appendChild(a), r < o.length - 1) {
        const l = document.createElement("span");
        l.className = "editora-statusbar-separator", l.textContent = "|", t.appendChild(l);
      }
    }), n.forEach((i, r) => {
      const a = document.createElement("span");
      if (a.className = "editora-statusbar-item", a.textContent = i, e.appendChild(a), r < n.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 F(s, t) {
  const e = s.textContent || "", o = $(s, t.startContainer, t.startOffset), i = e.substring(0, o).split(`
`), r = i.length, a = i[i.length - 1].length + 1;
  return { line: r, column: a };
}
function $(s, t, e) {
  var r;
  let o = 0;
  const n = document.createTreeWalker(
    s,
    NodeFilter.SHOW_TEXT,
    null
  );
  let i = n.firstChild();
  for (; i; ) {
    if (i === t) {
      o += e;
      break;
    } else i.nodeType === Node.TEXT_NODE && (o += ((r = i.textContent) == null ? void 0 : r.length) || 0);
    i = n.nextNode();
  }
  return o;
}
function _(s) {
  var o, n;
  const t = s.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()) === "" || ((n = i.textContent) == null ? void 0 : n.trim()) === "") && e++;
  } else {
    const r = (s.textContent || "").split(`
`).length;
    e = Math.max(1, r);
  }
  return e;
}
function W(s) {
  const t = s.trim() ? s.trim().split(/\s+/).length : 0, e = s.length;
  return { words: t, chars: e };
}
function U(s, t) {
  const e = s.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 E = class E {
  /**
   * 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), this.normalizeConfig(e);
  }
  /**
   * Normalize mixed legacy/new config shapes
   */
  static normalizeConfig(t) {
    const e = { ...t };
    if (e.toolbarFloating !== void 0 || e.toolbarSticky !== void 0) {
      const r = typeof e.toolbar == "object" && e.toolbar ? { ...e.toolbar } : typeof e.toolbar == "string" ? { items: e.toolbar } : {};
      e.toolbarFloating !== void 0 && (r.floating = !!e.toolbarFloating), e.toolbarSticky !== void 0 && (r.sticky = !!e.toolbarSticky), e.toolbar = r;
    }
    if (e.toolbarItems !== void 0 && typeof e.toolbar == "object" && e.toolbar && (e.toolbar.items = e.toolbarItems), e.autosaveEnabled !== void 0 || e.autosaveIntervalMs !== void 0 || e.autosaveStorageKey !== void 0 || e.autosaveProvider !== void 0 || e.autosaveApiUrl !== void 0) {
      const r = typeof e.autosave == "object" && e.autosave ? { ...e.autosave } : {};
      e.autosaveEnabled !== void 0 && (r.enabled = !!e.autosaveEnabled), e.autosaveIntervalMs !== void 0 && (r.intervalMs = Number(e.autosaveIntervalMs)), e.autosaveStorageKey !== void 0 && (r.storageKey = e.autosaveStorageKey), e.autosaveProvider !== void 0 && (r.provider = e.autosaveProvider), e.autosaveApiUrl !== void 0 && (r.apiUrl = e.autosaveApiUrl), e.autosave = r;
    }
    const o = {
      enabled: !1,
      intervalMs: 3e4,
      storageKey: "rte-autosave",
      provider: "localStorage",
      apiUrl: ""
    };
    if (typeof e.autosave == "boolean")
      e.autosave = {
        ...o,
        enabled: e.autosave
      };
    else if (typeof e.autosave == "object" && e.autosave) {
      const r = {
        ...o,
        ...e.autosave
      };
      r.intervalMs === void 0 && r.interval !== void 0 && (r.intervalMs = Number(r.interval)), r.enabled === void 0 && (r.enabled = !0), (!Number.isFinite(r.intervalMs) || r.intervalMs <= 0) && (r.intervalMs = o.intervalMs), e.autosave = r;
    } else
      e.autosave = o;
    if (e.languageLocale !== void 0 || e.languageDirection !== void 0) {
      const r = typeof e.language == "object" && e.language ? { ...e.language } : {};
      e.languageLocale !== void 0 && (r.locale = e.languageLocale), e.languageDirection !== void 0 && (r.direction = e.languageDirection), e.language = r;
    }
    const n = { locale: "en", direction: "ltr" };
    if (typeof e.language == "string" ? e.language = {
      locale: e.language,
      direction: n.direction
    } : typeof e.language == "object" && e.language ? e.language = {
      ...n,
      ...e.language
    } : e.language = n, e.spellcheckEnabled !== void 0 || e.spellcheckProvider !== void 0 || e.spellcheckApiUrl !== void 0) {
      const r = typeof e.spellcheck == "object" && e.spellcheck ? { ...e.spellcheck } : {};
      e.spellcheckEnabled !== void 0 && (r.enabled = !!e.spellcheckEnabled), e.spellcheckProvider !== void 0 && (r.provider = e.spellcheckProvider), e.spellcheckApiUrl !== void 0 && (r.apiUrl = e.spellcheckApiUrl), e.spellcheck = r;
    }
    const i = {
      enabled: !1,
      provider: "browser",
      apiUrl: ""
    };
    if (typeof e.spellcheck == "boolean")
      e.spellcheck = {
        ...i,
        enabled: e.spellcheck
      };
    else if (typeof e.spellcheck == "object" && e.spellcheck) {
      const r = {
        ...i,
        ...e.spellcheck
      };
      !r.provider && r.mode && (r.provider = r.mode === "local" ? "browser" : "api"), r.enabled === void 0 && (r.enabled = !!(r.mode || r.provider || r.apiUrl)), e.spellcheck = r;
    } else
      e.spellcheck = i;
    return e.contextMenuEnabled !== void 0 && (e.contextMenu = {
      enabled: !!e.contextMenuEnabled
    }), typeof e.contextMenu == "boolean" ? e.contextMenu = { enabled: e.contextMenu } : typeof e.contextMenu == "object" && e.contextMenu ? e.contextMenu = {
      enabled: e.contextMenu.enabled !== !1
    } : e.contextMenu = { enabled: !0 }, (e.pasteClean !== void 0 || e.pasteKeepFormatting !== void 0 || e.pasteConvertWord !== void 0) && (e.paste = {
      ...e.paste || {},
      ...e.pasteClean !== void 0 ? { clean: !!e.pasteClean } : {},
      ...e.pasteKeepFormatting !== void 0 ? { keepFormatting: !!e.pasteKeepFormatting } : {},
      ...e.pasteConvertWord !== void 0 ? { convertWord: !!e.pasteConvertWord } : {}
    }), e.paste = {
      clean: !0,
      keepFormatting: !1,
      convertWord: !0,
      ...e.paste || {}
    }, e.contentConfig = {
      allowedTags: [],
      allowedAttributes: {},
      sanitize: !0,
      ...e.contentConfig || {}
    }, (e.securitySanitizeOnPaste !== void 0 || e.securitySanitizeOnInput !== void 0) && (e.security = {
      ...e.security || {},
      ...e.securitySanitizeOnPaste !== void 0 ? { sanitizeOnPaste: !!e.securitySanitizeOnPaste } : {},
      ...e.securitySanitizeOnInput !== void 0 ? { sanitizeOnInput: !!e.securitySanitizeOnInput } : {}
    }), e.security = {
      sanitizeOnPaste: !0,
      sanitizeOnInput: !0,
      ...e.security || {}
    }, (e.accessibilityEnableAria !== void 0 || e.accessibilityKeyboardNavigation !== void 0 || e.accessibilityChecker !== void 0) && (e.accessibility = {
      ...e.accessibility || {},
      ...e.accessibilityEnableAria !== void 0 ? { enableARIA: !!e.accessibilityEnableAria } : {},
      ...e.accessibilityKeyboardNavigation !== void 0 ? { keyboardNavigation: !!e.accessibilityKeyboardNavigation } : {},
      ...e.accessibilityChecker !== void 0 ? { checker: !!e.accessibilityChecker } : {}
    }), typeof e.accessibility == "boolean" && (e.accessibility = {
      enableARIA: e.accessibility,
      keyboardNavigation: e.accessibility,
      checker: !1
    }), e.accessibility = {
      enableARIA: !0,
      keyboardNavigation: !0,
      checker: !1,
      ...e.accessibility || {}
    }, (e.performanceDebounceInputMs !== void 0 || e.performanceViewportOnlyScan !== void 0) && (e.performance = {
      ...e.performance || {},
      ...e.performanceDebounceInputMs !== void 0 ? { debounceInputMs: Number(e.performanceDebounceInputMs) } : {},
      ...e.performanceViewportOnlyScan !== void 0 ? { viewportOnlyScan: !!e.performanceViewportOnlyScan } : {}
    }), typeof e.performance == "boolean" && (e.performance = {
      debounceInputMs: 100,
      viewportOnlyScan: e.performance
    }), e.performance = {
      debounceInputMs: 100,
      viewportOnlyScan: !0,
      ...e.performance || {}
    }, (typeof e.performance.debounceInputMs != "number" || !Number.isFinite(e.performance.debounceInputMs) || e.performance.debounceInputMs < 0) && (e.performance.debounceInputMs = 100), e;
  }
  /**
   * Parse web component attributes
   */
  static parseAttributes(t) {
    const e = {};
    for (const [o, n] of Object.entries(t)) {
      const i = this.kebabToCamel(o);
      e[i] = this.parseAttributeValue(n);
    }
    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 [n, i] of Object.entries(o))
        i != null && (typeof i == "object" && !Array.isArray(i) && e[n] ? e[n] = this.merge(e[n], i) : e[n] = i);
    return e;
  }
};
E.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,
  accessibility: {
    enableARIA: !0,
    keyboardNavigation: !0,
    checker: !1
  },
  performance: {
    debounceInputMs: 100,
    viewportOnlyScan: !0
  },
  spellcheck: {
    enabled: !1,
    provider: "browser",
    apiUrl: ""
  },
  language: {
    locale: "en",
    direction: "ltr"
  },
  contextMenu: {
    enabled: !0
  },
  contentConfig: {
    allowedTags: [],
    allowedAttributes: {},
    sanitize: !0
  },
  paste: {
    clean: !0,
    keepFormatting: !1,
    convertWord: !0
  },
  security: {
    sanitizeOnPaste: !0,
    sanitizeOnInput: !0
  },
  statusbar: !1
};
let x = E;
class K {
  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 n = await o();
    return e && this.applyPluginConfig(n, e), this.loadedPlugins.set(t, n), n;
  }
  /**
   * Load multiple plugins
   */
  async loadMultiple(t, e) {
    return (await Promise.all(
      t.map((n) => this.load(n, e))
    )).filter((n) => n !== 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);
  }
}
const q = [
  "p",
  "br",
  "strong",
  "em",
  "u",
  "s",
  "strike",
  "del",
  "b",
  "i",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "ul",
  "ol",
  "li",
  "a",
  "img",
  "video",
  "audio",
  "iframe",
  "table",
  "thead",
  "tbody",
  "tr",
  "th",
  "td",
  "blockquote",
  "pre",
  "code",
  "span",
  "div",
  "section",
  "sup",
  "sub",
  "hr"
], V = {
  "*": ["class", "style", "id", "data-*", "role", "aria-*", "tabindex", "contenteditable", "spellcheck", "dir", "lang"],
  a: ["href", "target", "rel", "title"],
  img: ["src", "alt", "width", "height", "loading"],
  video: ["src", "controls", "width", "height", "autoplay", "loop", "muted"],
  audio: ["src", "controls", "autoplay", "loop", "muted"],
  iframe: ["src", "width", "height", "name", "title", "longdesc", "allow", "allowfullscreen", "frameborder", "scrolling", "loading", "referrerpolicy"],
  table: ["border", "cellpadding", "cellspacing"],
  td: ["colspan", "rowspan", "align", "valign"],
  th: ["colspan", "rowspan", "align", "valign"]
};
function M(s, t, e) {
  if ((t == null ? void 0 : t.sanitize) === !1)
    return s;
  const o = t != null && t.allowedTags && t.allowedTags.length > 0 ? t.allowedTags : q, i = !!(t != null && t.allowedAttributes) && Object.keys(t.allowedAttributes).length > 0 ? t.allowedAttributes : V, r = document.createElement("div");
  return r.innerHTML = s, I(r, o, i), r.innerHTML;
}
function I(s, t, e) {
  const o = Array.from(s.childNodes);
  for (const n of o)
    if (n.nodeType === Node.ELEMENT_NODE) {
      const i = n, r = i.tagName.toLowerCase();
      if (!t.includes(r)) {
        for (; i.firstChild; )
          s.insertBefore(i.firstChild, i);
        s.removeChild(i);
        continue;
      }
      G(i, e), I(i, t, e);
    } else n.nodeType !== Node.TEXT_NODE && s.removeChild(n);
}
function G(s, t) {
  const e = s.tagName.toLowerCase(), o = Array.from(s.attributes), n = t[e] || [], i = t["*"] || [], r = [...n, ...i];
  for (const a of o) {
    const l = a.name.toLowerCase();
    let c = !1;
    r.includes(l) && (c = !0);
    for (const d of r)
      if (d.endsWith("*")) {
        const h = d.slice(0, -1);
        if (l.startsWith(h)) {
          c = !0;
          break;
        }
      }
    (l.startsWith("on") || l === "javascript:" || l === "href" && a.value.trim().toLowerCase().startsWith("javascript:") || l === "src" && a.value.trim().toLowerCase().startsWith("javascript:")) && (c = !1), l === "dir" && !["ltr", "rtl", "auto"].includes(a.value.trim().toLowerCase()) && (c = !1), c || s.removeAttribute(a.name);
  }
  s.hasAttribute("href") && (s.getAttribute("href") || "").trim().toLowerCase().startsWith("javascript:") && s.removeAttribute("href"), s.hasAttribute("src") && (s.getAttribute("src") || "").trim().toLowerCase().startsWith("javascript:") && s.removeAttribute("src");
}
function X(s, t, e) {
  return (e == null ? void 0 : e.sanitizeOnPaste) === !1 ? s : M(s, t);
}
function Y(s, t, e) {
  return (e == null ? void 0 : e.sanitizeOnInput) === !1 ? s : M(s, t);
}
const J = '.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{--editora-dark-toolbar-bg-start: #353d48;--editora-dark-toolbar-bg-end: #2d3540;--editora-dark-button-bg-start: #46505f;--editora-dark-button-bg-end: #3b4553;--editora-dark-button-hover-start: #525d6d;--editora-dark-button-hover-end: #465262;--editora-dark-button-active-start: #5eaaf6;--editora-dark-button-active-end: #4a95de;--editora-dark-border: #475263;--editora-dark-border-strong: #566275;--editora-dark-text: #e1e9f5;--editora-dark-text-strong: #f3f7ff;--editora-dark-text-muted: #aeb9cc;--editora-dark-surface: #1d242d;--editora-dark-content: #1f2732;background:linear-gradient(180deg,#1b2330,#1c2430);color:var(--editora-dark-text);border-color:var(--editora-dark-border)}.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:linear-gradient(180deg,var(--editora-dark-toolbar-bg-start) 0%,var(--editora-dark-toolbar-bg-end) 100%);border-bottom-color:var(--editora-dark-border);box-shadow:inset 0 1px #ffffff0d}.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-group-button{display:flex;align-items:center}.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:0px solid #ccc;border-radius:0!important}&:hover{background:#e0e0e0;border-color:#ccc}}}.editora-theme-dark .editora-toolbar-button{background:linear-gradient(180deg,var(--editora-dark-button-bg-start) 0%,var(--editora-dark-button-bg-end) 100%);border-color:var(--editora-dark-border-strong);color:var(--editora-dark-text);box-shadow:inset 0 1px #ffffff14,0 1px 1px #00000059}.editora-theme-dark .editora-toolbar-group-items{border-color:var(--editora-dark-border-strong);background:linear-gradient(180deg,var(--editora-dark-button-bg-start) 0%,var(--editora-dark-button-bg-end) 100%)}.editora-theme-dark .editora-toolbar-group-items .editora-toolbar-button:first-child{border-right-color:#566275}.editora-theme-dark .editora-toolbar-group-items .editora-toolbar-button:last-child{border-left-color:#566275}.editora-theme-dark .editora-toolbar-input.font-size{background-color:#2e3642;color:var(--editora-dark-text-strong);border-color:var(--editora-dark-border-strong);caret-color:var(--editora-dark-text-strong)}.editora-theme-dark .editora-toolbar-input.font-size::placeholder{color:var(--editora-dark-text-strong);opacity:1}.editora-toolbar-button:hover{background:#e0e0e0;border-color:#ccc}.editora-theme-dark .editora-toolbar-button:hover{background:linear-gradient(180deg,var(--editora-dark-button-hover-start) 0%,var(--editora-dark-button-hover-end) 100%);border-color:#66748a;color:var(--editora-dark-text-strong)}.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:linear-gradient(180deg,var(--editora-dark-button-active-start) 0%,var(--editora-dark-button-active-end) 100%);border-color:#67adf4;color:#0f1b2a}.editora-theme-dark .editora-toolbar-button:disabled{background:#313946;border-color:#424d5e;color:#7f8ca1}.editora-theme-dark .editora-toolbar-button[data-command=insertTable],.editora-theme-dark .editora-toolbar-button[data-command=print],.editora-theme-dark .editora-toolbar-button[data-command=toggleSpellCheck],.editora-theme-dark .editora-toolbar-button[data-command=toggleA11yChecker],.editora-theme-dark .editora-toolbar-button[data-command=setDirectionLTR],.editora-theme-dark .editora-toolbar-button[data-command=setDirectionRTL]{color:#f1f6ff}.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:20px;height:20px;display:block;color:currentColor;fill:currentColor}.editora-theme-dark .editora-toolbar-icon,.editora-theme-dark .editora-toolbar-icon *{color:inherit}.editora-theme-dark :is(.editora-toolbar-button,.editora-toolbar-icon) svg :is([stroke="#000" i],[stroke="#000000" i],[stroke=black i],[stroke="#0f0f0f" i],[stroke="#111111" i],[style*="stroke:#000" i],[style*="stroke: #000" i],[style*="stroke:black" i],[style*="stroke: black" i],[style*="stroke:#0f0f0f" i],[style*="stroke: #0f0f0f" i]){stroke:currentColor!important}.editora-theme-dark :is(.editora-toolbar-button,.editora-toolbar-icon) svg :is([fill="#000" i],[fill="#000000" i],[fill=black i],[fill="#0f0f0f" i],[fill="#111111" i],[style*="fill:#000" i],[style*="fill: #000" i],[style*="fill:black" i],[style*="fill: black" i],[style*="fill:#0f0f0f" i],[style*="fill: #0f0f0f" i]){fill:currentColor!important}.editora-toolbar-separator{width:1px;height:24px;background:#ddd;margin:0 4px}.editora-theme-dark .editora-toolbar-separator{background:#4d596b}.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:#29323d;border-color:#4d596b;box-shadow:0 8px 20px #00000073}.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:#d7deea}.editora-toolbar-dropdown-item:hover{background:#f5f5f5}.editora-theme-dark .editora-toolbar-dropdown-item:hover{background:#3a4554;color:#f0f6ff}.editora-content{flex:1;min-height:200px;padding:16px;outline:none;overflow-y:auto;line-height:1.6}.editora-theme-dark .editora-content{color:#ecf3ff;background:linear-gradient(180deg,var(--editora-dark-content) 0%,#1c232e 100%)}.editora-content:empty:before{content:attr(data-placeholder);color:#999;pointer-events:none}.editora-theme-dark .editora-content:empty:before{color:#8f9bb0}.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-theme-dark .editora-content,.editora-theme-dark .editora-content :is(p,span,div,li,ul,ol,td,th,h1,h2,h3,h4,h5,h6,strong,em,u,s,small,sub,sup,blockquote,code,pre,a){color:#ecf3ff}.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:#ecf3ff}.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-theme-dark .rte-code-block{background:linear-gradient(180deg,#212a36,#1b2430)!important;border-color:#4f5b70!important;color:#e7effc!important}.editora-theme-dark .rte-code-block code{color:#e7effc!important}.editora-theme-dark .rte-code-block:before{background:#111927!important;color:#dce8ff!important}.editora-theme-dark .rte-code-block .rte-code-copy{background:#2b3441!important;border-color:#5a667b!important;color:#dce8ff!important}.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:#ecf3ff}.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:#29323d;border-color:#4d596b;box-shadow:0 8px 20px #00000073}.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:linear-gradient(180deg,#2c3440,#252d37);border-top-color:#3f4a5b;color:#d7deea}.editora-statusbar-item{white-space:nowrap}.editora-statusbar-separator{color:#ddd}.editora-theme-dark .editora-statusbar-separator{color:#566275}.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}}';
let y;
const Q = "__editoraCommandEditorRoot", Z = "__editoraLastCommandButton", S = "editora-editor, [data-editora-editor], .rte-editor, .editora-editor", T = ".rte-content, .editora-content", C = /* @__PURE__ */ new Set();
let g = null, A = !1, k = null, w = null;
function L(s) {
  if (!(s instanceof HTMLElement)) return !1;
  const t = s;
  return typeof t.execCommand == "function" && (t.tagName.toLowerCase() === "editora-editor" || t.classList.contains("editora-editor") || t.hasAttribute("data-editora-editor"));
}
function tt(s) {
  return s ? s.nodeType === Node.ELEMENT_NODE ? s : s.parentElement : null;
}
function b(s) {
  if (!s) return null;
  if (L(s))
    return s;
  const t = s.matches(S) ? s : s.closest(S);
  return !t || !L(t) ? null : t;
}
function et() {
  var n;
  if (typeof window == "undefined") return null;
  const s = window[Q];
  if (s instanceof HTMLElement) {
    const i = b(s);
    if (i) return i;
    const r = s.matches(T) ? s : s.querySelector(T);
    if (r) {
      const a = b(r);
      if (a) return a;
    }
  }
  const t = window[Z];
  if (t instanceof HTMLElement) {
    const i = b(t);
    if (i) return i;
  }
  const e = document.activeElement;
  if (e) {
    const i = b(e);
    if (i) return i;
  }
  const o = (n = window.getSelection) == null ? void 0 : n.call(window);
  if (o && o.rangeCount > 0) {
    const i = b(tt(o.getRangeAt(0).startContainer));
    if (i) return i;
  }
  if (g && g.isConnected)
    return g;
  for (const i of C)
    if (i.isConnected) return i;
  return null;
}
function ot() {
  if (typeof window == "undefined" || A) return;
  k = typeof window.executeEditorCommand == "function" ? window.executeEditorCommand.bind(window) : null, w = typeof window.execEditorCommand == "function" ? window.execEditorCommand.bind(window) : null;
  const s = (t, e) => {
    const o = et();
    return o ? o.execCommand(t, e) : k ? k(t, e) : w ? w(t, e) : !1;
  };
  window.executeEditorCommand = s, window.execEditorCommand = s, A = !0;
}
function it() {
  const s = "editora-webcomponent-styles";
  if (!document.getElementById(s)) {
    const t = document.createElement("style");
    t.id = s, t.textContent = J, document.head.appendChild(t);
  }
}
function D() {
  if (!y) {
    const s = m.__globalPluginLoader;
    s ? y = s : y = new K();
  }
  return y;
}
function nt(s) {
  const t = D();
  Object.entries(s).forEach(([e, o]) => {
    t.register(e, o);
  });
}
class m extends HTMLElement {
  constructor() {
    if (super(), this.pluginLoader = D(), this.config = {}, this.isInitialized = !1, this.keyboardShortcutManager = new O(), this.lastAutosavedContent = "", this.loadedPlugins = [], this.lastBeforeInputType = null, it(), !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",
      "toolbar-floating",
      "toolbar-sticky",
      "readonly",
      "disabled",
      "theme",
      "placeholder",
      "autofocus",
      "autosave",
      "autosave-enabled",
      "autosave-interval-ms",
      "autosave-storage-key",
      "autosave-provider",
      "autosave-api-url",
      "accessibility",
      "accessibility-enable-aria",
      "accessibility-keyboard-navigation",
      "accessibility-checker",
      "performance",
      "performance-debounce-input-ms",
      "performance-viewport-only-scan",
      "language",
      "language-locale",
      "language-direction",
      "spellcheck",
      "spellcheck-enabled",
      "spellcheck-provider",
      "context-menu",
      "context-menu-enabled",
      "paste",
      "paste-clean",
      "paste-keep-formatting",
      "paste-convert-word",
      "security",
      "security-sanitize-on-paste",
      "security-sanitize-on-input",
      "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 (m.__globalPluginLoader) {
      this.pluginLoader = m.__globalPluginLoader;
      return;
    }
    return new Promise((t) => {
      const e = () => {
        m.__globalPluginLoader ? (this.pluginLoader = m.__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() {
    var o;
    if (this.querySelector(".editora-toolbar") || this.isInitialized) return;
    this.setAttribute("data-editora-editor", "true"), C.add(this), g || (g = this), ot(), 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();
    this.loadedPlugins = t, t.forEach((n) => {
      if (n.init && typeof n.init == "function")
        try {
          n.init({ editorElement: this });
        } catch (i) {
          console.error(`[RichTextEditor] Error initializing plugin ${n.name}:`, i);
        }
    });
    const e = (o = this.restoreAutosavedContent()) != null ? o : this.getAttribute("data-initial-content") || "";
    this.engine = new z({
      content: e,
      plugins: t,
      readonly: this.config.readonly
    }), this.createUI(t, e), this.setupEventListeners(), this.startAutosave(), 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 = [], e = this.config.plugins && (typeof this.config.plugins == "string" && this.config.plugins.length > 0 || Array.isArray(this.config.plugins) && this.config.plugins.length > 0), n = this.getAccessibilityConfig().checker === !0;
    if (e) {
      if (typeof this.config.plugins == "string") {
        const i = this.config.plugins.split(/\s+/).filter(Boolean);
        n && !i.includes("a11yChecker") && i.push("a11yChecker");
        for (const r of i) {
          const a = await this.pluginLoader.load(r, this.getPluginLoadConfig(r));
          a && t.push(a);
        }
      } else if (Array.isArray(this.config.plugins)) {
        for (const i of this.config.plugins)
          if (typeof i == "string") {
            const r = await this.pluginLoader.load(i, this.getPluginLoadConfig(i));
            r && t.push(r);
          } else
            t.push(i);
        if (n && !t.some((i) => (i == null ? void 0 : i.name) === "a11yChecker")) {
          const i = await this.pluginLoader.load("a11yChecker", this.getPluginLoadConfig("a11yChecker"));
          i && t.push(i);
        }
      }
    } else {
      const i = this.pluginLoader.getRegisteredPluginNames();
      for (const r of i) {
        const a = await this.pluginLoader.load(r, this.getPluginLoadConfig(r));
        a && t.push(a);
      }
    }
    return t;
  }
  resolveToolbarItems() {
    const t = this.config.toolbarItems;
    if (typeof t == "string") return t;
    if (Array.isArray(t)) return t.join(" ");
    const e = this.config.toolbar;
    if (typeof e == "string") return e;
    if (!e || typeof e != "object") return;
    const o = e.items;
    if (typeof o == "string") return o;
    if (Array.isArray(o)) return o.join(" ");
  }
  isToolbarStickyEnabled() {
    const t = this.config.toolbar;
    return !t || typeof t != "object" ? !1 : !!t.sticky;
  }
  isToolbarFloatingEnabled() {
    const t = this.config.toolbar;
    return !t || typeof t != "object" ? !1 : !!t.floating;
  }
  isStatusbarEnabled() {
    const t = this.config.statusbar;
    return typeof t == "boolean" ? t : t && typeof t == "object" ? t.enabled !== !1 : !1;
  }
  getStatusbarPosition() {
    const t = this.config.statusbar;
    return t && typeof t == "object" && t.position === "top" ? "top" : "bottom";
  }
  getLanguageConfig() {
    const t = this.config.language;
    return typeof t == "string" ? { locale: t, direction: "ltr" } : t && typeof t == "object" ? {
      locale: t.locale || "en",
      direction: t.direction === "rtl" ? "rtl" : "ltr"
    } : { locale: "en", direction: "ltr" };
  }
  getAccessibilityConfig() {
    const t = this.config.accessibility;
    return typeof t == "boolean" ? {
      enableARIA: t,
      keyboardNavigation: t,
      checker: !1
    } : t && typeof t == "object" ? {
      enableARIA: t.enableARIA !== !1,
      keyboardNavigation: t.keyboardNavigation !== !1,
      checker: !!t.checker
    } : {
      enableARIA: !0,
      keyboardNavigation: !0,
      checker: !1
    };
  }
  getPerformanceConfig() {
    var e;
    const t = this.config.performance;
    if (typeof t == "boolean")
      return {
        debounceInputMs: 100,
        viewportOnlyScan: t
      };
    if (t && typeof t == "object") {
      const o = Number((e = t.debounceInputMs) != null ? e : 100);
      return {
        debounceInputMs: Number.isFinite(o) && o >= 0 ? o : 100,
        viewportOnlyScan: t.viewportOnlyScan !== !1
      };
    }
    return {
      debounceInputMs: 100,
      viewportOnlyScan: !0
    };
  }
  isEditorInViewport() {
    if (!this.contentElement || typeof window == "undefined") return !0;
    const t = this.contentElement.getBoundingClientRect();
    return t.bottom >= 0 && t.top <= window.innerHeight;
  }
  applyAccessibilitySettings() {
    if (!this.contentElement) return;
    const t = this.getAccessibilityConfig();
    if (t.enableARIA) {
      this.contentElement.setAttribute("role", "textbox"), this.contentElement.setAttribute("aria-multiline", "true"), this.contentElement.setAttribute("aria-disabled", this.config.readonly ? "true" : "false");
      const e = typeof this.config.placeholder == "string" ? this.config.placeholder.trim() : "";
      e ? this.contentElement.setAttribute("aria-label", e) : this.contentElement.removeAttribute("aria-label");
    } else
      this.contentElement.removeAttribute("role"), this.contentElement.removeAttribute("aria-multiline"), this.contentElement.removeAttribute("aria-disabled"), this.contentElement.removeAttribute("aria-label");
    this.contentElement.tabIndex = t.keyboardNavigation ? 0 : -1;
  }
  applyLanguageSettings() {
    if (!this.contentElement) return;
    const t = this.getLanguageConfig();
    this.contentElement.setAttribute("lang", t.locale), this.contentElement.setAttribute("dir", t.direction);
  }
  getSpellcheckConfig() {
    const t = this.config.spellcheck;
    if (typeof t == "boolean")
      return {
        enabled: t,
        provider: "browser"
      };
    if (t && typeof t == "object") {
      const e = t.provider || "browser";
      return {
        enabled: !!t.enabled,
        provider: e,
        mode: t.mode
      };
    }
    return { enabled: !1, provider: "browser" };
  }
  applySpellcheckSettings() {
    if (!this.contentElement) return;
    const t = this.getSpellcheckConfig(), e = t.enabled && t.provider === "browser";
    this.contentElement.spellcheck = e, this.contentElement.setAttribute("spellcheck", e ? "true" : "false");
  }
  executeCommand(t, e) {
    var i;
    typeof window != "undefined" && (window.__editoraCommandEditorRoot = this);
    const o = {
      editorElement: this,
      contentElement: this.contentElement,
      toolbarElement: this.toolbarElement
    }, n = this.loadedPlugins.find((r) => r.commands && r.commands[t]);
    if (n && n.commands) {
      const r = n.commands[t];
      if (typeof r == "function")
        try {
          return r(t === "toggleFullscreen" ? this : e, o), !0;
        } catch (a) {
          return console.error(`[RichTextEditor] Error executing native command ${t}:`, a), !1;
        }
    }
    return ((i = this.engine) == null ? void 0 : i.execCommand(t, e)) || !1;
  }
  getPluginLoadConfig(t) {
    const e = this.config.pluginConfig;
    if (e && typeof e == "object") {
      const i = e[t];
      if (i && typeof i == "object")
        return i;
    }
    const o = {
      spellCheck: ["spellcheck", "spellCheck"],
      trackChanges: ["trackchanges", "track-changes", "trackChanges"],
      versionDiff: ["versiondiff", "version-diff", "versionDiff"],
      "version-diff": ["versiondiff", "version-diff", "versionDiff"],
      conditionalContent: ["conditionalcontent", "conditional-content", "conditionalContent"],
      "conditional-content": ["conditionalcontent", "conditional-content", "conditionalContent"],
      dataBinding: ["databinding", "data-binding", "dataBinding"],
      "data-binding": ["databinding", "data-binding", "dataBinding"],
      contentRules: ["contentrules", "content-rules", "contentRules"],
      "content-rules": ["contentrules", "content-rules", "contentRules"],
      mentions: ["mention", "mentions"],
      mention: ["mention", "mentions"],
      slashCommands: ["slashcommands", "slash-commands", "slashCommands"],
      "slash-commands": ["slashcommands", "slash-commands", "slashCommands"],
      formatPainter: ["formatpainter", "format-painter", "formatPainter"],
      "format-painter": ["formatpainter", "format-painter", "formatPainter"]
    }, n = [
      t,
      t.toLowerCase(),
      ...o[t] || []
    ];
    for (const i of n) {
      const r = this.config[i];
      if (r && typeof r == "object" && !Array.isArray(r))
        return r;
    }
  }
  getContentSanitizeConfig() {
    const t = this.config.contentConfig;
    return t && typeof t == "object" ? t : { sanitize: !0 };
  }
  getSecurityConfig() {
    const t = this.config.security;
    return t && typeof t == "object" ? t : { sanitizeOnPaste: !0, sanitizeOnInput: !0 };
  }
  getAutosaveConfig() {
    var e, o;
    const t = this.config.autosave;
    if (typeof t == "boolean")
      return {
        enabled: t,
        intervalMs: 3e4,
        storageKey: "rte-autosave",
        provider: "localStorage"
      };
    if (t && typeof t == "object") {
      const n = Number((o = (e = t.intervalMs) != null ? e : t.interval) != null ? o : 3e4);
      return {
        enabled: !!t.enabled,
        intervalMs: Number.isFinite(n) && n > 0 ? n : 3e4,
        storageKey: String(t.storageKey || "rte-autosave"),
        provider: t.provider || "localStorage",
        apiUrl: t.apiUrl
      };
    }
    return {
      enabled: !1,
      intervalMs: 3e4,
      storageKey: "rte-autosave",
      provider: "localStorage"
    };
  }
  persistAutosave(t) {
    const e = this.getAutosaveConfig();
    if (e.enabled && t !== this.lastAutosavedContent) {
      if (this.lastAutosavedContent = t, e.provider === "localStorage") {
        try {
          localStorage.setItem(e.storageKey, t), localStorage.setItem(`${e.storageKey}-timestamp`, Date.now().toString());
        } catch (o) {
          console.error("[RichTextEditor] Failed to save autosave content to localStorage:", o);
        }
        return;
      }
      e.provider === "api" && e.apiUrl && fetch(e.apiUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content: t, timestamp: Date.now() })
      }).catch((o) => {
        console.error("[RichTextEditor] Failed to save autosave content to API:", o);
      });
    }
  }
  restoreAutosavedContent() {
    const t = this.getAutosaveConfig();
    if (!t.enabled || t.provider !== "localStorage") return null;
    try {
      const e = localStorage.getItem(t.storageKey);
      if (e)
        return this.lastAutosavedContent = e, e;
    } catch (e) {
      console.error("[RichTextEditor] Failed to restore autosaved content:", e);
    }
    return null;
  }
  stopAutosave() {
    this.autosaveTimer && (clearInterval(this.autosaveTimer), this.autosaveTimer = void 0);
  }
  startAutosave() {
    this.stopAutosave();
    const t = this.getAutosaveConfig();
    !t.enabled || !this.contentElement || (this.autosaveTimer = setInterval(() => {
      var e;
      this.persistAutosave(((e = this.contentElement) == null ? void 0 : e.innerHTML) || "");
    }, t.intervalMs));
  }
  insertHTMLAtSelection(t) {
    if (!this.contentElement) return;
    const e = window.getSelection();
    if (e && e.rangeCount > 0) {
      const o = e.getRangeAt(0);
      o.deleteContents();
      const n = document.createElement("div");
      n.innerHTML = t;
      const i = document.createDocumentFragment();
      for (; n.firstChild; )
        i.appendChild(n.firstChild);
      o.insertNode(i), o.collapse(!1), e.removeAllRanges(), e.addRange(o);
    } else
      this.contentElement.focus(), document.execCommand("insertHTML", !1, t);
  }
  /**
   * Create UI elements
   */
  createUI(t, e) {
    const o = this.querySelector('[slot="toolbar"]'), n = this.querySelector('[slot="statusbar"]');
    this.innerHTML = "", this.config.toolbar !== !1 && !o ? (this.toolbarElement = document.createElement("div"), this.toolbarElement.className = "editora-toolbar-container", this.appendChild(this.toolbarElement), this.toolbar = new R(
      {
        items: this.resolveToolbarItems(),
        sticky: this.isToolbarStickyEnabled(),
        position: "top"
      },
      t,
      this.pluginLoader
      // Pass plugin loader to get all registered plugins
    ), this.toolbar.setCommandHandler((i, r) => {
      var a;
      if (this.contentElement) {
        this.contentElement.focus();
        const l = window.getSelection();
        if (!l || l.rangeCount === 0 || !this.contentElement.contains(l.anchorNode)) {
          const c = document.createRange(), d = this.contentElement.lastChild || this.contentElement;
          d.nodeType === Node.TEXT_NODE ? c.setStart(d, ((a = d.textContent) == null ? void 0 : a.length) || 0) : d.nodeType === Node.ELEMENT_NODE ? (c.selectNodeContents(d), c.collapse(!1)) : c.setStart(this.contentElement, 0), c.collapse(!0), l == null || l.removeAllRanges(), l == null || l.addRange(c);
        }
      }
      return this.executeCommand(i, r);
    }), this.toolbar.render(this.toolbarElement)) : 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.applyLanguageSettings(), this.applyAccessibilitySettings(), this.applySpellcheckSettings(), 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((a) => {
        if (a.nodeType === Node.ELEMENT_NODE) {
          const l = a.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.isToolbarFloatingEnabled() && (this.floatingToolbar = new H({ enabled: !0 }), this.floatingToolbar.create(this)), n ? this.appendChild(n) : this.isStatusbarEnabled() && (this.statusBarElement = document.createElement("div"), this.statusBarElement.className = "editora-statusbar-container", this.appendChild(this.statusBarElement), this.statusBar = new j({ position: this.getStatusbarPosition() }), 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;
    const t = this.keyboardShortcutManager;
    this.contentElement.addEventListener("beforeinput", (o) => {
      this.lastBeforeInputType = o.inputType || null;
    }), this.contentElement.addEventListener("input", () => {
      if (!this.contentElement) return;
      let o = this.contentElement.innerHTML;
      const n = this.getPerformanceConfig(), i = this.getContentSanitizeConfig(), r = this.getSecurityConfig(), a = this.lastBeforeInputType;
      if (this.lastBeforeInputType = null, r.sanitizeOnInput !== !1 && i.sanitize !== !1 && !a) {
        const d = Y(o, i, r);
        if (d !== o) {
          const h = window.getSelection(), p = h && h.rangeCount > 0 ? h.getRangeAt(0) : null;
          if (this.contentElement.innerHTML = d, p && h)
            try {
              h.removeAllRanges(), h.addRange(p);
            } catch (u) {
            }
          o = d;
        }
      }
      this.contentChangeDebounceTimer && clearTimeout(this.contentChangeDebounceTimer);
      const c = () => {
        this.dispatchEvent(new CustomEvent("content-change", {
          detail: { html: o },
          bubbles: !0
        }));
      };
      n.debounceInputMs > 0 ? this.contentChangeDebounceTimer = setTimeout(c, n.debounceInputMs) : c(), this.updateStatusBar();
    }), this.contentElement.addEventListener("contextmenu", (o) => {
      const n = this.config.contextMenu;
      (n === !1 || typeof n == "object" && n !== null && n.enabled === !1) && o.preventDefault();
    }), this.contentElement.addEventListener("paste", (o) => {
      var d, h;
      if (o.__editoraSmartPasteHandled === !0 || o.defaultPrevented)
        return;
      o.preventDefault();
      const n = this.config.paste || {};
      let i = ((d = o.clipboardData) == null ? void 0 : d.getData("text/html")) || "";
      const r = ((h = o.clipboardData) == null ? void 0 : h.getData("text/plain")) || "", a = this.getContentSanitizeConfig(), l = this.getSecurityConfig(), c = !!i && /class=["'][^"']*Mso|xmlns:w=|urn:schemas-microsoft-com:office/i.test(i);
      if ((n.clean || !n.keepFormatting) && r) {
        document.execCommand("insertText", !1, r);
        return;
      }
      if (n.convertWord === !1 && c && r) {
        document.execCommand("insertText", !1, r);
        return;
      }
      if (i) {
        l.sanitizeOnPaste !== !1 && a.sanitize !== !1 && (i = X(i, a, l)), this.insertHTMLAtSelection(i);
        return;
      }
      r && document.execCommand("insertText", !1, r);
    }), this.contentElement.addEventListener("focus", () => {
      g = this, this.dispatchEvent(new Event("editor-focus", { bubbles: !0 })), this.updateStatusBar();
    }), this.contentElement.addEventListener("blur", () => {
      this.contentChangeDebounceTimer && (clearTimeout(this.contentChangeDebounceTimer), this.contentChangeDebounceTimer = void 0), this.contentElement && this.dispatchEvent(new CustomEvent("content-change", {
        detail: { html: this.contentElement.innerHTML },
        bubbles: !0
      })), this.dispatchEvent(new Event("editor-blur", { bubbles: !0 })), this.updateFloatingToolbar(), this.updateStatusBar();
    }), this.contentElement.addEventListener("keydown", (o) => {
      this.getAccessibilityConfig().keyboardNavigation && t.handleKeyDown(o, (i, r) => {
        this.executeCommand(i, r);
      });
    });
    const e = () => {
      const o = this.getSelectionRangeInEditor(), n = document.activeElement, i = !!n && !!this.contentElement && (n === this.contentElement || this.contentElement.contains(n));
      this.getPerformanceConfig().viewportOnlyScan && !this.isEditorInViewport() && !i || !o && !i || (this.updateFloatingToolbar(), this.updateStatusBar());
    };
    this.selectionChangeHandler = e, document.addEventListener("selectionchange", this.selectionChangeHandler);
  }
  getSelectionRangeInEditor() {
    if (!this.contentElement) return null;
    const t = window.getSelection();
    if (!t || t.rangeCount === 0)
      return null;
    const e = t.getRangeAt(0), o = e.commonAncestorContainer;
    return this.contentElement.contains(o) ? e : null;
  }
  isSelectionBackward(t) {
    if (!t.anchorNode || !t.focusNode) return !1;
    try {
      const e = document.createRange();
      return e.setStart(t.anchorNode, t.anchorOffset), e.setEnd(t.focusNode, t.focusOffset), e.collapsed;
    } catch (e) {
      return !1;
    }
  }
  getSelectionAnchorRect(t, e) {
    const o = Array.from(e.getClientRects()).filter((i) => i.width > 0 || i.height > 0);
    return o.length === 0 ? e.getBoundingClientRect() : this.isSelectionBackward(t) ? o[0] : o[o.length - 1];
  }
  /**
   * Update floating toolbar position
   */
  updateFloatingToolbar() {
    if (!this.floatingToolbar || !this.contentElement) return;
    if (this.config.readonly || this.contentElement.contentEditable === "false" || this.contentElement.getAttribute("data-readonly") === "true" || this.getAttribute("readonly") === "true" || this.getAttribute("data-readonly") === "true") {
      this.floatingToolbar.hide();
      return;
    }
    const e = this.getPerformanceConfig(), o = document.activeElement === this.contentElement || !!this.contentElement && this.contentElement.contains(document.activeElement);
    if (e.viewportOnlyScan && !this.isEditorInViewport() && !o) {
      this.floatingToolbar.hide();
      return;
    }
    const n = this.getSelectionRangeInEditor();
    if (!n) {
      this.floatingToolbar.hide();
      return;
    }
    if (n.collapsed) {
      this.floatingToolbar.hide();
      return;
    }
    const i = window.getSelection();
    if (!i) {
      this.floatingToolbar.hide();
      return;
    }
    const r = this.getSelectionAnchorRect(i, n);
    if (!r) {
      this.floatingToolbar.hide();
      return;
    }
    this.floatingToolbar.show(r.left, r.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.getPerformanceConfig(), e = document.activeElement === this.contentElement || this.contentElement.contains(document.activeElement);
    if (t.viewportOnlyScan && !this.isEditorInViewport() && !e)
      return;
    const o = this.contentElement.textContent || "", { words: n, chars: i } = W(o), r = _(this.contentElement);
    let a, l;
    const c = this.getSelectionRangeInEditor();
    c && (a = F(this.contentElement, c), c.collapsed || (l = U(c, a), a = void 0)), this.statusBar.update({
      wordCount: n,
      charCount: i,
      lineCount: r,
      cursorPosition: a,
      selectionInfo: l
    });
  }
  /**
   * Handle attribute changes
   */
  handleAttributeChange(t, e) {
    switch (t) {
      case "readonly":
        this.contentElement && (this.contentElement.contentEditable = e === "true" ? "false" : "true", this.applyAccessibilitySettings()), 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), this.applyAccessibilitySettings());
        break;
      case "accessibility":
      case "accessibility-enable-aria":
      case "accessibility-keyboard-navigation":
      case "accessibility-checker":
        this.applyAccessibilitySettings();
        break;
      case "performance":
      case "performance-debounce-input-ms":
      case "performance-viewport-only-scan":
        break;
      case "language":
      case "language-locale":
      case "language-direction":
        this.applyLanguageSettings();
        break;
      case "spellcheck":
      case "spellcheck-enabled":
      case "spellcheck-provider":
        this.applySpellcheckSettings();
        break;
      case "autosave":
      case "autosave-enabled":
      case "autosave-interval-ms":
      case "autosave-storage-key":
      case "autosave-provider":
      case "autosave-api-url":
        this.startAutosave();
        break;
      case "security":
      case "security-sanitize-on-paste":
      case "security-sanitize-on-input":
      case "paste":
      case "paste-clean":
      case "paste-keep-formatting":
      case "paste-convert-word":
      case "context-menu":
      case "context-menu-enabled":
        break;
      case "toolbar":
      case "toolbar-items":
      case "toolbar-floating":
      case "toolbar-sticky":
      case "plugins":
      case "statusbar":
        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) => this.executeCommand(t, e),
      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, n;
    this.contentChangeDebounceTimer && (clearTimeout(this.contentChangeDebounceTimer), this.contentChangeDebounceTimer = void 0), this.contentElement && this.persistAutosave(this.contentElement.innerHTML || ""), this.stopAutosave(), this.selectionChangeHandler && (document.removeEventListener("selectionchange", this.selectionChangeHandler), this.selectionChangeHandler = void 0), (t = this.engine) == null || t.destroy(), (e = this.toolbar) == null || e.destroy(), (o = this.floatingToolbar) == null || o.destroy(), (n = this.statusBar) == null || n.destroy(), this.innerHTML = "", this.contentElement = void 0, this.toolbarElement = void 0, this.statusBarElement = void 0, this.loadedPlugins = [], this.isInitialized = !1, C.delete(this), g === this && (g = null), 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) {
    return this.executeCommand(t, e);
  }
  focus() {
    var t;
    (t = this.contentElement) == null || t.focus();
  }
  blur() {
    var t;
    (t = this.contentElement) == null || t.blur();
  }
}
export {
  B as C,
  v as E,
  H as F,
  O as K,
  N as P,
  m as R,
  P as S,
  R as T,
  z as a,
  j as b,
  $ as c,
  _ as d,
  W as e,
  U as f,
  F as g,
  x as h,
  K as i,
  nt as j
};
//# sourceMappingURL=index-YZ5TROdg.mjs.map
