/**
 * Integration script: replaces the live-edit textarea with MarkdownWYSIWYG editor.
 * Runs after mkdocs-live-edit-plugin. Uses MutationObserver to detect when
 * the .live-edit-source textarea appears, then replaces it with the WYSIWYG editor.
 * Patches the editor to support MkDocs admonitions (!!! note) in HTML mode.
 * Patches PRE/code block handling to prevent text loss when contenteditable
 * splits blocks (e.g. DIV children) during editing before switching to markdown mode.
 * Patches _htmlToMarkdown to preserve extra newlines inside code blocks when collapsing
 * multiple blank lines in the final output.
 * Patches text node handling to preserve multiple spaces (e.g. "Foo.  Bar", leading spaces).
 * Uses a preprocessor/postprocessor to preserve all markdown link styles (inline, reference,
 * shortcut) exactly as the original author intended when loading, saving, and switching modes.
 * Preserves unordered list markers (*, -, +) when content is unchanged; new/modified lists use '-'.
 */
(function () {
  if (typeof MarkdownWYSIWYG === 'undefined') {
    console.warn('live-wysiwyg: MarkdownWYSIWYG not loaded, falling back to plain textarea');
    return;
  }

  function resolveImageSrc(href) {
    if (!href) return href;
    if (/^(?:https?:\/\/|\/|data:)/.test(href)) return href;
    try {
      var parentDir = new URL('..', document.baseURI).href;
      return new URL(href, parentDir).pathname;
    } catch (e) { return href; }
  }

  function computeRelativeImagePath(pageSrcPath, imageSrcPath) {
    if (!pageSrcPath || !imageSrcPath) return imageSrcPath || '';
    var pageParts = pageSrcPath.replace(/\\/g, '/').split('/');
    pageParts.pop();
    var imgParts = imageSrcPath.replace(/\\/g, '/').split('/');
    var common = 0;
    while (common < pageParts.length && common < imgParts.length - 1 &&
           pageParts[common] === imgParts[common]) {
      common++;
    }
    var ups = pageParts.length - common;
    var segments = [];
    for (var i = 0; i < ups; i++) segments.push('..');
    for (var j = common; j < imgParts.length; j++) segments.push(imgParts[j]);
    return segments.join('/');
  }

  (function registerCodeBlockRenderer() {
    if (typeof marked === 'undefined') return;
    function parseInfoString(info) {
      var result = { lang: '', attrs: {} };
      if (!info) return result;
      info = info.trim();
      var langMatch = info.match(/^(\S+)/);
      if (langMatch) result.lang = langMatch[1];
      var attrRe = /(\w+)="([^"]*)"/g;
      var m;
      while ((m = attrRe.exec(info)) !== null) {
        result.attrs[m[1]] = m[2];
      }
      if (result.lang && result.lang.indexOf('=') !== -1) result.lang = '';
      return result;
    }
    marked.use({
      renderer: {
        code: function (token) {
          var info = parseInfoString(token.lang);
          var lang = info.lang;
          var escaped = (token.text || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
          var attrs = '';
          if (lang) attrs += ' data-lang="' + lang + '"';
          if (info.attrs.title) attrs += ' data-title="' + info.attrs.title.replace(/"/g, '&quot;') + '"';
          if (info.attrs.linenums) attrs += ' data-linenums="' + info.attrs.linenums + '"';
          if (info.attrs.hl_lines) attrs += ' data-hl-lines="' + info.attrs.hl_lines + '"';
          var codeClass = lang ? ' class="language-' + lang + '"' : '';
          return '<pre' + attrs + '><code' + codeClass + '>' + escaped + '</code></pre>\n';
        },
        image: function (token) {
          var href = token.href || '';
          var text = token.text || '';
          var title = token.title || '';
          var resolved = resolveImageSrc(href);
          var dataOrigSrc = (resolved !== href) ? ' data-orig-src="' + href.replace(/"/g, '&quot;') + '"' : '';
          var titleAttr = title ? ' title="' + title.replace(/"/g, '&quot;') + '"' : '';
          return '<img src="' + resolved.replace(/"/g, '&quot;') + '" alt="' + text.replace(/"/g, '&quot;') + '"' + titleAttr + dataOrigSrc + '>';
        }
      }
    });
  })();

  /**
   * Ensure new list items in a checklist get a checkbox. When user presses Enter in a
   * checklist item, the browser creates a new LI without a checkbox. This adds one.
   */
  function ensureChecklistNewItems(editableArea) {
    if (!editableArea) return;
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return;
    var range = sel.getRangeAt(0);
    var node = range.startContainer;
    if (node.nodeType === 3) node = node.parentNode;
    var li = node;
    while (li && li !== editableArea) {
      if (li.nodeName === 'LI') break;
      li = li.parentNode;
    }
    if (!li || li.parentNode.nodeName !== 'UL') return;
    var ul = li.parentNode;
    var hasCheckbox = ul.querySelector('li input[type="checkbox"]');
    if (!hasCheckbox) return;
    var firstChild = li.firstChild;
    while (firstChild && firstChild.nodeType === 3 && !firstChild.textContent.trim()) firstChild = firstChild.nextSibling;
    if (firstChild && firstChild.nodeName === 'INPUT' && firstChild.type === 'checkbox') return;
    var prevLi = li.previousElementSibling;
    var prevChecked = false;
    if (prevLi && prevLi.nodeName === 'LI') {
      var prevCb = getDirectCheckboxOfLi(prevLi);
      if (prevCb) prevChecked = prevCb.checked;
    }
    var cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.checked = prevChecked;
    if (prevChecked) cb.setAttribute('checked', '');
    cb.setAttribute('data-live-wysiwyg-checklist', '1');
    cb.setAttribute('contenteditable', 'false');
    (function (checkbox) {
      function onCheckboxMouseDown(e) {
        if (e.target !== checkbox) return;
        e.preventDefault();
        e.stopPropagation();
        checkbox.checked = !checkbox.checked;
        if (checkbox.checked) checkbox.setAttribute('checked', '');
        else checkbox.removeAttribute('checked');
        var editable = checkbox.closest && checkbox.closest('[contenteditable="true"]');
        if (editable && editable.dispatchEvent) {
          editable.dispatchEvent(new Event('input', { bubbles: true }));
        }
      }
      function onCheckboxClick(e) {
        if (e.target !== checkbox) return;
        e.preventDefault();
        e.stopPropagation();
      }
      checkbox.addEventListener('mousedown', onCheckboxMouseDown, true);
      checkbox.addEventListener('click', onCheckboxClick, true);
    })(cb);
    var savedNode = range.startContainer;
    var savedOffset = range.startOffset;

    var space = document.createTextNode(' ');
    li.insertBefore(space, li.firstChild);
    li.insertBefore(cb, space);

    var cursorBeforeCb = (savedNode === li && savedOffset <= 2) ||
        savedNode === cb || savedNode === space;
    var newRange = document.createRange();
    try {
      if (cursorBeforeCb) {
        newRange.setStart(space, 1);
      } else {
        newRange.setStart(savedNode, savedOffset);
      }
    } catch (ex) {
      newRange.setStart(space, 1);
    }
    newRange.collapse(true);
    sel.removeAllRanges();
    sel.addRange(newRange);
  }

  /**
   * Fix malformed nested lists: when indent creates UL/OL as sibling of LI instead of
   * child, move the list into the previous LI so markdown indentation persists.
   */
  function fixMalformedNestedLists(editableArea) {
    if (!editableArea) return;
    var changed;
    do {
      changed = false;
      var lists = editableArea.querySelectorAll('ul, ol');
      for (var i = 0; i < lists.length; i++) {
        var list = lists[i];
        var parent = list.parentNode;
        if (!parent || (parent.nodeName !== 'UL' && parent.nodeName !== 'OL')) continue;
        var prev = list.previousSibling;
        while (prev && prev.nodeType !== 1) prev = prev.previousSibling;
        if (prev && prev.nodeName === 'LI') {
          prev.appendChild(list);
          changed = true;
          break;
        }
      }
    } while (changed);
  }

  /**
   * Enhance checklist items: make checkboxes clickable and toggle on click.
   * Checkboxes are rendered by marked (GFM task lists) as disabled; we remove disabled
   * and add a handler to toggle checked state. Uses mousedown in capture phase so we
   * intercept before contenteditable handles the event (which can block checkbox toggling).
   */
  function enhanceChecklists(editableArea) {
    if (!editableArea) return;
    var checkboxes = editableArea.querySelectorAll('li input[type="checkbox"]');
    for (var i = 0; i < checkboxes.length; i++) {
      var cb = checkboxes[i];
      if (cb.getAttribute('data-live-wysiwyg-checklist') === '1') continue;
      cb.setAttribute('data-live-wysiwyg-checklist', '1');
      cb.removeAttribute('disabled');
      cb.setAttribute('contenteditable', 'false');
      (function (checkbox) {
        function onCheckboxMouseDown(e) {
          if (e.target !== checkbox) return;
          e.preventDefault();
          e.stopPropagation();
          checkbox.checked = !checkbox.checked;
          if (checkbox.checked) checkbox.setAttribute('checked', '');
          else checkbox.removeAttribute('checked');
          var editable = checkbox.closest && checkbox.closest('[contenteditable="true"]');
          if (editable && editable.dispatchEvent) {
            editable.dispatchEvent(new Event('input', { bubbles: true }));
          }
        }
        function onCheckboxClick(e) {
          if (e.target !== checkbox) return;
          e.preventDefault();
          e.stopPropagation();
        }
        checkbox.addEventListener('mousedown', onCheckboxMouseDown, true);
        checkbox.addEventListener('click', onCheckboxClick, true);
      })(cb);
    }
  }

  var CODE_LANG_LIST = [
    'python', 'javascript', 'typescript', 'java', 'c', 'cpp', 'csharp',
    'go', 'rust', 'ruby', 'php', 'swift', 'kotlin', 'scala', 'bash',
    'shell', 'sql', 'html', 'css', 'json', 'yaml', 'xml', 'markdown',
    'dockerfile', 'terraform', 'lua', 'perl', 'r', 'matlab', 'groovy'
  ];

  var _indentSettingsCache = null;
  function getIndentSettings() {
    if (_indentSettingsCache) return _indentSettingsCache;
    var defaults = { enabled: true, type: 'space', size: 4 };
    try {
      var raw = _getSetting('liveWysiwygIndent');
      if (raw) {
        var parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
        defaults.enabled = typeof parsed.enabled === 'boolean' ? parsed.enabled : true;
        defaults.type = parsed.type === 'tab' ? 'tab' : 'space';
        defaults.size = [2, 4, 8].indexOf(parsed.size) !== -1 ? parsed.size : 4;
      }
    } catch (e) {}
    _indentSettingsCache = defaults;
    return defaults;
  }
  function setIndentSettings(settings) {
    _indentSettingsCache = settings;
    _setSetting('liveWysiwygIndent', settings);
  }

  var _activeSettingsDropdown = null;
  function dismissActiveSettingsDropdown() {
    if (_activeSettingsDropdown) {
      if (_activeSettingsDropdown.el.parentNode) _activeSettingsDropdown.el.parentNode.removeChild(_activeSettingsDropdown.el);
      if (_activeSettingsDropdown.closeHandler) document.removeEventListener('mousedown', _activeSettingsDropdown.closeHandler, true);
      if (_activeSettingsDropdown.scrollHandler) window.removeEventListener('scroll', _activeSettingsDropdown.scrollHandler, true);
      _activeSettingsDropdown = null;
    }
  }

  var _activeLangDropdown = null;

  function dismissActiveLangDropdown() {
    if (_activeLangDropdown) {
      if (_activeLangDropdown.el.parentNode) _activeLangDropdown.el.parentNode.removeChild(_activeLangDropdown.el);
      if (_activeLangDropdown.closeHandler) document.removeEventListener('mousedown', _activeLangDropdown.closeHandler, true);
      if (_activeLangDropdown.scrollHandler) window.removeEventListener('scroll', _activeLangDropdown.scrollHandler, true);
      _activeLangDropdown = null;
    }
  }

  function createLangDropdown(anchorBtn, currentLang, onSelect) {
    dismissActiveLangDropdown();
    var dropdown = document.createElement('div');
    dropdown.className = 'md-code-lang-dropdown';
    dropdown.setAttribute('contenteditable', 'false');
    var filter = document.createElement('input');
    filter.className = 'md-code-lang-filter';
    filter.type = 'text';
    filter.placeholder = 'Filter...';
    filter.value = currentLang || '';
    dropdown.appendChild(filter);
    var list = document.createElement('div');
    list.className = 'md-code-lang-list';
    dropdown.appendChild(list);
    function render(filterText) {
      list.innerHTML = '';
      var ft = (filterText || '').toLowerCase();
      var langs = CODE_LANG_LIST.filter(function (l) { return !ft || l.indexOf(ft) !== -1; });
      if (ft && langs.indexOf(ft) === -1 && ft.match(/^[a-z0-9_+#.-]+$/i)) {
        langs.unshift(ft);
      }
      for (var i = 0; i < langs.length; i++) {
        var item = document.createElement('div');
        item.className = 'md-code-lang-item';
        if (langs[i] === currentLang) item.classList.add('md-code-lang-item-active');
        item.textContent = langs[i];
        item.setAttribute('data-lang', langs[i]);
        list.appendChild(item);
      }
    }
    render(filter.value);
    filter.addEventListener('input', function () { render(filter.value); });
    function wrappedSelect(chosen) {
      dismissActiveLangDropdown();
      onSelect(chosen);
    }
    list.addEventListener('mousedown', function (e) {
      var item = e.target;
      if (!item.classList || !item.classList.contains('md-code-lang-item')) return;
      e.preventDefault();
      e.stopPropagation();
      wrappedSelect(item.getAttribute('data-lang'));
    });
    _attachDialogKeyboard(filter, {
      category: 'informational',
      onDismiss: function () { wrappedSelect(null); },
      onConfirm: function () {
        var first = list.querySelector('.md-code-lang-item');
        if (first) wrappedSelect(first.getAttribute('data-lang'));
      }
    });

    function positionDropdown() {
      var rect = anchorBtn.getBoundingClientRect();
      var left = rect.right - 180;
      if (left < 0) left = rect.left;
      dropdown.style.top = (rect.bottom + 2) + 'px';
      dropdown.style.left = left + 'px';
    }

    document.body.appendChild(dropdown);
    positionDropdown();

    var closeHandler = function (ev) {
      if (dropdown.contains(ev.target) || ev.target === anchorBtn) return;
      dismissActiveLangDropdown();
    };
    document.addEventListener('mousedown', closeHandler, true);

    var scrollHandler = function () { positionDropdown(); };
    window.addEventListener('scroll', scrollHandler, true);

    _activeLangDropdown = { el: dropdown, closeHandler: closeHandler, scrollHandler: scrollHandler };

    return { el: dropdown, focusFilter: function () { requestAnimationFrame(function () { filter.focus(); }); } };
  }

  function addLangButtonToBasicPre(pre, editableArea) {
    if (pre.querySelector('.md-code-lang-btn')) return;
    if (pre.parentNode && pre.parentNode.classList && pre.parentNode.classList.contains('md-code-block')) return;
    var btn = document.createElement('button');
    btn.className = 'md-code-lang-btn';
    btn.setAttribute('contenteditable', 'false');
    btn.textContent = 'lang';
    btn.type = 'button';
    pre.style.position = 'relative';
    pre.appendChild(btn);
    btn.addEventListener('mousedown', function (e) {
      e.preventDefault();
      e.stopPropagation();
      if (_activeLangDropdown) return;
      var dd = createLangDropdown(btn, '', function (chosen) {
        if (!chosen) return;
        convertBasicToAdvanced(pre, chosen, editableArea);
      });
      dd.focusFilter();
    });
    addSettingsButtonToBasicPre(pre);
  }

  function convertBasicToAdvanced(pre, lang, editableArea) {
    pre.setAttribute('data-lang', lang);
    var codeEl = pre.querySelector('code');
    if (codeEl) codeEl.className = 'language-' + lang;
    var oldBtn = pre.querySelector('.md-code-lang-btn');
    if (oldBtn) oldBtn.parentNode.removeChild(oldBtn);
    var oldDD = pre.querySelector('.md-code-lang-dropdown');
    if (oldDD) oldDD.parentNode.removeChild(oldDD);
    var oldSettings = pre.querySelector('.md-code-settings-btn');
    if (oldSettings) oldSettings.parentNode.removeChild(oldSettings);
    var oldSettingsDD = pre.querySelector('.md-code-settings-dropdown');
    if (oldSettingsDD) oldSettingsDD.parentNode.removeChild(oldSettingsDD);
    enhanceCodeBlocks(editableArea);
    if (wysiwygEditor && wysiwygEditor._finalizeUpdate) {
      wysiwygEditor._finalizeUpdate(editableArea.innerHTML);
    }
  }

  function getOrCreateAdvancedBtnGroup(wrapper) {
    var group = wrapper.querySelector('.md-code-btn-group-advanced');
    if (!group) {
      group = document.createElement('div');
      group.className = 'md-code-btn-group-advanced';
      group.setAttribute('contenteditable', 'false');
      wrapper.style.position = 'relative';
      wrapper.appendChild(group);
    }
    return group;
  }

  function addLangButtonToAdvancedBlock(wrapper) {
    if (wrapper.querySelector('.md-code-lang-btn-advanced')) return;
    var pre = wrapper.querySelector('pre');
    if (!pre) return;
    var currentLang = pre.getAttribute('data-lang') || '';
    var btn = document.createElement('button');
    btn.className = 'md-code-lang-btn-advanced';
    btn.setAttribute('contenteditable', 'false');
    btn.textContent = currentLang || 'lang';
    btn.type = 'button';
    var group = getOrCreateAdvancedBtnGroup(wrapper);
    group.appendChild(btn);
    btn.addEventListener('mousedown', function (e) {
      e.preventDefault();
      e.stopPropagation();
      if (_activeLangDropdown) return;
      var dd = createLangDropdown(btn, pre.getAttribute('data-lang') || '', function (chosen) {
        if (!chosen) return;
        pre.setAttribute('data-lang', chosen);
        var codeEl = pre.querySelector('code');
        if (codeEl) codeEl.className = 'language-' + chosen;
        btn.textContent = chosen;
        var titleBar = wrapper.querySelector('.md-code-title, .md-code-lang');
        if (titleBar && titleBar.classList.contains('md-code-lang')) {
          titleBar.textContent = chosen;
        }
        if (wysiwygEditor && wysiwygEditor._finalizeUpdate) {
          var ea = pre.closest('[contenteditable="true"]');
          if (ea) wysiwygEditor._finalizeUpdate(ea.innerHTML);
        }
      });
      dd.focusFilter();
    });
    addSettingsButtonToAdvancedBlock(wrapper);
  }

  var GEAR_SVG = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>';

  function createSettingsDropdown(anchorBtn) {
    dismissActiveSettingsDropdown();
    var settings = getIndentSettings();
    var dropdown = document.createElement('div');
    dropdown.className = 'md-code-settings-dropdown';
    dropdown.setAttribute('contenteditable', 'false');

    function buildUI() {
      dropdown.innerHTML = '';
      var s = getIndentSettings();

      var row1 = document.createElement('div');
      row1.className = 'md-code-settings-row';
      var lbl1 = document.createElement('span');
      lbl1.className = 'md-code-settings-label';
      lbl1.textContent = 'Auto-indent';
      row1.appendChild(lbl1);
      var toggle = document.createElement('button');
      toggle.className = 'md-code-settings-toggle' + (s.enabled ? ' active' : '');
      toggle.type = 'button';
      toggle.textContent = s.enabled ? 'ON' : 'OFF';
      toggle.addEventListener('mousedown', function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        s.enabled = !s.enabled;
        setIndentSettings(s);
        buildUI();
      });
      row1.appendChild(toggle);
      dropdown.appendChild(row1);

      var row2 = document.createElement('div');
      row2.className = 'md-code-settings-row';
      var lbl2 = document.createElement('span');
      lbl2.className = 'md-code-settings-label';
      lbl2.textContent = 'Type';
      row2.appendChild(lbl2);
      var btnGroup1 = document.createElement('div');
      btnGroup1.className = 'md-code-settings-btn-group';
      var btnSpaces = document.createElement('button');
      btnSpaces.type = 'button';
      btnSpaces.className = 'md-code-settings-opt' + (s.type === 'space' ? ' active' : '');
      btnSpaces.textContent = 'Spaces';
      btnSpaces.addEventListener('mousedown', function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        s.type = 'space';
        setIndentSettings(s);
        buildUI();
      });
      btnGroup1.appendChild(btnSpaces);
      var btnTabs = document.createElement('button');
      btnTabs.type = 'button';
      btnTabs.className = 'md-code-settings-opt' + (s.type === 'tab' ? ' active' : '');
      btnTabs.textContent = 'Tabs';
      btnTabs.addEventListener('mousedown', function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        s.type = 'tab';
        setIndentSettings(s);
        buildUI();
      });
      btnGroup1.appendChild(btnTabs);
      row2.appendChild(btnGroup1);
      dropdown.appendChild(row2);

      if (s.type === 'space') {
        var row3 = document.createElement('div');
        row3.className = 'md-code-settings-row';
        var lbl3 = document.createElement('span');
        lbl3.className = 'md-code-settings-label';
        lbl3.textContent = 'Size';
        row3.appendChild(lbl3);
        var btnGroup2 = document.createElement('div');
        btnGroup2.className = 'md-code-settings-btn-group';
        [2, 4, 8].forEach(function (n) {
          var b = document.createElement('button');
          b.type = 'button';
          b.className = 'md-code-settings-opt' + (s.size === n ? ' active' : '');
          b.textContent = String(n);
          b.addEventListener('mousedown', function (ev) {
            ev.preventDefault();
            ev.stopPropagation();
            s.size = n;
            setIndentSettings(s);
            buildUI();
          });
          btnGroup2.appendChild(b);
        });
        row3.appendChild(btnGroup2);
        dropdown.appendChild(row3);
      }
    }
    buildUI();

    function positionDropdown() {
      var rect = anchorBtn.getBoundingClientRect();
      var left = rect.right - 200;
      if (left < 0) left = rect.left;
      dropdown.style.top = (rect.bottom + 2) + 'px';
      dropdown.style.left = left + 'px';
    }
    var firstBtn = dropdown.querySelector('button');
    _attachDialogKeyboard(dropdown, {
      category: 'settings',
      onDismiss: function () { dismissActiveSettingsDropdown(); },
      autoFocus: firstBtn
    });

    document.body.appendChild(dropdown);
    positionDropdown();

    var closeHandler = function (ev) {
      if (dropdown.contains(ev.target) || ev.target === anchorBtn) return;
      dismissActiveSettingsDropdown();
    };
    document.addEventListener('mousedown', closeHandler, true);
    var scrollHandler = function () { positionDropdown(); };
    window.addEventListener('scroll', scrollHandler, true);
    _activeSettingsDropdown = { el: dropdown, closeHandler: closeHandler, scrollHandler: scrollHandler };
  }

  function addSettingsButtonToBasicPre(pre) {
    if (pre.querySelector('.md-code-settings-btn')) return;
    var btn = document.createElement('button');
    btn.className = 'md-code-settings-btn';
    btn.setAttribute('contenteditable', 'false');
    btn.innerHTML = GEAR_SVG;
    btn.type = 'button';
    pre.appendChild(btn);
    btn.addEventListener('mousedown', function (e) {
      e.preventDefault();
      e.stopPropagation();
      if (_activeSettingsDropdown) { dismissActiveSettingsDropdown(); return; }
      createSettingsDropdown(btn);
    });
  }

  function addSettingsButtonToAdvancedBlock(wrapper) {
    if (wrapper.querySelector('.md-code-settings-btn-advanced')) return;
    var btn = document.createElement('button');
    btn.className = 'md-code-settings-btn-advanced';
    btn.setAttribute('contenteditable', 'false');
    btn.innerHTML = GEAR_SVG;
    btn.type = 'button';
    var group = getOrCreateAdvancedBtnGroup(wrapper);
    var langBtn = group.querySelector('.md-code-lang-btn-advanced');
    if (langBtn) {
      group.insertBefore(btn, langBtn);
    } else {
      group.appendChild(btn);
    }
    btn.addEventListener('mousedown', function (e) {
      e.preventDefault();
      e.stopPropagation();
      if (_activeSettingsDropdown) { dismissActiveSettingsDropdown(); return; }
      createSettingsDropdown(btn);
    });
  }

  function enhanceBasicPreBlocks(editableArea) {
    if (!editableArea) return;
    var pres = editableArea.querySelectorAll('pre');
    for (var i = 0; i < pres.length; i++) {
      var pre = pres[i];
      if (pre.parentNode && pre.parentNode.classList && pre.parentNode.classList.contains('md-code-block')) continue;
      if (pre.hasAttribute('data-title') || pre.hasAttribute('data-linenums') || pre.hasAttribute('data-lang')) continue;
      addLangButtonToBasicPre(pre, editableArea);
    }
  }

  function enhanceCodeBlocks(editableArea) {
    if (!editableArea) return;
    var pres = editableArea.querySelectorAll('pre[data-title], pre[data-linenums], pre[data-lang]');
    for (var i = 0; i < pres.length; i++) {
      var pre = pres[i];
      if (pre.parentNode && pre.parentNode.classList && pre.parentNode.classList.contains('md-code-block')) continue;
      var wrapper = document.createElement('div');
      wrapper.className = 'md-code-block';
      var title = pre.getAttribute('data-title');
      var lang = pre.getAttribute('data-lang') || '';
      var headerBar = document.createElement('div');
      wrapper.appendChild(headerBar);
      (function (bar, preEl, langName) {
        function setupAsTitle(text) {
          bar.className = 'md-code-title';
          bar.setAttribute('contenteditable', 'true');
          bar.removeAttribute('data-placeholder');
          bar.textContent = text;
          preEl.setAttribute('data-title', text);
        }
        function setupAsLang() {
          bar.className = 'md-code-lang';
          bar.setAttribute('contenteditable', 'false');
          bar.removeAttribute('data-placeholder');
          bar.textContent = langName;
          preEl.removeAttribute('data-title');
        }
        var outsideClickHandler = null;
        function revertIfEmpty() {
          if (bar.classList.contains('md-code-title') && !bar.textContent.trim()) {
            if (langName) {
              setupAsLang();
            } else {
              bar.setAttribute('data-placeholder', 'Enter title...');
              preEl.removeAttribute('data-title');
            }
          }
          removeOutsideClickHandler();
        }
        function removeOutsideClickHandler() {
          if (outsideClickHandler) {
            document.removeEventListener('mousedown', outsideClickHandler, true);
            outsideClickHandler = null;
          }
        }
        function installOutsideClickHandler() {
          removeOutsideClickHandler();
          outsideClickHandler = function (e) {
            if (!bar.contains(e.target)) {
              revertIfEmpty();
            }
          };
          document.addEventListener('mousedown', outsideClickHandler, true);
        }
        function setupAsTitleEditing() {
          bar.className = 'md-code-title';
          bar.setAttribute('contenteditable', 'true');
          bar.setAttribute('data-placeholder', 'Enter title...');
          bar.textContent = '';
          preEl.removeAttribute('data-title');
          installOutsideClickHandler();
          requestAnimationFrame(function () {
            bar.focus();
            var sel = window.getSelection();
            if (sel) {
              var range = document.createRange();
              range.selectNodeContents(bar);
              range.collapse(true);
              sel.removeAllRanges();
              sel.addRange(range);
            }
          });
        }
        function onInput() {
          preEl.setAttribute('data-title', bar.textContent.trim());
        }
        function onKeydown(e) {
          if (e.key === 'Enter') e.preventDefault();
        }
        function onClick() {
          if (bar.classList.contains('md-code-lang')) {
            setupAsTitleEditing();
          }
        }
        function onBlur() {
          revertIfEmpty();
        }
        bar.addEventListener('input', onInput);
        bar.addEventListener('keydown', onKeydown);
        bar.addEventListener('click', onClick);
        bar.addEventListener('blur', onBlur);
        if (title) {
          setupAsTitle(title);
        } else if (langName) {
          setupAsLang();
        }
      })(headerBar, pre, lang);
      pre.parentNode.insertBefore(wrapper, pre);
      wrapper.appendChild(pre);
      addLangButtonToAdvancedBlock(wrapper);
      var linenums = pre.getAttribute('data-linenums');
      if (linenums) {
        var codeEl = pre.querySelector('code');
        var text = codeEl ? codeEl.textContent : pre.textContent;
        var lineCount = text.split('\n').length;
        if (text.endsWith('\n')) lineCount--;
        var startNum = parseInt(linenums, 10) || 1;
        var gutter = document.createElement('div');
        gutter.className = 'md-code-line-numbers';
        gutter.setAttribute('contenteditable', 'false');
        for (var n = 0; n < lineCount; n++) {
          var span = document.createElement('span');
          span.textContent = String(startNum + n);
          span.setAttribute('data-line', String(startNum + n));
          gutter.appendChild(span);
        }
        pre.insertBefore(gutter, pre.firstChild);
        (function (gutterEl, codeElement) {
          gutterEl.addEventListener('click', function (e) {
            var target = e.target;
            if (target.tagName !== 'SPAN' || !target.hasAttribute('data-line')) return;
            if (!codeElement) return;
            var lineIdx = Array.prototype.indexOf.call(gutterEl.children, target);
            if (lineIdx < 0) return;
            var textNode = codeElement.firstChild;
            if (!textNode || textNode.nodeType !== 3) return;
            var text = textNode.textContent;
            var offset = 0;
            for (var li = 0; li < lineIdx; li++) {
              var nl = text.indexOf('\n', offset);
              if (nl === -1) break;
              offset = nl + 1;
            }
            var range = document.createRange();
            range.setStart(textNode, offset);
            range.collapse(true);
            var sel = window.getSelection();
            if (sel) {
              sel.removeAllRanges();
              sel.addRange(range);
            }
          });
        })(gutter, codeEl);
      }
    }
    enhanceBasicPreBlocks(editableArea);
    var advancedBlocks = editableArea.querySelectorAll('.md-code-block');
    for (var j = 0; j < advancedBlocks.length; j++) {
      addLangButtonToAdvancedBlock(advancedBlocks[j]);
    }
  }

  function createInteractiveCheckbox(checked) {
    var cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.checked = !!checked;
    if (cb.checked) cb.setAttribute('checked', '');
    cb.setAttribute('data-live-wysiwyg-checklist', '1');
    cb.setAttribute('contenteditable', 'false');
    (function (checkbox) {
      function onCheckboxMouseDown(e) {
        if (e.target !== checkbox) return;
        e.preventDefault();
        e.stopPropagation();
        checkbox.checked = !checkbox.checked;
        if (checkbox.checked) checkbox.setAttribute('checked', '');
        else checkbox.removeAttribute('checked');
        var editable = checkbox.closest && checkbox.closest('[contenteditable="true"]');
        if (editable && editable.dispatchEvent) {
          editable.dispatchEvent(new Event('input', { bubbles: true }));
        }
      }
      function onCheckboxClick(e) {
        if (e.target !== checkbox) return;
        e.preventDefault();
        e.stopPropagation();
      }
      checkbox.addEventListener('mousedown', onCheckboxMouseDown, true);
      checkbox.addEventListener('click', onCheckboxClick, true);
    })(cb);
    return cb;
  }

  /** Get the direct-child checkbox of an LI (not from nested children). */
  function getDirectCheckboxOfLi(li) {
    for (var c = li.firstChild; c; c = c.nextSibling) {
      if (c.nodeName === 'INPUT' && c.type === 'checkbox') return c;
    }
    return null;
  }

  /** Return { node, offset } for the first character of content (first non-whitespace after checkbox). Does not modify DOM. */
  function getFirstContentPosition(li) {
    var cb = getDirectCheckboxOfLi(li);
    if (!cb) return null;
    function findFirst(node) {
      if (!node || node === li) return null;
      if (node.nodeType === 3) {
        var text = node.textContent || '';
        for (var i = 0; i < text.length; i++) {
          var c = text.charAt(i);
          if (c !== ' ' && c !== '\u00a0' && c !== '\t' && c !== '\n' && c !== '\r') {
            var code = c.charCodeAt(0);
            if (code !== 0x200B && code !== 0x200C && code !== 0x200D && code !== 0xFEFF) return { node: node, offset: i };
          }
        }
        return null;
      }
      if (node.nodeType === 1) {
        if (node.nodeName === 'UL' || node.nodeName === 'OL') return null;
        for (var c = node.firstChild; c; c = c.nextSibling) {
          var r = findFirst(c);
          if (r) return r;
        }
      }
      return null;
    }
    for (var n = cb.nextSibling; n; n = n.nextSibling) {
      var r = findFirst(n);
      if (r) return r;
    }
    return getPositionAfterCheckboxSpaces(li);
  }

  /** Return { node, offset } for position after the space(s) following the checkbox. Does not modify DOM. */
  function getPositionAfterCheckboxSpaces(li) {
    var cb = getDirectCheckboxOfLi(li);
    if (!cb) return null;
    var n = cb.nextSibling;
    var totalLen = 0;
    var lastNode = null;
    var lastOffset = 0;
    while (n && n.nodeType === 3 && /^[\s ]*$/.test(n.textContent)) {
      lastNode = n;
      lastOffset = n.textContent.length;
      totalLen += n.textContent.length;
      n = n.nextSibling;
    }
    if (!lastNode) return null;
    var pos = 0;
    n = cb.nextSibling;
    while (n && n.nodeType === 3 && /^[\s\u00a0]*$/.test(n.textContent)) {
      var len = (n.textContent || '').length;
      if (pos + len >= 2) return { node: n, offset: 2 - pos };
      pos += len;
      n = n.nextSibling;
    }
    return { node: lastNode, offset: lastOffset };
  }

  /** Return { node, offset } for the last character of content before any nested UL/OL. */
  function getLastContentPositionBeforeNestedList(li) {
    var cb = getDirectCheckboxOfLi(li);
    if (!cb) return null;
    function findLast(node) {
      if (!node || node === li) return null;
      if (node.nodeType === 3) {
        var len = (node.textContent || '').length;
        return len > 0 ? { node: node, offset: len } : null;
      }
      if (node.nodeType === 1) {
        if (node.nodeName === 'UL' || node.nodeName === 'OL') return null;
        var last = null;
        for (var c = node.lastChild; c; c = c.previousSibling) {
          var r = findLast(c);
          if (r) return r;
        }
      }
      return null;
    }
    var lastPos = null;
    for (var n = cb.nextSibling; n; n = n.nextSibling) {
      if (n.nodeType === 1 && (n.nodeName === 'UL' || n.nodeName === 'OL')) break;
      var r = findLast(n);
      if (r) lastPos = r;
    }
    return lastPos || getPositionAfterCheckboxSpaces(li);
  }

  /** Return the last (deepest) LI in the subtree, for visual order traversal. */
  function getLastLeafLi(li) {
    var nested = null;
    for (var c = li.firstChild; c; c = c.nextSibling) {
      if (c.nodeName === 'UL' || c.nodeName === 'OL') { nested = c; break; }
    }
    if (!nested || !nested.lastElementChild || nested.lastElementChild.nodeName !== 'LI') return li;
    return getLastLeafLi(nested.lastElementChild);
  }

  function addCheckboxToLi(li, checked) {
    if (li.querySelector('input[type="checkbox"]')) return;
    var cb = createInteractiveCheckbox(checked === undefined ? false : !!checked);
    var space = document.createTextNode('\u00a0 ');
    li.insertBefore(space, li.firstChild);
    li.insertBefore(cb, space);
  }

  function removeCheckboxFromLi(li) {
    var cb = li.querySelector('input[type="checkbox"]');
    if (!cb) return;
    var next = cb.nextSibling;
    if (next && next.nodeType === 3 && /^[\s\u00a0]/.test(next.textContent)) {
      next.textContent = next.textContent.replace(/^[\s\u00a0]/, '');
      if (!next.textContent) next.parentNode.removeChild(next);
    }
    cb.parentNode.removeChild(cb);
  }

  function findCursorList(ea) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return null;
    var node = sel.getRangeAt(0).commonAncestorContainer;
    if (node.nodeType === 3) node = node.parentNode;
    var li = node;
    while (li && li !== ea) {
      if (li.nodeName === 'LI') break;
      li = li.parentNode;
    }
    if (!li || li.nodeName !== 'LI') return null;
    var list = li.parentNode;
    if (!list || (list.nodeName !== 'UL' && list.nodeName !== 'OL')) return null;
    var isChecklist = false;
    if (list.nodeName === 'UL') {
      for (var i = 0; i < list.children.length; i++) {
        var child = list.children[i];
        if (child.nodeName === 'LI') {
          var cb = child.querySelector('input[type="checkbox"]');
          if (cb && cb.parentNode === child) { isChecklist = true; break; }
        }
      }
    }
    return { list: list, li: li, isChecklist: isChecklist };
  }

  function convertListTag(list, newTag) {
    if (list.nodeName === newTag) return list;
    var newList = document.createElement(newTag);
    while (list.firstChild) newList.appendChild(list.firstChild);
    list.parentNode.replaceChild(newList, list);
    return newList;
  }

  function createListInContainer(ea, listTag, isChecklist) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return;
    var range = sel.getRangeAt(0);
    var node = range.startContainer;
    if (node.nodeType === 3) node = node.parentNode;

    var container = ea;
    var anc = node;
    while (anc && anc !== ea) {
      var inLi = anc.nodeName === 'LI' && anc.parentNode && (anc.parentNode.nodeName === 'UL' || anc.parentNode.nodeName === 'OL');
      if ((anc.classList && anc.classList.contains('admonition')) || anc.nodeName === 'BLOCKQUOTE' || inLi) {
        container = anc;
        break;
      }
      anc = anc.parentNode;
    }

    var inner = node;
    while (inner && inner !== container && inner.parentNode !== container) {
      inner = inner.parentNode;
    }
    var targetBlock = (inner && inner !== container && inner.parentNode === container) ? inner : null;

    if (container === ea && !targetBlock) {
      var block = node;
      while (block && block !== ea && block.parentNode !== ea) block = block.parentNode;
      if (block && block !== ea && block.parentNode === ea) targetBlock = block;
    }

    var list = document.createElement(listTag);
    var li = document.createElement('li');

    if (targetBlock) {
      var text = (targetBlock.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '').trim();
      if (text && targetBlock.nodeType === 1) {
        while (targetBlock.firstChild) li.appendChild(targetBlock.firstChild);
      } else {
        li.innerHTML = '&#8203;';
      }
      list.appendChild(li);
      if (isChecklist) addCheckboxToLi(li);
      container.insertBefore(list, targetBlock);
      container.removeChild(targetBlock);
    } else {
      li.innerHTML = '&#8203;';
      list.appendChild(li);
      if (isChecklist) addCheckboxToLi(li);
      container.appendChild(list);
    }

    sel = window.getSelection();
    if (sel) {
      var newRange = document.createRange();
      var focusNode = li;
      if (isChecklist) {
        var cb = li.querySelector('input[type="checkbox"]');
        if (cb && cb.nextSibling) {
          focusNode = cb.nextSibling;
          newRange.setStart(focusNode, focusNode.nodeType === 3 ? focusNode.textContent.length : 0);
        } else {
          newRange.selectNodeContents(li);
          newRange.collapse(false);
        }
      } else {
        newRange.selectNodeContents(li);
        newRange.collapse(false);
      }
      sel.removeAllRanges();
      sel.addRange(newRange);
    }
  }

  (function patchToggleChecklist() {
    var proto = MarkdownWYSIWYG.prototype;

    proto._toggleChecklist = function () {
      if (this.currentMode === 'wysiwyg') {
        this.editableArea.focus();
        var ea = this.editableArea;
        var info = findCursorList(ea);
        if (info) {
          var list = info.list;
          var cursorLi = info.li;
          var sel = window.getSelection();
          var savedNode = null, savedOffset = 0;
          if (sel && sel.rangeCount > 0) {
            var r = sel.getRangeAt(0);
            savedNode = r.startContainer;
            savedOffset = r.startOffset;
          }
          if (info.isChecklist) {
            for (var i = 0; i < list.children.length; i++) {
              if (list.children[i].nodeName === 'LI') removeCheckboxFromLi(list.children[i]);
            }
          } else {
            if (list.nodeName === 'OL') {
              list = convertListTag(list, 'UL');
            }
            for (var i = 0; i < list.children.length; i++) {
              if (list.children[i].nodeName === 'LI') addCheckboxToLi(list.children[i]);
            }
          }
          if (sel && savedNode) {
            try {
              var rng = document.createRange();
              if (savedNode.parentNode) {
                rng.setStart(savedNode, Math.min(savedOffset, savedNode.nodeType === 3 ? savedNode.textContent.length : savedNode.childNodes.length));
              } else {
                rng.selectNodeContents(cursorLi);
                rng.collapse(false);
              }
              rng.collapse(true);
              sel.removeAllRanges();
              sel.addRange(rng);
            } catch (ex) {
              /* cursor restore failed, leave as-is */
            }
          }
        } else {
          createListInContainer(ea, 'UL', true);
        }
        this._finalizeUpdate(this.editableArea.innerHTML);
      } else {
        var textarea = this.markdownArea;
        var text = textarea.value;
        var start = textarea.selectionStart;
        var end = textarea.selectionEnd;
        var firstLineStart = text.lastIndexOf('\n', start - 1) + 1;
        if (start === 0 && text.charAt(0) !== '\n') firstLineStart = 0;
        var lastLineEnd = text.indexOf('\n', end);
        if (lastLineEnd === -1) lastLineEnd = text.length;
        var regionText = text.substring(firstLineStart, lastLineEnd);
        var lines = regionText.split('\n');
        var checklistRe = /^(\s*)([-*+])\s+\[[ xX]\]\s/;
        var listRe = /^(\s*)([-*+])\s/;
        var hasContent = false;
        var allChecklist = true;
        var allList = true;
        for (var i = 0; i < lines.length; i++) {
          if (!lines[i].trim()) continue;
          hasContent = true;
          if (!checklistRe.test(lines[i])) allChecklist = false;
          if (!listRe.test(lines[i])) allList = false;
        }
        if (!hasContent) { allChecklist = false; allList = false; }
        var newLines;
        if (allChecklist) {
          newLines = lines.map(function (line) {
            return line.replace(/^(\s*)([-*+])\s+\[[ xX]\]\s/, '$1$2 ');
          });
        } else if (allList) {
          newLines = lines.map(function (line) {
            if (!line.trim()) return line;
            return line.replace(/^(\s*)([-*+])\s/, '$1$2 [ ] ');
          });
        } else {
          newLines = lines.map(function (line) {
            if (!line.trim()) return line;
            return '- [ ] ' + line;
          });
        }
        var newText = newLines.join('\n');
        textarea.value = text.substring(0, firstLineStart) + newText + text.substring(lastLineEnd);
        textarea.focus();
        textarea.setSelectionRange(firstLineStart, firstLineStart + newText.length);
        this._finalizeUpdate(textarea.value);
      }
    };

    var origWysiwygActive = proto._updateWysiwygToolbarActiveStates;
    if (origWysiwygActive) {
      proto._updateWysiwygToolbarActiveStates = function () {
        origWysiwygActive.apply(this, arguments);
        var sel = window.getSelection();

        var checklistBtn = this.toolbar && this.toolbar.querySelector('.md-toolbar-button-checklist');
        if (checklistBtn) {
          checklistBtn.classList.remove('active');
          if (sel && sel.rangeCount > 0) {
            var node = sel.getRangeAt(0).commonAncestorContainer;
            if (node.nodeType === 3) node = node.parentNode;
            while (node && node !== this.editableArea) {
              if (node.nodeName === 'UL') break;
              node = node.parentNode;
            }
            if (node && node.nodeName === 'UL') {
              var hasDirectCheckbox = false;
              for (var k = 0; k < node.children.length; k++) {
                var li = node.children[k];
                if (li.nodeName === 'LI') {
                  var cb = li.querySelector('input[type="checkbox"]');
                  if (cb && cb.parentNode === li) { hasDirectCheckbox = true; break; }
                }
              }
              if (hasDirectCheckbox) checklistBtn.classList.add('active');
            }
          }
        }

        var hBtn = this.headingButton;
        if (hBtn) {
          if (!hBtn._originalIcon) hBtn._originalIcon = hBtn.innerHTML;
          var headingTag = null;
          if (sel && sel.rangeCount > 0) {
            var el = sel.getRangeAt(0).commonAncestorContainer;
            if (el.nodeType === 3) el = el.parentNode;
            while (el && el !== this.editableArea) {
              if (/^H[1-6]$/.test(el.nodeName)) { headingTag = el.nodeName; break; }
              el = el.parentNode;
            }
          }
          if (headingTag) {
            hBtn.textContent = headingTag;
          } else {
            hBtn.innerHTML = hBtn._originalIcon;
          }
        }
      };
    }

    var origMarkdownActive = proto._updateMarkdownToolbarActiveStates;
    if (origMarkdownActive) {
      proto._updateMarkdownToolbarActiveStates = function () {
        origMarkdownActive.apply(this, arguments);
        var btn = this.toolbar && this.toolbar.querySelector('.md-toolbar-button-checklist');
        if (!btn) return;
        btn.classList.remove('active');
        if (!this.markdownArea) return;
        var text = this.markdownArea.value;
        var selStart = this.markdownArea.selectionStart;
        var lineStart = text.lastIndexOf('\n', selStart - 1) + 1;
        if (selStart === 0 && lineStart > 0 && text.charAt(0) !== '\n') lineStart = 0;
        var lineEnd = text.indexOf('\n', lineStart);
        var line = text.substring(lineStart, lineEnd === -1 ? text.length : lineEnd);
        if (/^\s*[-*+]\s+\[[ xX]\]/.test(line)) {
          btn.classList.add('active');
        }
      };
    }

    var origHandleToolbarClick = proto._handleToolbarClick;
    if (origHandleToolbarClick) {
      proto._handleToolbarClick = function (buttonConfig, buttonElement) {
        _flushHistoryCapture();
        var isListBtn = (buttonConfig.id === 'ul' || buttonConfig.id === 'ol') && this.currentMode === 'wysiwyg';
        if (isListBtn) {
          this.editableArea.focus();
          var ea = this.editableArea;
          var info = findCursorList(ea);
          if (info) {
            var list = info.list;
            var requestedTag = (buttonConfig.id === 'ol') ? 'OL' : 'UL';
            if (list.nodeName === requestedTag && !info.isChecklist) {
              origHandleToolbarClick.apply(this, arguments);
              return;
            }
            var sel = window.getSelection();
            var savedNode = null, savedOffset = 0;
            if (sel && sel.rangeCount > 0) {
              var r = sel.getRangeAt(0);
              savedNode = r.startContainer;
              savedOffset = r.startOffset;
            }
            if (info.isChecklist) {
              for (var i = 0; i < list.children.length; i++) {
                if (list.children[i].nodeName === 'LI') removeCheckboxFromLi(list.children[i]);
              }
            }
            convertListTag(list, requestedTag);
            if (sel && savedNode) {
              try {
                var rng = document.createRange();
                if (savedNode.parentNode) {
                  rng.setStart(savedNode, Math.min(savedOffset, savedNode.nodeType === 3 ? savedNode.textContent.length : savedNode.childNodes.length));
                } else {
                  rng.selectNodeContents(info.li);
                  rng.collapse(false);
                }
                rng.collapse(true);
                sel.removeAllRanges();
                sel.addRange(rng);
              } catch (ex) { /* cursor restore failed */ }
            }
            this._finalizeUpdate(ea.innerHTML);
            this._updateToolbarActiveStates();
            return;
          }
          createListInContainer(ea, (buttonConfig.id === 'ol') ? 'OL' : 'UL', false);
          this._finalizeUpdate(ea.innerHTML);
          this._updateToolbarActiveStates();
          return;
        }
        origHandleToolbarClick.apply(this, arguments);
      };
    }
  })();

  var ADMONITION_ICON_PENCIL = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M20.71 7.04c.39-.39.39-1.04 0-1.41l-2.34-2.34c-.37-.39-1.02-.39-1.41 0l-1.84 1.83 3.75 3.75M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25z"/></svg>';
  var ADMONITION_ICON_FLAME = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 17.41 3.8 13.5.67zM11.71 19c-1.78 0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 4.04 0 2.65-2.15 4.8-4.8 4.8z"/></svg>';
  var ADMONITION_ICON_ALERT = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/></svg>';
  var ADMONITION_ICON_ZAP = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M7 2v11h3v9l7-12h-4l4-8z"/></svg>';
  var ADMONITION_ICON_CLIPBOARD = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-2 14l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"/></svg>';
  var ADMONITION_ICON_INFO = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>';
  var ADMONITION_ICON_CHECK = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>';
  var ADMONITION_ICON_QUESTION = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/></svg>';
  var ADMONITION_ICON_XMARK = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>';
  var ADMONITION_ICON_BUG = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5s-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/></svg>';
  var ADMONITION_ICON_BEAKER = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M19.8 18.4L14 10.67V6.5l1.35-1.69c.26-.33.03-.81-.39-.81H9.04c-.42 0-.65.48-.39.81L10 6.5v4.17L4.2 18.4c-.49.66-.02 1.6.8 1.6h14c.82 0 1.29-.94.8-1.6z"/></svg>';
  var ADMONITION_ICON_QUOTE = '<svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18"><path d="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z"/></svg>';

  var ADMONITION_TYPES = [
    { id: 'note',      label: 'Note',      color: '#448aff', icon: ADMONITION_ICON_PENCIL },
    { id: 'abstract',  label: 'Abstract',  color: '#00b0ff', icon: ADMONITION_ICON_CLIPBOARD },
    { id: 'info',      label: 'Info',      color: '#00b8d4', icon: ADMONITION_ICON_INFO },
    { id: 'tip',       label: 'Tip',       color: '#00c853', icon: ADMONITION_ICON_FLAME },
    { id: 'hint',      label: 'Hint',      color: '#00b0ff', icon: ADMONITION_ICON_FLAME },
    { id: 'important', label: 'Important', color: '#ff6d00', icon: ADMONITION_ICON_FLAME },
    { id: 'success',   label: 'Success',   color: '#00c853', icon: ADMONITION_ICON_CHECK },
    { id: 'question',  label: 'Question',  color: '#64dd17', icon: ADMONITION_ICON_QUESTION },
    { id: 'warning',   label: 'Warning',   color: '#ff9100', icon: ADMONITION_ICON_ALERT },
    { id: 'caution',   label: 'Caution',   color: '#ffc400', icon: ADMONITION_ICON_ALERT },
    { id: 'attention', label: 'Attention', color: '#ffab00', icon: ADMONITION_ICON_ALERT },
    { id: 'failure',   label: 'Failure',   color: '#ff5252', icon: ADMONITION_ICON_XMARK },
    { id: 'danger',    label: 'Danger',    color: '#ff1744', icon: ADMONITION_ICON_ZAP },
    { id: 'error',     label: 'Error',     color: '#ff5252', icon: ADMONITION_ICON_ZAP },
    { id: 'bug',       label: 'Bug',       color: '#f50057', icon: ADMONITION_ICON_BUG },
    { id: 'example',   label: 'Example',   color: '#7c4dff', icon: ADMONITION_ICON_BEAKER },
    { id: 'quote',     label: 'Quote',     color: '#9e9e9e', icon: ADMONITION_ICON_QUOTE }
  ];

  var ADMONITION_TYPE_IDS = ['note', 'warning', 'danger', 'tip', 'hint', 'important', 'caution', 'error', 'attention', 'abstract', 'info', 'success', 'question', 'failure', 'bug', 'example', 'quote'];

  function isAdmonitionElement(node) {
    if (!node || !node.classList) return false;
    if (node.nodeName === 'DIV' && node.classList.contains('admonition')) return true;
    if (node.nodeName === 'DETAILS') {
      for (var i = 0; i < ADMONITION_TYPE_IDS.length; i++) {
        if (node.classList.contains(ADMONITION_TYPE_IDS[i])) return true;
      }
    }
    return false;
  }

  function getAdmonitionType(node) {
    for (var i = 0; i < ADMONITION_TYPE_IDS.length; i++) {
      if (node.classList.contains(ADMONITION_TYPE_IDS[i])) return ADMONITION_TYPE_IDS[i];
    }
    return null;
  }

  function convertToCollapsible(adDiv) {
    var type = getAdmonitionType(adDiv);
    if (!type) return adDiv;
    var details = document.createElement('details');
    details.setAttribute('open', '');
    var classes = type;
    if (adDiv.classList.contains('inline')) classes += ' inline';
    if (adDiv.classList.contains('end')) classes += ' end';
    details.className = classes;
    details.setAttribute('contenteditable', 'true');
    var literal = adDiv.getAttribute('data-md-literal');
    if (literal) details.setAttribute('data-md-literal', literal);

    var titleEl = adDiv.querySelector(':scope > .admonition-title');
    var summary = document.createElement('summary');
    summary.textContent = titleEl ? titleEl.textContent : (type.charAt(0).toUpperCase() + type.slice(1));
    details.appendChild(summary);

    while (adDiv.firstChild) {
      var child = adDiv.firstChild;
      if (child === titleEl) { adDiv.removeChild(child); continue; }
      if (child.classList && child.classList.contains('md-admonition-settings-btn')) { adDiv.removeChild(child); continue; }
      details.appendChild(child);
    }
    if (adDiv.parentNode) adDiv.parentNode.replaceChild(details, adDiv);
    return details;
  }

  function convertToNonCollapsible(detailsEl) {
    var type = getAdmonitionType(detailsEl);
    if (!type) return detailsEl;
    var div = document.createElement('div');
    var classes = 'admonition ' + type;
    if (detailsEl.classList.contains('inline')) classes += ' inline';
    if (detailsEl.classList.contains('end')) classes += ' end';
    div.className = classes;
    div.setAttribute('contenteditable', 'true');
    var literal = detailsEl.getAttribute('data-md-literal');
    if (literal) div.setAttribute('data-md-literal', literal);

    var summaryEl = detailsEl.querySelector(':scope > summary');
    var titleP = document.createElement('p');
    titleP.className = 'admonition-title';
    titleP.textContent = summaryEl ? summaryEl.textContent : (type.charAt(0).toUpperCase() + type.slice(1));
    div.appendChild(titleP);

    while (detailsEl.firstChild) {
      var child = detailsEl.firstChild;
      if (child === summaryEl) { detailsEl.removeChild(child); continue; }
      if (child.classList && child.classList.contains('md-admonition-settings-btn')) { detailsEl.removeChild(child); continue; }
      div.appendChild(child);
    }
    if (detailsEl.parentNode) detailsEl.parentNode.replaceChild(div, detailsEl);
    return div;
  }

  var _activeAdmonitionDropdown = null;
  function dismissAdmonitionSettingsDropdown() {
    if (_activeAdmonitionDropdown) {
      if (_activeAdmonitionDropdown.el.parentNode) _activeAdmonitionDropdown.el.parentNode.removeChild(_activeAdmonitionDropdown.el);
      if (_activeAdmonitionDropdown.closeHandler) document.removeEventListener('mousedown', _activeAdmonitionDropdown.closeHandler, true);
      if (_activeAdmonitionDropdown.scrollHandler) window.removeEventListener('scroll', _activeAdmonitionDropdown.scrollHandler, true);
      _activeAdmonitionDropdown = null;
    }
  }

  function _showAdmonitionDetailsConfirm(typeName, onProceed, onCancel) {
    var overlay = document.createElement('div');
    overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.35);z-index:999999;display:flex;align-items:center;justify-content:center;';
    var dialog = document.createElement('div');
    dialog.style.cssText = 'background:var(--md-default-bg-color,#fff);color:var(--md-default-fg-color,#333);border:1px solid var(--md-default-fg-color--lighter,#ccc);border-radius:8px;padding:20px 24px;max-width:380px;box-shadow:0 4px 16px rgba(0,0,0,0.2);font-family:inherit;';
    var msg = document.createElement('p');
    msg.style.cssText = 'margin:0 0 16px;font-size:14px;line-height:1.5;';
    msg.textContent = 'The \u201c' + typeName.charAt(0).toUpperCase() + typeName.slice(1) + '\u201d admonition type will be lost when converting to a details tag. Proceed?';
    var btnRow = document.createElement('div');
    btnRow.style.cssText = 'display:flex;justify-content:flex-end;gap:8px;';
    var cancelBtn = document.createElement('button');
    cancelBtn.type = 'button';
    cancelBtn.textContent = 'Cancel';
    cancelBtn.style.cssText = 'padding:6px 16px;border:1px solid var(--md-default-fg-color--lighter,#ccc);border-radius:4px;background:transparent;color:inherit;cursor:pointer;font-size:13px;';
    var proceedBtn = document.createElement('button');
    proceedBtn.type = 'button';
    proceedBtn.textContent = 'Proceed';
    proceedBtn.style.cssText = 'padding:6px 16px;border:none;border-radius:4px;background:var(--md-primary-fg-color,#4051b5);color:var(--md-primary-bg-color,#fff);cursor:pointer;font-size:13px;';
    function dismiss() { if (overlay.parentNode) overlay.parentNode.removeChild(overlay); }
    cancelBtn.addEventListener('click', function () { dismiss(); if (onCancel) onCancel(); });
    proceedBtn.addEventListener('click', function () { dismiss(); if (onProceed) onProceed(); });
    overlay.addEventListener('mousedown', function (ev) { if (ev.target === overlay) { dismiss(); if (onCancel) onCancel(); } });
    proceedBtn.tabIndex = 1;
    cancelBtn.tabIndex = 2;
    btnRow.appendChild(cancelBtn);
    btnRow.appendChild(proceedBtn);
    dialog.appendChild(msg);
    dialog.appendChild(btnRow);
    overlay.appendChild(dialog);
    _attachDialogKeyboard(overlay, {
      category: 'confirmation',
      onDismiss: function () { dismiss(); if (onCancel) onCancel(); },
      onConfirm: function () { dismiss(); if (onProceed) onProceed(); },
      autoFocus: proceedBtn
    });
    document.body.appendChild(overlay);
  }

  function createAdmonitionSettingsDropdown(anchorBtn, adEl, ea) {
    dismissAdmonitionSettingsDropdown();
    dismissActiveSettingsDropdown();

    var dropdown = document.createElement('div');
    dropdown.className = 'md-admonition-settings-dropdown';
    dropdown.setAttribute('contenteditable', 'false');

    function positionDropdown() {
      var rect = anchorBtn.getBoundingClientRect();
      var left = rect.right - 210;
      if (left < 0) left = rect.left;
      dropdown.style.top = (rect.bottom + 2) + 'px';
      dropdown.style.left = left + 'px';
    }

    function readState() {
      var isCollapsible = (adEl.nodeName === 'DETAILS');
      var isCollapsed = isCollapsible && adEl.hasAttribute('data-default-collapsed');
      var isDetailsTag = isCollapsible && adEl.hasAttribute('data-details-tag');
      var hasInline = adEl.classList.contains('inline');
      var hasEnd = adEl.classList.contains('end');
      var hideTitle = adEl.hasAttribute('data-hide-title');
      var placement = hasInline ? (hasEnd ? 'inline-end' : 'inline') : 'standalone';
      var type = getAdmonitionType(adEl) || 'note';
      return { isCollapsible: isCollapsible, isCollapsed: isCollapsed, isDetailsTag: isDetailsTag, placement: placement, hideTitle: hideTitle, type: type };
    }

    function getDefaultTitleForType(type) {
      for (var i = 0; i < ADMONITION_TYPES.length; i++) {
        if (ADMONITION_TYPES[i].id === type) return ADMONITION_TYPES[i].label;
      }
      return type ? (type.charAt(0).toUpperCase() + type.slice(1)) : 'Note';
    }

    function setAdmonitionType(adEl, newType) {
      var oldType = getAdmonitionType(adEl) || 'note';
      var titleEl = adEl.querySelector(':scope > .admonition-title') || adEl.querySelector(':scope > summary');
      if (titleEl && !adEl.hasAttribute('data-hide-title')) {
        var currentTitle = (titleEl.textContent || '').trim();
        var oldDefault = getDefaultTitleForType(oldType);
        if (currentTitle === oldDefault) {
          titleEl.textContent = getDefaultTitleForType(newType);
        }
      }
      for (var i = 0; i < ADMONITION_TYPE_IDS.length; i++) {
        adEl.classList.remove(ADMONITION_TYPE_IDS[i]);
      }
      adEl.classList.add(newType);
      if (adEl.hasAttribute('data-md-literal')) {
        var prefix = adEl.nodeName === 'DETAILS' ? (adEl.hasAttribute('open') && !adEl.hasAttribute('data-default-collapsed') ? '???+ ' : '??? ') : '!!! ';
        adEl.setAttribute('data-md-literal', prefix + newType + ' ');
      }
    }

    function buildUI() {
      dropdown.innerHTML = '';
      var state = readState();

      var typeRow = document.createElement('div');
      typeRow.className = 'md-admonition-settings-row';
      var typeLabel = document.createElement('span');
      typeLabel.className = 'md-admonition-settings-label';
      typeLabel.textContent = 'Type';
      var typeSelect = document.createElement('select');
      typeSelect.className = 'md-admonition-type-select';
      for (var ti = 0; ti < ADMONITION_TYPES.length; ti++) {
        var opt = document.createElement('option');
        opt.value = ADMONITION_TYPES[ti].id;
        opt.textContent = ADMONITION_TYPES[ti].label;
        if (ADMONITION_TYPES[ti].id === state.type) opt.selected = true;
        typeSelect.appendChild(opt);
      }
      typeSelect.addEventListener('change', function () {
        var newType = typeSelect.value;
        if (newType === state.type) return;
        setAdmonitionType(adEl, newType);
        state.type = newType;
        syncAndRebuild();
      });
      typeRow.appendChild(typeLabel);
      typeRow.appendChild(typeSelect);
      dropdown.appendChild(typeRow);

      var placementGroup = document.createElement('div');
      placementGroup.className = 'md-admonition-placement-group';

      var btnStandalone = document.createElement('button');
      btnStandalone.type = 'button';
      btnStandalone.className = 'md-admonition-placement-full' + (state.placement === 'standalone' ? ' active' : '');
      btnStandalone.textContent = 'Standalone';
      btnStandalone.addEventListener('mousedown', function (ev) {
        ev.preventDefault(); ev.stopPropagation();
        adEl.classList.remove('inline', 'end');
        syncAndRebuild();
      });

      var halvesRow = document.createElement('div');
      halvesRow.className = 'md-admonition-placement-halves';

      var btnInlineLeft = document.createElement('button');
      btnInlineLeft.type = 'button';
      btnInlineLeft.className = 'md-admonition-placement-half' + (state.placement === 'inline' ? ' active' : '');
      btnInlineLeft.innerHTML = '&#9664; Inline';
      btnInlineLeft.addEventListener('mousedown', function (ev) {
        ev.preventDefault(); ev.stopPropagation();
        adEl.classList.add('inline');
        adEl.classList.remove('end');
        syncAndRebuild();
      });

      var btnInlineRight = document.createElement('button');
      btnInlineRight.type = 'button';
      btnInlineRight.className = 'md-admonition-placement-half' + (state.placement === 'inline-end' ? ' active' : '');
      btnInlineRight.innerHTML = 'Inline &#9654;';
      btnInlineRight.addEventListener('mousedown', function (ev) {
        ev.preventDefault(); ev.stopPropagation();
        adEl.classList.add('inline', 'end');
        syncAndRebuild();
      });

      halvesRow.appendChild(btnInlineLeft);
      halvesRow.appendChild(btnInlineRight);
      placementGroup.appendChild(btnStandalone);
      placementGroup.appendChild(halvesRow);
      dropdown.appendChild(placementGroup);

      var collapsibleRow = document.createElement('div');
      collapsibleRow.className = 'md-admonition-settings-row';
      var collapsibleLabel = document.createElement('span');
      collapsibleLabel.className = 'md-admonition-settings-label';
      collapsibleLabel.textContent = 'Collapsible';
      var collapsibleToggle = document.createElement('button');
      collapsibleToggle.type = 'button';
      collapsibleToggle.className = 'md-admonition-settings-toggle' + (state.isCollapsible ? ' active' : '');
      collapsibleToggle.textContent = state.isCollapsible ? 'ON' : 'OFF';
      collapsibleToggle.addEventListener('mousedown', function (ev) {
        ev.preventDefault(); ev.stopPropagation();
        if (adEl.nodeName === 'DETAILS') {
          adEl = convertToNonCollapsible(adEl);
        } else {
          adEl = convertToCollapsible(adEl);
        }
        addSettingsButtonToAdmonition(adEl);
        anchorBtn = adEl.querySelector(':scope > .md-admonition-settings-btn');
        positionDropdown();
        syncAndRebuild();
      });
      collapsibleRow.appendChild(collapsibleLabel);
      collapsibleRow.appendChild(collapsibleToggle);
      dropdown.appendChild(collapsibleRow);

      if (state.isCollapsible) {
        var collapsedRow = document.createElement('div');
        collapsedRow.className = 'md-admonition-settings-row';
        var collapsedLabel = document.createElement('span');
        collapsedLabel.className = 'md-admonition-settings-label';
        collapsedLabel.textContent = 'Collapsed';
        var collapsedToggle = document.createElement('button');
        collapsedToggle.type = 'button';
        collapsedToggle.className = 'md-admonition-settings-toggle' + (state.isCollapsed ? ' active' : '');
        collapsedToggle.textContent = state.isCollapsed ? 'ON' : 'OFF';
        collapsedToggle.addEventListener('mousedown', function (ev) {
          ev.preventDefault(); ev.stopPropagation();
          if (adEl.hasAttribute('data-default-collapsed')) {
            adEl.removeAttribute('data-default-collapsed');
            if (adEl.hasAttribute('data-details-tag')) {
              adEl.removeAttribute('data-details-tag');
            }
          } else {
            adEl.setAttribute('data-default-collapsed', '1');
          }
          syncAndRebuild();
        });
        collapsedRow.appendChild(collapsedLabel);
        collapsedRow.appendChild(collapsedToggle);
        dropdown.appendChild(collapsedRow);

        var detailsTagRow = document.createElement('div');
        detailsTagRow.className = 'md-admonition-settings-row';
        var detailsTagLabel = document.createElement('span');
        detailsTagLabel.className = 'md-admonition-settings-label';
        detailsTagLabel.textContent = 'Details tag';
        var detailsTagToggle = document.createElement('button');
        detailsTagToggle.type = 'button';
        detailsTagToggle.className = 'md-admonition-settings-toggle' + (state.isDetailsTag ? ' active' : '');
        detailsTagToggle.textContent = state.isDetailsTag ? 'ON' : 'OFF';
        detailsTagToggle.addEventListener('mousedown', function (ev) {
          ev.preventDefault(); ev.stopPropagation();
          if (adEl.hasAttribute('data-details-tag')) {
            adEl.removeAttribute('data-details-tag');
            syncAndRebuild();
          } else {
            var currentType = getAdmonitionType(adEl) || 'note';
            function applyDetailsTag() {
              if (currentType !== 'note') {
                setAdmonitionType(adEl, 'note');
              }
              adEl.setAttribute('data-details-tag', '1');
              if (!adEl.hasAttribute('data-default-collapsed')) {
                adEl.setAttribute('data-default-collapsed', '1');
              }
              syncAndRebuild();
            }
            if (currentType !== 'note') {
              _showAdmonitionDetailsConfirm(currentType, applyDetailsTag, function () {});
            } else {
              applyDetailsTag();
            }
          }
        });
        detailsTagRow.appendChild(detailsTagLabel);
        detailsTagRow.appendChild(detailsTagToggle);
        dropdown.appendChild(detailsTagRow);
      }

      if (!state.isCollapsible) {
        var hideTitleRow = document.createElement('div');
        hideTitleRow.className = 'md-admonition-settings-row';
        var hideTitleLabel = document.createElement('span');
        hideTitleLabel.className = 'md-admonition-settings-label';
        hideTitleLabel.textContent = 'Hide title';
        var hideTitleToggle = document.createElement('button');
        hideTitleToggle.type = 'button';
        hideTitleToggle.className = 'md-admonition-settings-toggle' + (state.hideTitle ? ' active' : '');
        hideTitleToggle.textContent = state.hideTitle ? 'ON' : 'OFF';
        hideTitleToggle.addEventListener('mousedown', function (ev) {
          ev.preventDefault(); ev.stopPropagation();
          if (adEl.hasAttribute('data-hide-title')) {
            adEl.removeAttribute('data-hide-title');
            var type = getAdmonitionType(adEl);
            var defTitle = type ? (type.charAt(0).toUpperCase() + type.slice(1)) : 'Note';
            var existingTitle = adEl.querySelector(':scope > .admonition-title');
            if (!existingTitle) {
              var titleP = document.createElement('p');
              titleP.className = 'admonition-title';
              titleP.textContent = defTitle;
              adEl.insertBefore(titleP, adEl.firstChild);
            }
          } else {
            adEl.setAttribute('data-hide-title', '1');
            var titleEl = adEl.querySelector(':scope > .admonition-title');
            if (titleEl) adEl.removeChild(titleEl);
          }
          syncAndRebuild();
        });
        hideTitleRow.appendChild(hideTitleLabel);
        hideTitleRow.appendChild(hideTitleToggle);
        dropdown.appendChild(hideTitleRow);
      }
    }

    function syncAndRebuild() {
      if (wysiwygEditor && wysiwygEditor._finalizeUpdate) {
        wysiwygEditor._finalizeUpdate(ea.innerHTML);
      }
      buildUI();
    }

    buildUI();
    var typeSelectEl = dropdown.querySelector('.md-admonition-type-select');
    _attachDialogKeyboard(dropdown, {
      category: 'settings',
      onDismiss: function () { dismissAdmonitionSettingsDropdown(); },
      autoFocus: typeSelectEl
    });

    document.body.appendChild(dropdown);
    positionDropdown();

    var closeHandler = function (ev) {
      if (dropdown.contains(ev.target) || anchorBtn.contains(ev.target)) return;
      dismissAdmonitionSettingsDropdown();
    };
    var scrollHandler = function () { positionDropdown(); };
    document.addEventListener('mousedown', closeHandler, true);
    window.addEventListener('scroll', scrollHandler, true);

    _activeAdmonitionDropdown = { el: dropdown, closeHandler: closeHandler, scrollHandler: scrollHandler };
  }

  function addSettingsButtonToAdmonition(adEl) {
    if (adEl.querySelector(':scope > .md-admonition-settings-btn')) return;
    var btn = document.createElement('button');
    btn.className = 'md-admonition-settings-btn';
    btn.setAttribute('contenteditable', 'false');
    btn.innerHTML = GEAR_SVG;
    btn.type = 'button';
    adEl.appendChild(btn);
    btn.addEventListener('mousedown', function (e) {
      e.preventDefault();
      e.stopPropagation();
      if (_activeAdmonitionDropdown) {
        dismissAdmonitionSettingsDropdown();
        return;
      }
      var ea = adEl.closest('.md-editable-area') || adEl.closest('[contenteditable="true"]');
      if (!ea) {
        var p = adEl.parentNode;
        while (p) {
          if (p.classList && p.classList.contains('md-editable-area')) { ea = p; break; }
          p = p.parentNode;
        }
      }
      if (ea) createAdmonitionSettingsDropdown(btn, adEl, ea);
    });
  }

  function restoreEmptyAdmonitionTitle(titleEl) {
    if (!titleEl) return;
    var text = (titleEl.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
    if (text.length > 0) return;
    var adEl = titleEl.parentNode;
    if (!adEl || !isAdmonitionElement(adEl)) return;
    var type = getAdmonitionType(adEl);
    var defTitle = type ? (type.charAt(0).toUpperCase() + type.slice(1)) : 'Note';
    titleEl.textContent = defTitle;
  }

  function findTitleFromNode(node, ea) {
    var el = node && node.nodeType === 3 ? node.parentNode : node;
    while (el && el !== ea) {
      if (el.classList && el.classList.contains('admonition-title')) return el;
      if (el.nodeName === 'SUMMARY' && el.parentNode && el.parentNode.nodeName === 'DETAILS') return el;
      el = el.parentNode;
    }
    return null;
  }

  function _renderMarkdownInRawHtml(decoded) {
    if (!decoded || typeof marked === 'undefined') return decoded;
    var lines = decoded.split('\n');
    var minIndent = Infinity;
    for (var i = 0; i < lines.length; i++) {
      if (/^\s*$/.test(lines[i])) continue;
      var m = lines[i].match(/^( *)/);
      if (m && m[1].length < minIndent) minIndent = m[1].length;
    }
    if (minIndent === Infinity) minIndent = 0;
    var stripped = [];
    for (var i = 0; i < lines.length; i++) {
      stripped.push(lines[i].substring(minIndent));
    }
    var processed = [];
    var inFencedBlock = false;
    var fenceCloseRe = null;
    for (var i = 0; i < stripped.length; i++) {
      var line = stripped[i];
      if (inFencedBlock) {
        processed.push(line);
        if (fenceCloseRe && fenceCloseRe.test(line)) {
          inFencedBlock = false;
          fenceCloseRe = null;
        }
        continue;
      }
      var fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})/);
      if (fenceMatch) {
        inFencedBlock = true;
        var fc = fenceMatch[2];
        fenceCloseRe = new RegExp('^\\s*' + fc.charAt(0) + '{' + fc.length + ',}\\s*$');
        if (processed.length > 0 && !/^\s*$/.test(processed[processed.length - 1])) {
          processed.push('');
        }
        processed.push(line);
        continue;
      }
      var isHtmlLine = /^\s*<\/?[a-zA-Z]/.test(line);
      var isBlank = /^\s*$/.test(line);
      if (!isBlank && !isHtmlLine && processed.length > 0) {
        var prevNonBlank = '';
        for (var p = processed.length - 1; p >= 0; p--) {
          if (!/^\s*$/.test(processed[p])) { prevNonBlank = processed[p]; break; }
        }
        if (/>\s*$/.test(prevNonBlank) && !/^\s*$/.test(processed[processed.length - 1])) {
          processed.push('');
        }
      }
      if (isHtmlLine && processed.length > 0) {
        var prevNonBlank = '';
        for (var p = processed.length - 1; p >= 0; p--) {
          if (!/^\s*$/.test(processed[p])) { prevNonBlank = processed[p]; break; }
        }
        if (prevNonBlank && !/>\s*$/.test(prevNonBlank) && !/^\s*</.test(prevNonBlank) && !/^\s*$/.test(processed[processed.length - 1])) {
          processed.push('');
        }
      }
      processed.push(line);
    }
    var mdText = processed.join('\n');
    try {
      return marked.parse(mdText, { gfm: true });
    } catch (e) {
      return decoded;
    }
  }

  function _enhanceRawHtmlBlock(block) {
    if (!block) return;
    var pres = block.querySelectorAll('pre[data-title], pre[data-linenums], pre[data-lang]');
    for (var i = 0; i < pres.length; i++) {
      var pre = pres[i];
      if (pre.parentNode && pre.parentNode.classList && pre.parentNode.classList.contains('md-code-block')) continue;
      var wrapper = document.createElement('div');
      wrapper.className = 'md-code-block';
      var title = pre.getAttribute('data-title');
      var lang = pre.getAttribute('data-lang') || '';
      if (title || lang) {
        var headerBar = document.createElement('div');
        if (title) {
          headerBar.className = 'md-code-title';
          headerBar.textContent = title;
        } else {
          headerBar.className = 'md-code-lang';
          headerBar.textContent = lang;
        }
        headerBar.setAttribute('contenteditable', 'false');
        wrapper.appendChild(headerBar);
      }
      pre.parentNode.insertBefore(wrapper, pre);
      wrapper.appendChild(pre);
      var linenums = pre.getAttribute('data-linenums');
      if (linenums) {
        var codeEl = pre.querySelector('code');
        var text = codeEl ? codeEl.textContent : pre.textContent;
        var lineCount = text.split('\n').length;
        if (text.endsWith('\n')) lineCount--;
        var startNum = parseInt(linenums, 10) || 1;
        var gutter = document.createElement('div');
        gutter.className = 'md-code-line-numbers';
        gutter.setAttribute('contenteditable', 'false');
        for (var n = 0; n < lineCount; n++) {
          var span = document.createElement('span');
          span.textContent = String(startNum + n);
          span.setAttribute('data-line', String(startNum + n));
          gutter.appendChild(span);
        }
        pre.insertBefore(gutter, pre.firstChild);
      }
    }
  }

  function _dedentLines(text) {
    if (!text) return text;
    var lines = text.split('\n');
    var minIndent = Infinity;
    for (var i = 0; i < lines.length; i++) {
      if (!lines[i].trim()) continue;
      var m = lines[i].match(/^(\s*)/);
      if (m && m[1].length < minIndent) minIndent = m[1].length;
    }
    if (minIndent <= 0 || minIndent === Infinity) return text;
    return lines.map(function (l) { return l.substring(Math.min(minIndent, l.length)); }).join('\n');
  }

  function populateRawHtmlBlocks(editableArea) {
    if (!editableArea) return;
    var blocks = editableArea.querySelectorAll('[' + RAW_HTML_BLOCK_ATTR + ']');
    for (var bi = 0; bi < blocks.length; bi++) {
      var block = blocks[bi];
      if (block._rawHtmlPopulated) continue;
      var b64 = block.getAttribute(RAW_HTML_BLOCK_ATTR);
      if (!b64) continue;
      var decoded = _b64Decode(b64);
      if (/^\s*<details\b/i.test(decoded)) {
        var summaryMatch = decoded.match(/<summary\b[^>]*>([\s\S]*?)<\/summary>/i);
        var summaryText = summaryMatch ? summaryMatch[1].replace(/<[^>]+>/g, '').trim() : 'Details';
        var bodyMd = decoded;
        bodyMd = bodyMd.replace(/^\s*<details\b[^>]*>\s*/i, '');
        bodyMd = bodyMd.replace(/\s*<\/details>\s*$/i, '');
        if (summaryMatch) bodyMd = bodyMd.replace(summaryMatch[0], '');
        bodyMd = bodyMd.replace(/^\n+/, '').replace(/\n+$/, '');
        bodyMd = _dedentLines(bodyMd);

        var newDetails = document.createElement('details');
        newDetails.className = 'note';
        newDetails.setAttribute('data-details-tag', '1');
        newDetails.setAttribute('data-default-collapsed', '1');
        newDetails.setAttribute('contenteditable', 'true');
        var newSummary = document.createElement('summary');
        newSummary.textContent = summaryText;
        newDetails.appendChild(newSummary);
        var bodyHtml = '<p><br></p>';
        if (bodyMd && typeof marked !== 'undefined') {
          var rawResult = preprocessRawHtml(bodyMd);
          bodyHtml = marked.parse(rawResult.markdown) || bodyHtml;
        }
        var bodyContainer = document.createElement('div');
        bodyContainer.innerHTML = bodyHtml;
        while (bodyContainer.firstChild) newDetails.appendChild(bodyContainer.firstChild);
        block.parentNode.replaceChild(newDetails, block);
        populateRawHtmlBlocks(newDetails);
        enhanceCodeBlocks(newDetails);
        enhanceChecklists(newDetails);
        enhanceAdmonitions(newDetails);
        enhanceImages(newDetails);
        addSettingsButtonToAdmonition(newDetails);
        continue;
      }
      if (typeof marked !== 'undefined') {
        block.innerHTML = _renderMarkdownInRawHtml(decoded);
        _enhanceRawHtmlBlock(block);
      } else {
        block.innerHTML = decoded;
      }
      block.setAttribute('contenteditable', 'false');
      block.style.border = '1px dashed var(--md-default-fg-color--lighter, #ccc)';
      block.style.borderRadius = '4px';
      block.style.padding = '4px';
      block.style.margin = '4px 0';
      block.style.opacity = '0.85';
      block.style.pointerEvents = 'none';
      block._rawHtmlPopulated = true;
    }
  }

  function _isInsideRawHtmlBlock(el) {
    var p = el.parentNode;
    while (p && p !== document) {
      if (p.getAttribute && p.getAttribute(RAW_HTML_BLOCK_ATTR)) return true;
      p = p.parentNode;
    }
    return false;
  }

  function _upgradeBarDetailsElement(det) {
    if (_isInsideRawHtmlBlock(det)) return;
    if (det.querySelector(':scope > .md-admonition-settings-btn')) return;
    var hasTypeClass = false;
    for (var t = 0; t < ADMONITION_TYPE_IDS.length; t++) {
      if (det.classList.contains(ADMONITION_TYPE_IDS[t])) { hasTypeClass = true; break; }
    }
    if (hasTypeClass) return;
    det.classList.add('note');
    det.setAttribute('data-details-tag', '1');
    det.setAttribute('data-default-collapsed', '1');
    det.setAttribute('contenteditable', 'true');
    if (!det.querySelector(':scope > summary')) {
      var sum = document.createElement('summary');
      sum.textContent = 'Details';
      det.insertBefore(sum, det.firstChild);
    }
    if (typeof marked !== 'undefined') {
      _parseDetailsTextNodeRuns(det);
    }
    var hasBody = false;
    for (var bi = 0; bi < det.childNodes.length; bi++) {
      if (det.childNodes[bi].nodeName !== 'SUMMARY') { hasBody = true; break; }
    }
    if (!hasBody) {
      var emptyP = document.createElement('p');
      emptyP.innerHTML = '<br>';
      det.appendChild(emptyP);
    }
    populateRawHtmlBlocks(det);
    enhanceCodeBlocks(det);
    enhanceChecklists(det);
    enhanceAdmonitions(det);
    enhanceImages(det);
  }

  function _parseDetailsTextNodeRuns(container) {
    var runs = [];
    var currentRun = [];
    for (var i = 0; i < container.childNodes.length; i++) {
      var ch = container.childNodes[i];
      if (ch.nodeName === 'SUMMARY') continue;
      if (ch.nodeType === 3) {
        currentRun.push(ch);
      } else {
        if (currentRun.length > 0) {
          runs.push({ nodes: currentRun.slice(), insertBefore: ch });
          currentRun = [];
        }
      }
    }
    if (currentRun.length > 0) {
      runs.push({ nodes: currentRun.slice(), insertBefore: null });
    }
    for (var r = 0; r < runs.length; r++) {
      var run = runs[r];
      var md = '';
      for (var n = 0; n < run.nodes.length; n++) {
        md += run.nodes[n].textContent;
      }
      md = md.replace(/^\n+/, '').replace(/\n+$/, '');
      if (!md || !/\S/.test(md)) {
        for (var rn = 0; rn < run.nodes.length; rn++) {
          if (run.nodes[rn].parentNode === container) container.removeChild(run.nodes[rn]);
        }
        continue;
      }
      var rawResult = preprocessRawHtml(md);
      var html = marked.parse(rawResult.markdown) || '';
      if (!html) continue;
      var tempDiv = document.createElement('div');
      tempDiv.innerHTML = html;
      var insertPoint = run.insertBefore;
      while (tempDiv.firstChild) {
        container.insertBefore(tempDiv.firstChild, insertPoint);
      }
      for (var rn2 = 0; rn2 < run.nodes.length; rn2++) {
        if (run.nodes[rn2].parentNode === container) container.removeChild(run.nodes[rn2]);
      }
    }
  }

  function enhanceAdmonitions(editableArea) {
    if (!editableArea) return;
    var admonitions = editableArea.querySelectorAll('.admonition');
    for (var i = 0; i < admonitions.length; i++) {
      if (_isInsideRawHtmlBlock(admonitions[i])) continue;
      addSettingsButtonToAdmonition(admonitions[i]);
    }
    var allDetails = editableArea.querySelectorAll('details');
    for (var di = 0; di < allDetails.length; di++) {
      _upgradeBarDetailsElement(allDetails[di]);
    }
    for (var j = 0; j < ADMONITION_TYPE_IDS.length; j++) {
      var detailsEls = editableArea.querySelectorAll('details.' + ADMONITION_TYPE_IDS[j]);
      for (var k = 0; k < detailsEls.length; k++) {
        var det = detailsEls[k];
        if (_isInsideRawHtmlBlock(det)) continue;
        det.setAttribute('open', '');
        addSettingsButtonToAdmonition(det);
        var summary = det.querySelector(':scope > summary');
        if (summary) {
          if (!summary.dataset.liveWysiwygClickPatched) {
            summary.dataset.liveWysiwygClickPatched = '1';
            summary.addEventListener('click', function (e) {
              var d = this.parentNode;
              if (d && d.nodeName === 'DETAILS') {
                requestAnimationFrame(function () { d.setAttribute('open', ''); });
              }
            });
          }
        }
      }
    }
  }

  (function patchInsertAdmonition() {
    var proto = MarkdownWYSIWYG.prototype;
    var dropdown = null;
    var activeEditor = null;

    function getOrCreateDropdown(editor) {
      if (dropdown) return dropdown;
      dropdown = document.createElement('div');
      dropdown.className = 'md-admonition-dropdown';
      dropdown.style.cssText = 'display:none;position:absolute;z-index:99999;background:var(--md-default-bg-color, #fff);border:1px solid var(--md-default-fg-color--lighter, #ccc);border-radius:4px;box-shadow:var(--md-shadow-z2, 0 2px 8px rgba(0,0,0,0.15));min-width:160px;padding:4px 0;margin-top:2px;';
      for (var i = 0; i < ADMONITION_TYPES.length; i++) {
        (function (t) {
          var item = document.createElement('button');
          item.type = 'button';
          item.className = 'md-admonition-dropdown-item';
          item.style.cssText = 'display:flex;align-items:center;gap:8px;width:calc(100% - 8px);margin:1px 4px;padding:5px 10px;border:1px solid transparent;border-radius:3px;background:transparent;cursor:pointer;font-size:13px;color:var(--md-default-fg-color, #333);text-align:left;transition:background 0.1s,border-color 0.1s;';
          var iconSpan = document.createElement('span');
          iconSpan.style.cssText = 'display:inline-flex;align-items:center;flex-shrink:0;color:' + t.color + ';';
          iconSpan.innerHTML = t.icon;
          var label = document.createElement('span');
          label.textContent = t.label;
          item.appendChild(iconSpan);
          item.appendChild(label);
          item.addEventListener('mouseenter', function () { item.style.background = 'var(--md-accent-fg-color--transparent, #cce5ff)'; item.style.borderColor = 'var(--md-accent-fg-color, #007bff)'; });
          item.addEventListener('mouseleave', function () { item.style.background = 'transparent'; item.style.borderColor = 'transparent'; });
          item.addEventListener('click', function (e) {
            e.stopPropagation();
            hideDropdown();
            if (activeEditor) insertAdmonition(activeEditor, t.id);
          });
          dropdown.appendChild(item);
        })(ADMONITION_TYPES[i]);
      }
      document.body.appendChild(dropdown);
      return dropdown;
    }

    function showDropdown(editor, buttonEl) {
      activeEditor = editor;
      var dd = getOrCreateDropdown(editor);
      if (editor.currentMode === 'wysiwyg') {
        var sel = window.getSelection();
        if (sel && sel.rangeCount > 0 && editor.editableArea.contains(sel.getRangeAt(0).commonAncestorContainer)) {
          editor.savedRangeInfo = sel.getRangeAt(0).cloneRange();
        }
      } else {
        editor.savedRangeInfo = { start: editor.markdownArea.selectionStart, end: editor.markdownArea.selectionEnd };
      }
      var rect = buttonEl.getBoundingClientRect();
      dd.style.display = 'block';
      dd.style.top = (rect.bottom + window.scrollY + 2) + 'px';
      dd.style.left = (rect.left + window.scrollX) + 'px';
      _admonitionDropdownDismiss = hideDropdown;
      setTimeout(function () {
        document.addEventListener('click', onDocClick, true);
      }, 0);
    }

    function hideDropdown() {
      if (dropdown) dropdown.style.display = 'none';
      document.removeEventListener('click', onDocClick, true);
      _admonitionDropdownDismiss = null;
    }

    function onDocClick(e) {
      if (dropdown && !dropdown.contains(e.target)) hideDropdown();
    }

    function insertAdmonition(editor, type) {
      var title = type.charAt(0).toUpperCase() + type.slice(1);
      if (editor.currentMode === 'wysiwyg') {
        var ea = editor.editableArea;
        ea.focus();
        var sel = window.getSelection();
        if (editor.savedRangeInfo instanceof Range && ea.contains(editor.savedRangeInfo.commonAncestorContainer)) {
          sel.removeAllRanges();
          sel.addRange(editor.savedRangeInfo);
        }
        var adDiv = document.createElement('div');
        adDiv.className = 'admonition ' + type;
        adDiv.setAttribute('contenteditable', 'true');
        var titleP = document.createElement('p');
        titleP.className = 'admonition-title';
        titleP.textContent = title;
        var bodyP = document.createElement('p');
        bodyP.textContent = 'Content here.';
        adDiv.appendChild(titleP);
        adDiv.appendChild(bodyP);
        var range = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
        if (range) {
          var insertParent = ea;
          var targetBlock = null;
          var ancestor = range.startContainer;
          if (ancestor.nodeType === 3) ancestor = ancestor.parentNode;
          var foundContainer = null;
          var cur = ancestor;
          while (cur && cur !== ea) {
            if (isAdmonitionElement(cur)) { foundContainer = cur; break; }
            if (cur.nodeName === 'BLOCKQUOTE') { foundContainer = cur; break; }
            cur = cur.parentNode;
          }
          if (foundContainer) {
            insertParent = foundContainer;
            var inner = ancestor;
            while (inner && inner !== foundContainer && inner.parentNode !== foundContainer) {
              inner = inner.parentNode;
            }
            if (inner && inner !== foundContainer && inner.parentNode === foundContainer) {
              var isTitleOrGear = (inner.classList && (inner.classList.contains('admonition-title') || inner.classList.contains('md-admonition-settings-btn'))) || inner.nodeName === 'SUMMARY';
              if (!isTitleOrGear) targetBlock = inner;
            }
          } else {
            var block = ancestor;
            while (block && block !== ea && block.parentNode !== ea) {
              block = block.parentNode;
            }
            if (block && block !== ea && block.parentNode === ea) {
              targetBlock = block;
            }
          }
          if (targetBlock && targetBlock.parentNode === insertParent) {
            var blockText = (targetBlock.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
            var hasContent = blockText.length > 0;
            if (hasContent) {
              insertParent.insertBefore(adDiv, targetBlock.nextSibling);
            } else {
              insertParent.insertBefore(adDiv, targetBlock);
              insertParent.removeChild(targetBlock);
            }
          } else {
            range.collapse(false);
            range.insertNode(adDiv);
          }
          var newRange = document.createRange();
          newRange.selectNodeContents(bodyP);
          sel.removeAllRanges();
          sel.addRange(newRange);
        } else {
          ea.appendChild(adDiv);
        }
        enhanceAdmonitions(ea);
        editor.savedRangeInfo = null;
        editor._finalizeUpdate(ea.innerHTML);
      } else {
        var textarea = editor.markdownArea;
        var start, end;
        if (editor.savedRangeInfo && typeof editor.savedRangeInfo.start === 'number') {
          start = editor.savedRangeInfo.start;
          end = editor.savedRangeInfo.end;
        } else {
          start = textarea.selectionStart;
          end = textarea.selectionEnd;
        }
        var text = textarea.value;
        var before = text.substring(0, start);
        var after = text.substring(end);
        var prefix = (before.length > 0 && !before.endsWith('\n')) ? '\n' : '';
        var suffix = (after.length > 0 && !after.startsWith('\n')) ? '\n' : '';
        var snippet = prefix + '!!! ' + type + '\n    Content here.\n' + suffix;
        textarea.value = before + snippet + after;
        var cursorStart = before.length + prefix.length + ('!!! ' + type + '\n    ').length;
        textarea.focus();
        textarea.setSelectionRange(cursorStart, cursorStart + 'Content here.'.length);
        editor.savedRangeInfo = null;
        editor._finalizeUpdate(textarea.value);
      }
    }

    proto._insertAdmonition = function (buttonEl) {
      if (dropdown && dropdown.style.display !== 'none') {
        hideDropdown();
        return;
      }
      var btn = buttonEl || (this.toolbar && this.toolbar.querySelector('.md-toolbar-button-admonition'));
      if (btn) showDropdown(this, btn);
    };
  })();

  (function patchBlockquoteInAdmonition() {
    var proto = MarkdownWYSIWYG.prototype;
    var origWrap = proto._wrapSelectionInBlockquote;
    if (!origWrap) return;
    proto._wrapSelectionInBlockquote = function () {
      _flushHistoryCapture();
      var ea = this.editableArea;
      var sel = window.getSelection();
      if (!sel || sel.rangeCount === 0) return origWrap.call(this);
      var range = sel.getRangeAt(0);
      var node = range.startContainer;
      if (node.nodeType === 3) node = node.parentNode;
      var ad = null;
      var anc = node;
      while (anc && anc !== ea) {
        if (anc.classList && anc.classList.contains('admonition')) {
          ad = anc;
          break;
        }
        anc = anc.parentNode;
      }
      if (!ad) return origWrap.call(this);
      var topBlockFor = function (n, container) {
        var cur = n;
        if (cur.nodeType === 3) cur = cur.parentNode;
        while (cur && cur.parentNode !== container) cur = cur.parentNode;
        return cur;
      };
      var startBlock = topBlockFor(range.startContainer, ad);
      var endBlock = topBlockFor(range.endContainer, ad);
      var titleEl = ad.querySelector('.admonition-title');
      var bodyBlocks = [];
      for (var i = 0; i < ad.childNodes.length; i++) {
        var c = ad.childNodes[i];
        if (c !== titleEl) bodyBlocks.push(c);
      }
      var startIdx = bodyBlocks.indexOf(startBlock);
      var endIdx = bodyBlocks.indexOf(endBlock);
      if (startIdx === -1) startIdx = 0;
      if (endIdx === -1) endIdx = startIdx;
      if (startIdx > endIdx) { var t = startIdx; startIdx = endIdx; endIdx = t; }
      var blocks = bodyBlocks.slice(startIdx, endIdx + 1);
      if (blocks.length === 0) return origWrap.call(this);
      var isEmptyNode = function (n) {
        if (n.nodeType === 3) return !n.textContent.replace(/[\s\u00a0]/g, '');
        if (n.nodeName === 'BR') return true;
        var text = (n.textContent || '').replace(/[\s\u00a0]/g, '');
        if (!text && !n.querySelector('img, table, hr')) return true;
        return false;
      };
      var filtered = [];
      for (var i = 0; i < blocks.length; i++) {
        if (!isEmptyNode(blocks[i])) filtered.push(blocks[i]);
      }
      if (filtered.length === 0) return origWrap.call(this);
      var bq = document.createElement('blockquote');
      ad.insertBefore(bq, filtered[0]);
      for (var j = 0; j < blocks.length; j++) {
        var block = blocks[j];
        if (filtered.indexOf(block) === -1) {
          if (block.parentNode) block.parentNode.removeChild(block);
        } else {
          if (this._isBlockElement(block)) {
            bq.appendChild(block);
          } else {
            var p = document.createElement('p');
            p.appendChild(block);
            bq.appendChild(p);
          }
        }
      }
      sel.removeAllRanges();
      var newRange = document.createRange();
      newRange.selectNodeContents(bq);
      sel.addRange(newRange);
      this._finalizeUpdate(ea.innerHTML);
    };
  })();

  (function patchHeadingDropdownForFocusMode() {
    var proto = MarkdownWYSIWYG.prototype;
    var origShow = proto._showHeadingDropdown;
    if (!origShow) return;
    proto._showHeadingDropdown = function () {
      origShow.call(this);
      if (isFocusModeActive && this.headingDropdown && this.headingButton) {
        var rect = this.headingButton.getBoundingClientRect();
        var dd = this.headingDropdown;
        dd.style.position = 'fixed';
        dd.style.top = (rect.bottom + 2) + 'px';
        dd.style.left = rect.left + 'px';
        dd.style.zIndex = '10000';
      }
    };
    var origHide = proto._hideHeadingDropdown;
    if (!origHide) return;
    proto._hideHeadingDropdown = function () {
      origHide.call(this);
      if (this.headingDropdown) {
        this.headingDropdown.style.position = '';
        this.headingDropdown.style.top = '';
        this.headingDropdown.style.left = '';
        this.headingDropdown.style.zIndex = '';
      }
    };
  })();

  (function patchTableGridSelectorForFocusMode() {
    var proto = MarkdownWYSIWYG.prototype;
    var origShow = proto._showTableGridSelector;
    if (!origShow) return;
    proto._showTableGridSelector = function (buttonElement) {
      origShow.call(this, buttonElement);
      if (isFocusModeActive && this.tableGridSelector && buttonElement) {
        var rect = buttonElement.getBoundingClientRect();
        var gs = this.tableGridSelector;
        gs.style.position = 'fixed';
        gs.style.top = (rect.bottom + 5) + 'px';
        gs.style.left = rect.left + 'px';
        gs.style.zIndex = '10000';
        var gsRect = gs.getBoundingClientRect();
        if (gsRect.right > window.innerWidth - 10) {
          gs.style.left = (window.innerWidth - gsRect.width - 10) + 'px';
        }
        if (gsRect.left < 10) {
          gs.style.left = '10px';
        }
      }
    };
    var origHide = proto._hideTableGridSelector;
    if (!origHide) return;
    proto._hideTableGridSelector = function () {
      origHide.call(this);
      if (this.tableGridSelector) {
        this.tableGridSelector.style.position = '';
        this.tableGridSelector.style.top = '';
        this.tableGridSelector.style.left = '';
        this.tableGridSelector.style.zIndex = '';
      }
    };
  })();

  (function patchInsertCodeBlock() {
    var proto = MarkdownWYSIWYG.prototype;
    var origInsertCodeBlock = proto._insertCodeBlock;
    if (!origInsertCodeBlock) return;
    proto._insertCodeBlock = function () {
      _flushHistoryCapture();
      if (this.currentMode === 'wysiwyg') {
        var ea = this.editableArea;
        ea.focus();
        var selection = window.getSelection();
        var initialSelectedText = selection ? selection.toString() : '';
        var pre = document.createElement('pre');
        var code = document.createElement('code');
        code.textContent = initialSelectedText || 'code';
        pre.appendChild(code);
        if (selection && selection.rangeCount > 0) {
          var range = selection.getRangeAt(0);
          var block = range.startContainer;
          if (block.nodeType === 3) block = block.parentNode;
          while (block && block !== ea && block.parentNode !== ea) {
            block = block.parentNode;
          }
          var insertParent = ea;
          var targetBlock = null;
          var anc = range.startContainer;
          if (anc.nodeType === 3) anc = anc.parentNode;
          while (anc && anc !== ea) {
            var inLi = anc.nodeName === 'LI' && anc.parentNode && (anc.parentNode.nodeName === 'UL' || anc.parentNode.nodeName === 'OL');
            if ((anc.classList && anc.classList.contains('admonition')) || anc.nodeName === 'BLOCKQUOTE' || inLi) {
              insertParent = anc;
              var inner = range.startContainer;
              if (inner.nodeType === 3) inner = inner.parentNode;
              while (inner && inner !== anc && inner.parentNode !== anc) {
                inner = inner.parentNode;
              }
              if (inner && inner !== anc && inner.parentNode === anc) {
                targetBlock = inner;
              }
              break;
            }
            anc = anc.parentNode;
          }
          if (insertParent === ea && block && block !== ea && block.parentNode === ea) {
            targetBlock = block;
          }
          if (targetBlock && targetBlock.parentNode === insertParent) {
            var blockText = (targetBlock.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
            var hasContent = blockText.length > 0;
            if (hasContent && !initialSelectedText) {
              insertParent.insertBefore(pre, targetBlock.nextSibling);
            } else if (hasContent) {
              range.deleteContents();
              var blockTextAfter = (targetBlock.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
              if (blockTextAfter.length === 0) {
                insertParent.insertBefore(pre, targetBlock);
                insertParent.removeChild(targetBlock);
              } else {
                insertParent.insertBefore(pre, targetBlock.nextSibling);
              }
            } else {
              insertParent.insertBefore(pre, targetBlock);
              insertParent.removeChild(targetBlock);
            }
          } else {
            range.deleteContents();
            range.insertNode(pre);
          }
          var newRange = document.createRange();
          newRange.selectNodeContents(code);
          selection.removeAllRanges();
          selection.addRange(newRange);
        } else {
          ea.appendChild(pre);
        }
        enhanceBasicPreBlocks(ea);
        this._finalizeUpdate(ea.innerHTML);
      } else {
        origInsertCodeBlock.call(this);
      }
    };
  })();

  (function patchInsertInlineCode() {
    var proto = MarkdownWYSIWYG.prototype;
    var origInsertInlineCode = proto._insertInlineCode;
    if (!origInsertInlineCode) return;
    proto._insertInlineCode = function () {
      if (this.currentMode !== 'wysiwyg') {
        origInsertInlineCode.call(this);
        return;
      }
      var ea = this.editableArea;
      ea.focus();
      var sel = window.getSelection();
      if (!sel || !sel.rangeCount) {
        origInsertInlineCode.call(this);
        return;
      }

      var range = sel.getRangeAt(0);
      var node = range.commonAncestorContainer;
      if (node.nodeType === 3) node = node.parentNode;

      var codeAncestor = null;
      var anc = node;
      while (anc && anc !== ea) {
        if (anc.nodeName === 'CODE' && (!anc.parentNode || anc.parentNode.nodeName !== 'PRE')) {
          codeAncestor = anc;
          break;
        }
        anc = anc.parentNode;
      }

      if (!sel.isCollapsed) {
        var codeEls = [];
        var searchRoot = range.commonAncestorContainer;
        if (searchRoot.nodeType === 3) searchRoot = searchRoot.parentNode;
        while (searchRoot && searchRoot !== ea && searchRoot.nodeName !== 'CODE') {
          if (searchRoot.parentNode === ea || searchRoot.parentNode === null) break;
          searchRoot = searchRoot.parentNode;
        }
        if (!searchRoot || searchRoot.nodeName === 'CODE') searchRoot = ea;
        var codes = searchRoot.querySelectorAll('code');
        for (var i = 0; i < codes.length; i++) {
          if (codes[i].parentNode && codes[i].parentNode.nodeName === 'PRE') continue;
          var codeRange = document.createRange();
          codeRange.selectNode(codes[i]);
          var overlaps = range.compareBoundaryPoints(Range.START_TO_END, codeRange) > 0 &&
                         range.compareBoundaryPoints(Range.END_TO_START, codeRange) < 0;
          if (overlaps) codeEls.push(codes[i]);
        }
        if (codeAncestor && codeEls.indexOf(codeAncestor) === -1) {
          codeEls.push(codeAncestor);
        }

        if (codeEls.length > 0) {
          var firstText = null;
          var lastText = null;
          var totalLen = 0;
          for (var j = 0; j < codeEls.length; j++) {
            var ce = codeEls[j];
            var parent = ce.parentNode;
            var text = ce.textContent;
            var textNode = document.createTextNode(text);
            parent.insertBefore(textNode, ce);
            parent.removeChild(ce);
            if (!firstText) firstText = textNode;
            lastText = textNode;
            totalLen += text.length;
          }
          if (firstText && lastText) {
            var newRange = document.createRange();
            newRange.setStart(firstText, 0);
            newRange.setEnd(lastText, lastText.textContent.length);
            sel.removeAllRanges();
            sel.addRange(newRange);
          }
          if (this._finalizeUpdate) this._finalizeUpdate(ea.innerHTML);
          return;
        }

        origInsertInlineCode.call(this);
        return;
      }

      if (codeAncestor) {
        var text = codeAncestor.textContent;
        var parent = codeAncestor.parentNode;
        var textNode = document.createTextNode(text);
        parent.insertBefore(textNode, codeAncestor);
        parent.removeChild(codeAncestor);
        var cursorRange = document.createRange();
        cursorRange.setStart(textNode, 0);
        cursorRange.setEnd(textNode, text.length);
        sel.removeAllRanges();
        sel.addRange(cursorRange);
        if (this._finalizeUpdate) this._finalizeUpdate(ea.innerHTML);
        return;
      }

      origInsertInlineCode.call(this);
    };
  })();

  (function patchInsertLink() {
    var proto = MarkdownWYSIWYG.prototype;
    var origInsertLink = proto._insertLink;
    if (!origInsertLink) return;

    var _activeLinkDropdown = null;
    function dismissLinkDropdown() {
      if (_activeLinkDropdown) {
        if (_activeLinkDropdown.el.parentNode) _activeLinkDropdown.el.parentNode.removeChild(_activeLinkDropdown.el);
        if (_activeLinkDropdown.closeHandler) document.removeEventListener('mousedown', _activeLinkDropdown.closeHandler, true);
        if (_activeLinkDropdown.scrollHandler) window.removeEventListener('scroll', _activeLinkDropdown.scrollHandler, true);
        _activeLinkDropdown = null;
      }
    }

    function findAnchorInSelection(editableArea) {
      var sel = window.getSelection();
      if (!sel || sel.rangeCount === 0) return null;
      var node = sel.getRangeAt(0).commonAncestorContainer;
      if (node.nodeType === 3) node = node.parentNode;
      while (node && node !== editableArea) {
        if (node.nodeName === 'A' && node.getAttribute('href')) return node;
        node = node.parentNode;
      }
      return null;
    }


    function _repositionLinkDropdown(dropdown) {
      if (!dropdown._posRef || !dropdown.parentNode) return;
      var rect = dropdown._posRef.getBoundingClientRect();
      var ddRect = dropdown.getBoundingClientRect();
      var left = rect.left;
      if (left + ddRect.width > window.innerWidth - 8) {
        left = Math.max(4, window.innerWidth - ddRect.width - 8);
      }
      var top = rect.bottom + 4;
      if (top + ddRect.height > window.innerHeight - 8) {
        top = Math.max(4, rect.top - ddRect.height - 4);
      }
      dropdown.style.top = top + 'px';
      dropdown.style.left = left + 'px';
    }

    function createLinkDropdown(anchorBtn, editor, targetAnchorEl) {
      dismissLinkDropdown();
      dismissAdmonitionSettingsDropdown();
      dismissActiveSettingsDropdown();
      dismissActiveLangDropdown();
      dismissImageInsertDropdown();
      dismissImageGearDropdown();
      _hideLinkChain();

      var ea = editor.editableArea;
      var ma = editor.markdownArea;
      var isWysiwyg = editor.currentMode === 'wysiwyg';

      var existingAnchor = targetAnchorEl || null;
      if (!existingAnchor) {
        var savedRange = editor.savedRangeInfo;
        if (isWysiwyg && savedRange instanceof Range && ea.contains(savedRange.commonAncestorContainer)) {
          var sel = window.getSelection();
          sel.removeAllRanges();
          sel.addRange(savedRange);
        } else if (!isWysiwyg && ma && savedRange && typeof savedRange.start === 'number') {
          ma.setSelectionRange(savedRange.start, savedRange.end);
        }
        existingAnchor = isWysiwyg ? findAnchorInSelection(ea) : null;
      }
      var initialUrl = existingAnchor ? (existingAnchor.getAttribute('href') || '') : 'https://';
      var initialText = '';
      if (existingAnchor) {
        initialText = (existingAnchor.textContent || '').trim();
      } else if (isWysiwyg) {
        var savedRange = editor.savedRangeInfo;
        var sel = window.getSelection();
        if (sel && sel.rangeCount > 0) initialText = sel.toString().trim();
        if (!initialText && savedRange instanceof Range && ea.contains(savedRange.commonAncestorContainer)) {
          initialText = savedRange.toString().trim();
        }
      } else if (ma) {
        var savedRange = editor.savedRangeInfo;
        var start = savedRange && typeof savedRange.start === 'number' ? savedRange.start : ma.selectionStart;
        var end = savedRange && typeof savedRange.end === 'number' ? savedRange.end : ma.selectionEnd;
        if (start !== end) initialText = ma.value.substring(start, end).trim();
      }

      var dropdown = document.createElement('div');
      dropdown.className = 'md-link-settings-dropdown';
      dropdown.setAttribute('contenteditable', 'false');

      var posRef = targetAnchorEl || anchorBtn;
      dropdown._posRef = posRef;

      var urlRow = document.createElement('div');
      urlRow.className = 'md-link-settings-row';
      var urlLabel = document.createElement('span');
      urlLabel.className = 'md-link-settings-label';
      urlLabel.textContent = 'URL';
      var urlInput = document.createElement('input');
      urlInput.className = 'md-link-settings-input';
      urlInput.type = 'text';
      urlInput.placeholder = 'https://';
      urlInput.value = initialUrl;
      urlRow.appendChild(urlLabel);
      urlRow.appendChild(urlInput);
      dropdown.appendChild(urlRow);

      var textRow = document.createElement('div');
      textRow.className = 'md-link-settings-row';
      var textLabel = document.createElement('span');
      textLabel.className = 'md-link-settings-label';
      textLabel.textContent = 'Text';
      var textInput = document.createElement('input');
      textInput.className = 'md-link-settings-input';
      textInput.type = 'text';
      textInput.placeholder = 'link text';
      textInput.value = initialText;
      textRow.appendChild(textLabel);
      textRow.appendChild(textInput);
      dropdown.appendChild(textRow);

      var removeRow = null;
      if (existingAnchor) {
        removeRow = document.createElement('div');
        removeRow.className = 'md-link-settings-row md-link-settings-apply-row';
        var removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'md-link-settings-remove';
        removeBtn.textContent = 'Remove';
        removeBtn.addEventListener('mousedown', function (ev) {
          ev.preventDefault();
          ev.stopPropagation();
          if (existingAnchor && existingAnchor.parentNode) {
            var parent = existingAnchor.parentNode;
            while (existingAnchor.firstChild) parent.insertBefore(existingAnchor.firstChild, existingAnchor);
            parent.removeChild(existingAnchor);
            if (editor._finalizeUpdate) editor._finalizeUpdate(ea.innerHTML);
          }
          dismissLinkDropdown();
        });
        removeRow.appendChild(removeBtn);
      }

      var applyRow = document.createElement('div');
      applyRow.className = 'md-link-settings-row md-link-settings-apply-row';
      if (removeRow) applyRow.style.paddingTop = '0';
      var applyBtn = document.createElement('button');
      applyBtn.type = 'button';
      applyBtn.className = 'md-link-settings-apply';
      applyBtn.textContent = existingAnchor ? 'Update' : 'Insert';
      applyRow.appendChild(applyBtn);
      if (removeRow) { dropdown.appendChild(removeRow); }
      dropdown.appendChild(applyRow);

      function doApply() {
        var url = (urlInput.value || '').trim();
        if (!url) return;
        var text = (textInput.value || '').trim();
        if (!text && !existingAnchor) text = 'link text';

        if (isWysiwyg) {
          ea.focus();
          var sel = window.getSelection();
          if (existingAnchor) {
            existingAnchor.setAttribute('href', url);
            if (text && text !== initialText) {
              existingAnchor.textContent = text;
            }
          } else {
            var savedRange = editor.savedRangeInfo;
            var rangeToUse = null;
            if (savedRange instanceof Range && ea.contains(savedRange.commonAncestorContainer)) {
              sel.removeAllRanges();
              sel.addRange(savedRange);
              rangeToUse = savedRange;
            } else if (sel && sel.rangeCount > 0 && ea.contains(sel.getRangeAt(0).commonAncestorContainer)) {
              rangeToUse = sel.getRangeAt(0);
            }
            if (rangeToUse) {
              var linkTextNode = document.createTextNode(text || 'link text');
              rangeToUse.deleteContents();
              rangeToUse.insertNode(linkTextNode);
              rangeToUse.selectNodeContents(linkTextNode);
              sel.removeAllRanges();
              sel.addRange(rangeToUse);
            }
            document.execCommand('createLink', false, url);
          }
          if (editor._finalizeUpdate) editor._finalizeUpdate(ea.innerHTML);
        } else {
          ma.focus();
          var savedRange = editor.savedRangeInfo;
          var start = savedRange && typeof savedRange.start === 'number' ? savedRange.start : ma.selectionStart;
          var end = savedRange && typeof savedRange.end === 'number' ? savedRange.end : ma.selectionEnd;
          var prefix = '[';
          var suffix = '](' + url + ')';
          var replacement = prefix + text + suffix;
          ma.value = ma.value.substring(0, start) + replacement + ma.value.substring(end);
          ma.setSelectionRange(start + prefix.length, start + prefix.length + text.length);
          if (editor._finalizeUpdate) editor._finalizeUpdate(ma.value);
        }
        dismissLinkDropdown();
      }

      urlInput.tabIndex = 1;
      textInput.tabIndex = 2;
      if (removeRow) { var removeBtn2 = removeRow.querySelector('.md-link-settings-remove'); if (removeBtn2) removeBtn2.tabIndex = 3; }
      applyBtn.tabIndex = removeRow ? 4 : 3;

      var dirty = false;
      function markDirty() { dirty = true; }
      urlInput.addEventListener('input', markDirty);
      textInput.addEventListener('input', markDirty);

      applyBtn.addEventListener('mousedown', function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        doApply();
      });

      _attachDialogKeyboard(dropdown, {
        category: 'form',
        isDirty: function () { return dirty; },
        onConfirm: function () { doApply(); },
        onDismiss: function () { dismissLinkDropdown(); }
      });

      var ddHost = _focusOverlay || document.body;
      ddHost.appendChild(dropdown);
      _repositionLinkDropdown(dropdown);
      _attachContainerExpandBehavior(dropdown, {
        selector: '.md-link-settings-input',
        onResize: function () { _repositionLinkDropdown(dropdown); }
      });
      requestAnimationFrame(function () {
        urlInput.focus(); urlInput.select();
        if (!existingAnchor && urlInput.value === 'https://') {
          try {
            navigator.clipboard.readText().then(function (text) {
              text = (text || '').trim();
              if (/^https?:\/\//.test(text)) {
                urlInput.value = text;
                urlInput.select();
                dirty = true;
              }
            }).catch(function () {});
          } catch (e) {}
        }
      });

      var chainIcon = (_focusOverlay || document).querySelector('.md-link-chain-indicator');
      var closeHandler = function (ev) {
        if (dropdown.contains(ev.target) || ev.target === anchorBtn) return;
        if (chainIcon && chainIcon.contains(ev.target)) return;
        dismissLinkDropdown();
      };
      var scrollHandler = function () { _repositionLinkDropdown(dropdown); };
      document.addEventListener('mousedown', closeHandler, true);
      window.addEventListener('scroll', scrollHandler, true);

      _activeLinkDropdown = { el: dropdown, closeHandler: closeHandler, scrollHandler: scrollHandler };
    }

    // --- Link chain indicator (cursor + delayed hover) ---
    var _linkChainEl = null;
    var _linkChainTarget = null;
    var _linkChainHideTimer = null;
    var _linkChainShowTimer = null;
    var _linkChainHoverAnchor = null;

    function _hideLinkChain() {
      clearTimeout(_linkChainHideTimer);
      clearTimeout(_linkChainShowTimer);
      _linkChainHoverAnchor = null;
      if (_linkChainEl && _linkChainEl.parentNode) _linkChainEl.parentNode.removeChild(_linkChainEl);
      _linkChainEl = null;
      _linkChainTarget = null;
    }

    function _positionLinkChain(icon, anchorEl) {
      var rect = anchorEl.getBoundingClientRect();
      var top = rect.top - 30;
      if (top < 4) top = rect.bottom + 4;
      icon.style.top = top + 'px';
      icon.style.left = rect.left + 'px';
    }

    function _showLinkChain(anchorEl) {
      if (_activeLinkDropdown) return;
      var ea = wysiwygEditor && wysiwygEditor.editableArea;
      if (!ea || !ea.contains(anchorEl)) return;
      if (_linkChainTarget === anchorEl && _linkChainEl && _linkChainEl.parentNode) {
        clearTimeout(_linkChainHideTimer);
        _positionLinkChain(_linkChainEl, anchorEl);
        return;
      }
      if (_linkChainEl && _linkChainEl.parentNode) _linkChainEl.parentNode.removeChild(_linkChainEl);
      _linkChainTarget = anchorEl;

      var icon = document.createElement('button');
      icon.type = 'button';
      icon.className = 'md-toolbar-button md-link-chain-indicator';
      icon.setAttribute('contenteditable', 'false');
      icon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>';
      icon.title = 'Edit link';

      icon.style.position = 'fixed';
      icon.style.zIndex = '99998';
      _positionLinkChain(icon, anchorEl);

      icon.addEventListener('mousedown', function (ev) {
        ev.preventDefault();
        ev.stopPropagation();
        var editor = wysiwygEditor;
        if (!editor || editor.currentMode !== 'wysiwyg') return;
        var sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(anchorEl);
        sel.removeAllRanges();
        sel.addRange(range);
        createLinkDropdown(icon, editor, anchorEl);
      });

      icon.addEventListener('mouseenter', function () {
        clearTimeout(_linkChainHideTimer);
      });
      icon.addEventListener('mouseleave', function () {
        _linkChainHideTimer = setTimeout(_hideLinkChain, 200);
      });

      var host = _focusOverlay || document.body;
      host.appendChild(icon);
      _linkChainEl = icon;
    }

    function _findAnchorAtCursor(editableArea) {
      var sel = window.getSelection();
      if (!sel || sel.rangeCount === 0) return null;
      var node = sel.getRangeAt(0).startContainer;
      if (node.nodeType === 3) node = node.parentNode;
      while (node && node !== editableArea) {
        if (node.nodeName === 'A' && node.getAttribute('href')) return node;
        node = node.parentNode;
      }
      return null;
    }

    function _attachLinkChainHandler(editableArea) {
      if (!editableArea || editableArea._linkChainAttached) return;
      editableArea._linkChainAttached = true;

      editableArea.addEventListener('mouseover', function (e) {
        if (_activeLinkDropdown) return;
        var node = e.target;
        while (node && node !== editableArea) {
          if (node.nodeName === 'A' && node.getAttribute('href')) {
            _linkChainHoverAnchor = node;
            clearTimeout(_linkChainShowTimer);
            clearTimeout(_linkChainHideTimer);
            _linkChainShowTimer = setTimeout(function () {
              if (_linkChainHoverAnchor === node) _showLinkChain(node);
            }, 400);
            return;
          }
          node = node.parentNode;
        }
        _linkChainHoverAnchor = null;
        clearTimeout(_linkChainShowTimer);
        if (_linkChainEl && !_activeLinkDropdown) {
          _linkChainHideTimer = setTimeout(_hideLinkChain, 200);
        }
      });

      editableArea.addEventListener('mouseleave', function () {
        _linkChainHoverAnchor = null;
        clearTimeout(_linkChainShowTimer);
        if (_linkChainEl && !_activeLinkDropdown) {
          _linkChainHideTimer = setTimeout(_hideLinkChain, 200);
        }
      });

      document.addEventListener('selectionchange', function () {
        if (!wysiwygEditor || wysiwygEditor.currentMode !== 'wysiwyg') return;
        if (_activeLinkDropdown) return;
        var anchor = _findAnchorAtCursor(editableArea);
        if (anchor) {
          clearTimeout(_linkChainHideTimer);
          _showLinkChain(anchor);
        } else if (_linkChainEl) {
          _hideLinkChain();
        }
      });
    }

    proto._insertLink = function (buttonElement) {
      if (!buttonElement) buttonElement = this.toolbar && this.toolbar.querySelector('.md-toolbar-button-link');
      createLinkDropdown(buttonElement || document.body, this);
    };

    proto._attachLinkChainHandler = function () {
      _attachLinkChainHandler(this.editableArea);
    };
  })();

  // ---- Image insertion dropdown, resize, gear settings ----

  var _activeImageInsertDropdown = null;
  var _activeImageGearDropdown = null;
  var _activeImageSelection = null;
  var _imageDocumentSizes = {};

  function _imageDocSizeKey(img) {
    return img.getAttribute('data-orig-src') || img.getAttribute('src') || '';
  }

  function dismissImageInsertDropdown() {
    if (_activeImageInsertDropdown) {
      if (_activeImageInsertDropdown.el.parentNode) _activeImageInsertDropdown.el.parentNode.removeChild(_activeImageInsertDropdown.el);
      if (_activeImageInsertDropdown.closeHandler) document.removeEventListener('mousedown', _activeImageInsertDropdown.closeHandler, true);
      if (_activeImageInsertDropdown.scrollHandler) window.removeEventListener('scroll', _activeImageInsertDropdown.scrollHandler, true);
      _activeImageInsertDropdown = null;
    }
  }

  function dismissImageGearDropdown() {
    if (_activeImageGearDropdown) {
      if (_activeImageGearDropdown.el.parentNode) _activeImageGearDropdown.el.parentNode.removeChild(_activeImageGearDropdown.el);
      if (_activeImageGearDropdown.closeHandler) document.removeEventListener('mousedown', _activeImageGearDropdown.closeHandler, true);
      if (_activeImageGearDropdown.scrollHandler) window.removeEventListener('scroll', _activeImageGearDropdown.scrollHandler, true);
      _activeImageGearDropdown = null;
    }
  }

  function dismissImageSelection() {
    if (_activeImageSelection) {
      var img = _activeImageSelection.img;
      if (img) img.classList.remove('md-image-selected');
      var rc = _activeImageSelection.resizeContainer;
      if (rc && rc.parentNode) rc.parentNode.removeChild(rc);
      if (_activeImageSelection.clickHandler) document.removeEventListener('mousedown', _activeImageSelection.clickHandler, true);
      _activeImageSelection = null;
    }
    dismissImageGearDropdown();
  }

  function _tryConvertToRelativeImageUrl(absUrl) {
    try {
      var parsed = new URL(absUrl);
      if (parsed.origin !== window.location.origin) return null;
      var parentDir = new URL('..', document.baseURI).href;
      var parentPath = new URL(parentDir).pathname;
      var imgPath = parsed.pathname;
      if (imgPath.indexOf(parentPath) === 0) {
        return imgPath.substring(parentPath.length);
      }
      return imgPath;
    } catch (e) { return null; }
  }

  function createImageInsertDropdown(anchorBtn, editor) {
    dismissImageInsertDropdown();
    dismissImageGearDropdown();
    dismissActiveSettingsDropdown();
    dismissActiveLangDropdown();
    dismissAdmonitionSettingsDropdown();

    var ea = editor.editableArea;
    var ma = editor.markdownArea;
    var isWysiwyg = editor.currentMode === 'wysiwyg';
    var savedRange = editor.savedRangeInfo;

    if (isWysiwyg && savedRange instanceof Range && ea.contains(savedRange.commonAncestorContainer)) {
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(savedRange);
    } else if (!isWysiwyg && ma && savedRange && typeof savedRange.start === 'number') {
      ma.setSelectionRange(savedRange.start, savedRange.end);
    }

    var dropdown = document.createElement('div');
    dropdown.className = 'md-image-insert-dropdown';
    dropdown.setAttribute('contenteditable', 'false');

    var urlRow = document.createElement('div');
    urlRow.className = 'md-image-insert-row';
    var urlLabel = document.createElement('span');
    urlLabel.className = 'md-image-insert-label';
    urlLabel.textContent = 'URL';
    var urlInput = document.createElement('input');
    urlInput.className = 'md-image-insert-input';
    urlInput.type = 'text';
    urlInput.placeholder = 'https:// or relative path';
    urlRow.appendChild(urlLabel);
    urlRow.appendChild(urlInput);
    dropdown.appendChild(urlRow);

    var acContainer = document.createElement('div');
    acContainer.className = 'md-image-autocomplete';
    acContainer.style.display = 'none';
    dropdown.appendChild(acContainer);

    var imageList = (typeof liveWysiwygImageList !== 'undefined') ? liveWysiwygImageList : [];
    var pageSrcPath = _getCurrentSrcPath();
    var acSelectedIdx = -1;

    function acFileName(p) {
      var i = p.lastIndexOf('/');
      return i >= 0 ? p.substring(i + 1) : p;
    }

    function acAcceptSelected() {
      var items = acContainer.querySelectorAll('.md-image-ac-item');
      if (acSelectedIdx < 0 || acSelectedIdx >= items.length) return false;
      var chosen = items[acSelectedIdx].getAttribute('data-src-path');
      if (!chosen) return false;
      urlInput.value = computeRelativeImagePath(pageSrcPath, chosen);
      if (!altInput.value.trim()) {
        var fn = acFileName(chosen);
        var dot = fn.lastIndexOf('.');
        altInput.value = dot > 0 ? fn.substring(0, dot) : fn;
      }
      acContainer.style.display = 'none';
      acSelectedIdx = -1;
      return true;
    }

    function acRender(filterText) {
      acContainer.innerHTML = '';
      acSelectedIdx = -1;
      var ft = (filterText || '').toLowerCase();
      if (/^(?:https?:\/\/|data:)/.test(ft)) { acContainer.style.display = 'none'; return; }
      var matches = [];
      for (var mi = 0; mi < imageList.length && matches.length < 50; mi++) {
        var p = imageList[mi];
        var pLow = p.toLowerCase();
        var fn = acFileName(p).toLowerCase();
        if (!ft || pLow.indexOf(ft) !== -1 || fn.indexOf(ft) !== -1) matches.push(p);
      }
      if (ft && matches.length > 1) {
        matches.sort(function (a, b) {
          var aFn = acFileName(a).toLowerCase();
          var bFn = acFileName(b).toLowerCase();
          var aPrefix = aFn.indexOf(ft) === 0 ? 0 : 1;
          var bPrefix = bFn.indexOf(ft) === 0 ? 0 : 1;
          return aPrefix - bPrefix;
        });
      }
      if (matches.length === 0) { acContainer.style.display = 'none'; return; }
      for (var ri = 0; ri < matches.length; ri++) {
        var item = document.createElement('div');
        item.className = 'md-image-ac-item';
        item.setAttribute('data-src-path', matches[ri]);
        var nameSpan = document.createElement('span');
        nameSpan.className = 'md-image-ac-item-name';
        nameSpan.textContent = acFileName(matches[ri]);
        var pathSpan = document.createElement('span');
        pathSpan.className = 'md-image-ac-item-path';
        pathSpan.textContent = matches[ri];
        item.appendChild(nameSpan);
        item.appendChild(pathSpan);
        (function (idx) {
          item.addEventListener('mouseenter', function () { acHighlight(idx); });
          item.addEventListener('mousedown', function (ev) {
            ev.preventDefault();
            ev.stopPropagation();
            acSelectedIdx = idx;
            acAcceptSelected();
            urlInput.focus();
          });
        })(ri);
        acContainer.appendChild(item);
      }
      acContainer.style.display = '';
      if (matches.length > 0) acHighlight(0);
    }

    function acHighlight(idx) {
      var items = acContainer.querySelectorAll('.md-image-ac-item');
      for (var hi = 0; hi < items.length; hi++) {
        items[hi].classList.toggle('md-image-ac-item-selected', hi === idx);
      }
      acSelectedIdx = idx;
      if (idx >= 0 && idx < items.length) {
        items[idx].scrollIntoView({ block: 'nearest' });
      }
    }

    function acIsVisible() {
      return acContainer.style.display !== 'none' && acContainer.childNodes.length > 0;
    }

    var altRow = document.createElement('div');
    altRow.className = 'md-image-insert-row';
    var altLabel = document.createElement('span');
    altLabel.className = 'md-image-insert-label';
    altLabel.textContent = 'Alt';
    var altInput = document.createElement('input');
    altInput.className = 'md-image-insert-input';
    altInput.type = 'text';
    altInput.placeholder = 'alt text';
    altRow.appendChild(altLabel);
    altRow.appendChild(altInput);
    dropdown.appendChild(altRow);

    var sizeRow = document.createElement('div');
    sizeRow.className = 'md-image-insert-row';
    var sizeLabel = document.createElement('span');
    sizeLabel.className = 'md-image-insert-label';
    sizeLabel.textContent = 'Size';
    var sizeSlider = document.createElement('input');
    sizeSlider.className = 'md-image-insert-slider';
    sizeSlider.type = 'range';
    sizeSlider.min = '10';
    sizeSlider.max = '100';
    sizeSlider.value = '100';
    var sizePct = document.createElement('span');
    sizePct.className = 'md-image-insert-pct';
    sizePct.textContent = '100%';
    sizeSlider.addEventListener('input', function () {
      sizePct.textContent = sizeSlider.value + '%';
    });
    sizeRow.appendChild(sizeLabel);
    sizeRow.appendChild(sizeSlider);
    sizeRow.appendChild(sizePct);
    dropdown.appendChild(sizeRow);

    var applyRow = document.createElement('div');
    applyRow.className = 'md-image-insert-row md-image-insert-apply-row';
    var applyBtn = document.createElement('button');
    applyBtn.type = 'button';
    applyBtn.className = 'md-image-insert-apply';
    applyBtn.textContent = 'Insert';
    applyRow.appendChild(applyBtn);
    dropdown.appendChild(applyRow);

    urlInput.addEventListener('input', function () {
      var val = urlInput.value.trim();
      var rel = _tryConvertToRelativeImageUrl(val);
      if (rel !== null && rel !== val) {
        urlInput.value = rel;
      }
      acRender(urlInput.value.trim());
    });

    urlInput.addEventListener('focus', function () {
      acRender(urlInput.value.trim());
    });

    function positionDropdown() {
      var rect = anchorBtn.getBoundingClientRect();
      var left = rect.right - 260;
      if (left < 0) left = rect.left;
      dropdown.style.top = (rect.bottom + 2) + 'px';
      dropdown.style.left = left + 'px';
    }

    function doInsert() {
      var rawUrl = (urlInput.value || '').trim();
      if (!rawUrl) return;
      var alt = (altInput.value || '').trim();
      var scale = parseInt(sizeSlider.value, 10) || 100;

      var resolved = resolveImageSrc(rawUrl);
      var origSrc = (resolved !== rawUrl) ? rawUrl : null;

      if (isWysiwyg) {
        ea.focus();
        var sel = window.getSelection();
        var range;
        if (savedRange instanceof Range && ea.contains(savedRange.commonAncestorContainer)) {
          sel.removeAllRanges();
          sel.addRange(savedRange);
          range = savedRange;
        } else if (sel && sel.rangeCount > 0 && ea.contains(sel.getRangeAt(0).commonAncestorContainer)) {
          range = sel.getRangeAt(0);
        } else {
          range = document.createRange();
          range.selectNodeContents(ea);
          range.collapse(false);
          sel.removeAllRanges();
          sel.addRange(range);
        }

        var img = document.createElement('img');
        img.src = resolved;
        img.alt = alt;
        if (origSrc) img.setAttribute('data-orig-src', origSrc);

        img.setAttribute('data-size-syntax', _getSetting('live_wysiwyg_image_attr_syntax') === '0' ? 'html' : 'attr');

        if (scale < 100) {
          var probe = new Image();
          probe.onload = function () {
            var w = Math.round(probe.naturalWidth * scale / 100);
            var h = Math.round(probe.naturalHeight * scale / 100);
            img.setAttribute('width', String(w));
            img.setAttribute('height', String(h));
            if (editor._finalizeUpdate) editor._finalizeUpdate(ea.innerHTML);
          };
          probe.src = resolved;
        }

        range.deleteContents();

        var anchorNode = range.startContainer;
        if (anchorNode.nodeType === Node.TEXT_NODE) anchorNode = anchorNode.parentNode;

        var blockParent = anchorNode;
        var blockTags = { P: 1, DIV: 1, LI: 1, H1: 1, H2: 1, H3: 1, H4: 1, H5: 1, H6: 1, TD: 1, TH: 1 };
        while (blockParent && blockParent !== ea && !blockTags[blockParent.nodeName]) {
          blockParent = blockParent.parentNode;
        }
        if (!blockParent || blockParent === ea) {
          blockParent = null;
        }

        var imgP = document.createElement('p');
        imgP.appendChild(img);
        var pAfter = document.createElement('p');
        pAfter.innerHTML = '\u200B';

        if (blockParent) {
          var blockText = (blockParent.textContent || '').replace(/[\u200B\u00A0\s]/g, '');
          if (blockText.length === 0) {
            blockParent.parentNode.replaceChild(imgP, blockParent);
            imgP.parentNode.insertBefore(pAfter, imgP.nextSibling);
          } else {
            blockParent.parentNode.insertBefore(imgP, blockParent.nextSibling);
            imgP.parentNode.insertBefore(pAfter, imgP.nextSibling);
          }
        } else {
          ea.appendChild(imgP);
          ea.appendChild(pAfter);
        }

        range.setStart(pAfter, pAfter.childNodes.length > 0 ? 1 : 0);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        if (editor._finalizeUpdate) editor._finalizeUpdate(ea.innerHTML);
        if (typeof enhanceImages === 'function') enhanceImages(ea);
      } else {
        ma.focus();
        var start = savedRange && typeof savedRange.start === 'number' ? savedRange.start : ma.selectionStart;
        var end = savedRange && typeof savedRange.end === 'number' ? savedRange.end : ma.selectionEnd;
        var mdImg = '![' + alt + '](' + rawUrl + ')';
        var tv = ma.value;
        var prefix = '';
        var suffix = '\n';
        if (start > 0 && tv[start - 1] !== '\n') {
          prefix = (start > 1 && tv[start - 2] !== '\n') ? '\n\n' : '\n';
        } else if (start > 0 && tv[start - 1] === '\n' && start > 1 && tv[start - 2] !== '\n') {
          prefix = '\n';
        }
        if (end < tv.length && tv[end] !== '\n') {
          suffix = (end + 1 < tv.length && tv[end + 1] !== '\n') ? '\n\n' : '\n';
        }
        var replacement = prefix + mdImg + suffix;
        ma.value = tv.substring(0, start) + replacement + tv.substring(end);
        var cursorPos = start + replacement.length;
        ma.setSelectionRange(cursorPos, cursorPos);
        if (editor._finalizeUpdate) editor._finalizeUpdate(ma.value);
        if (editor._updateMarkdownLineNumbers) editor._updateMarkdownLineNumbers();
      }
      dismissImageInsertDropdown();
    }

    urlInput.tabIndex = 1;
    altInput.tabIndex = 2;
    sizeSlider.tabIndex = 3;
    applyBtn.tabIndex = 4;

    var dirty = false;
    function markDirty() { dirty = true; }
    urlInput.addEventListener('input', markDirty);
    altInput.addEventListener('input', markDirty);
    sizeSlider.addEventListener('input', markDirty);

    function _deriveAltFromUrl() {
      if (altInput.value.trim()) return;
      var url = (urlInput.value || '').trim();
      if (!url) return;
      var fn = url.split('/').pop().split('?')[0];
      var dot = fn.lastIndexOf('.');
      if (dot > 0) fn = fn.substring(0, dot);
      var derived = fn.replace(/[-_]/g, ' ').trim();
      if (derived) altInput.value = derived;
    }

    applyBtn.addEventListener('mousedown', function (ev) {
      ev.preventDefault();
      ev.stopPropagation();
      _deriveAltFromUrl();
      doInsert();
    });
    urlInput.addEventListener('keydown', function (ev) {
      if (acIsVisible()) {
        var items = acContainer.querySelectorAll('.md-image-ac-item');
        if (ev.key === 'ArrowDown') {
          ev.preventDefault();
          acHighlight(acSelectedIdx < items.length - 1 ? acSelectedIdx + 1 : 0);
          return;
        }
        if (ev.key === 'ArrowUp') {
          ev.preventDefault();
          acHighlight(acSelectedIdx > 0 ? acSelectedIdx - 1 : items.length - 1);
          return;
        }
        if (ev.key === 'Enter') {
          ev.preventDefault();
          acAcceptSelected();
          return;
        }
        if (ev.key === 'Tab') {
          ev.preventDefault();
          acAcceptSelected();
          return;
        }
        if (ev.key === 'Escape') {
          ev.preventDefault();
          acContainer.style.display = 'none';
          acSelectedIdx = -1;
          return;
        }
      }
    });

    _attachDialogKeyboard(dropdown, {
      category: 'form',
      isDirty: function () { return dirty; },
      enterGuard: function () { return !acIsVisible(); },
      onConfirm: function () { _deriveAltFromUrl(); doInsert(); },
      onDismiss: function () { dismissImageInsertDropdown(); }
    });

    document.body.appendChild(dropdown);
    positionDropdown();
    _attachContainerExpandBehavior(dropdown, {
      selector: '.md-image-insert-input',
      onResize: positionDropdown
    });
    requestAnimationFrame(function () {
      urlInput.focus();
      try {
        navigator.clipboard.readText().then(function (text) {
          text = (text || '').trim();
          if (!text) return;
          if (/^https?:\/\/.+/.test(text) || /\.(?:png|jpe?g|gif|svg|webp|bmp|ico|tiff?)$/i.test(text)) {
            var rel = _tryConvertToRelativeImageUrl(text);
            urlInput.value = (rel !== null) ? rel : text;
            urlInput.select();
            dirty = true;
            acRender(urlInput.value.trim());
          }
        }).catch(function () {});
      } catch (e) {}
    });

    var closeHandler = function (ev) {
      if (dropdown.contains(ev.target) || ev.target === anchorBtn) return;
      dismissImageInsertDropdown();
    };
    var scrollHandler = function () { positionDropdown(); };
    document.addEventListener('mousedown', closeHandler, true);
    window.addEventListener('scroll', scrollHandler, true);
    _activeImageInsertDropdown = { el: dropdown, closeHandler: closeHandler, scrollHandler: scrollHandler };
  }

  (function patchInsertImageAction() {
    var proto = MarkdownWYSIWYG.prototype;
    proto._insertImageAction = function (buttonElement) {
      if (!buttonElement) buttonElement = this.toolbar && this.toolbar.querySelector('.md-toolbar-button-image');
      if (this.currentMode === 'wysiwyg') {
        this.editableArea.focus();
        var sel = window.getSelection();
        if (sel && sel.rangeCount > 0) {
          this.savedRangeInfo = sel.getRangeAt(0).cloneRange();
        } else {
          var range = document.createRange();
          range.selectNodeContents(this.editableArea);
          range.collapse(false);
          this.savedRangeInfo = range;
        }
      } else {
        this.markdownArea.focus();
        this.savedRangeInfo = { start: this.markdownArea.selectionStart, end: this.markdownArea.selectionEnd };
      }
      createImageInsertDropdown(buttonElement || document.body, this);
    };
  })();

  // ---- Image resize & selection ----

  function _createResizeOverlay(wrapper, img) {
    dismissImageSelection();
    img.classList.add('md-image-selected');

    var rc = document.createElement('div');
    rc.className = 'md-image-resize-container';
    rc.setAttribute('contenteditable', 'false');

    var dimLabel = document.createElement('div');
    dimLabel.className = 'md-image-dimension-label';
    dimLabel.textContent = (img.width || img.naturalWidth) + ' x ' + (img.height || img.naturalHeight);
    rc.appendChild(dimLabel);

    var corners = ['nw', 'ne', 'sw', 'se'];
    corners.forEach(function (pos) {
      var h = document.createElement('div');
      h.className = 'md-image-resize-handle md-image-resize-handle-' + pos;
      h.setAttribute('contenteditable', 'false');
      h.addEventListener('mousedown', function (e) {
        e.preventDefault();
        e.stopPropagation();
        _startResize(img, pos, dimLabel, e);
      });
      rc.appendChild(h);
    });

    wrapper.appendChild(rc);

    var clickHandler = function (ev) {
      if (wrapper.contains(ev.target)) return;
      if (_activeImageGearDropdown && _activeImageGearDropdown.el && _activeImageGearDropdown.el.contains(ev.target)) return;
      dismissImageSelection();
    };
    document.addEventListener('mousedown', clickHandler, true);
    _activeImageSelection = { img: img, resizeContainer: rc, clickHandler: clickHandler };
  }

  function _startResize(img, corner, dimLabel, startEvt) {
    var startX = startEvt.clientX;
    var startY = startEvt.clientY;
    var startW = img.width || img.naturalWidth;
    var startH = img.height || img.naturalHeight;
    var aspect = img.naturalWidth / img.naturalHeight;
    var isLeft = corner === 'nw' || corner === 'sw';

    function onMove(e) {
      var dx = e.clientX - startX;
      if (isLeft) dx = -dx;
      var newW = Math.max(20, Math.round(startW + dx));
      var newH = Math.round(newW / aspect);
      img.setAttribute('width', String(newW));
      img.setAttribute('height', String(newH));
      img.style.width = newW + 'px';
      img.style.height = newH + 'px';
      dimLabel.textContent = newW + ' x ' + newH;
    }

    function onUp() {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup', onUp);
      if (wysiwygEditor && wysiwygEditor._finalizeUpdate && wysiwygEditor.editableArea) {
        wysiwygEditor._finalizeUpdate(wysiwygEditor.editableArea.innerHTML);
      }
    }

    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup', onUp);
  }

  // ---- Image gear settings ----

  function _showImageGearDropdown(gearBtn, img, wrapper) {
    dismissImageGearDropdown();

    var dropdown = document.createElement('div');
    dropdown.className = 'md-image-gear-dropdown';
    dropdown.setAttribute('contenteditable', 'false');

    var altRow = document.createElement('div');
    altRow.className = 'md-image-gear-row';
    var altLabel = document.createElement('span');
    altLabel.className = 'md-image-gear-label';
    altLabel.textContent = 'Alt';
    var altInput = document.createElement('input');
    altInput.className = 'md-image-gear-input';
    altInput.type = 'text';
    altInput.placeholder = 'alt text';
    altInput.value = img.getAttribute('alt') || '';
    altInput.addEventListener('input', function () {
      img.setAttribute('alt', altInput.value);
    });
    altRow.appendChild(altLabel);
    altRow.appendChild(altInput);
    dropdown.appendChild(altRow);

    var curW = img.getAttribute('width') ? parseInt(img.getAttribute('width'), 10) : img.naturalWidth;
    var curH = img.getAttribute('height') ? parseInt(img.getAttribute('height'), 10) : img.naturalHeight;
    var dimsRow = document.createElement('div');
    dimsRow.className = 'md-image-gear-row';
    var dimsLabel = document.createElement('span');
    dimsLabel.className = 'md-image-gear-label';
    dimsLabel.textContent = 'Size';
    var dimsValue = document.createElement('span');
    dimsValue.className = 'md-image-gear-dims';
    dimsValue.textContent = curW + ' x ' + curH;
    dimsRow.appendChild(dimsLabel);
    dimsRow.appendChild(dimsValue);
    dropdown.appendChild(dimsRow);

    var cbRow = document.createElement('div');
    cbRow.className = 'md-image-gear-row';
    var cbLabel = document.createElement('label');
    cbLabel.className = 'md-image-gear-cb-label';
    var cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.className = 'md-image-gear-cb';
    var attrSyntaxSetting = _getSetting('live_wysiwyg_image_attr_syntax');
    var imgSyntax = img.getAttribute('data-size-syntax');
    cb.checked = imgSyntax ? imgSyntax === 'attr' : attrSyntaxSetting !== '0';
    if (!imgSyntax) {
      img.setAttribute('data-size-syntax', cb.checked ? 'attr' : 'html');
    }
    cb.addEventListener('change', function () {
      img.setAttribute('data-size-syntax', cb.checked ? 'attr' : 'html');
      _setSetting('live_wysiwyg_image_attr_syntax', cb.checked ? '1' : '0');
    });
    cbLabel.appendChild(cb);
    cbLabel.appendChild(document.createTextNode('Markdown attr syntax'));
    cbRow.appendChild(cbLabel);
    dropdown.appendChild(cbRow);

    var inlineCbRow = document.createElement('div');
    inlineCbRow.className = 'md-image-gear-row';
    var inlineCbLabel = document.createElement('label');
    inlineCbLabel.className = 'md-image-gear-cb-label';
    var inlineCb = document.createElement('input');
    inlineCb.type = 'checkbox';
    inlineCb.className = 'md-image-gear-cb';
    inlineCb.checked = img.getAttribute('data-inline') === '1';
    inlineCb.addEventListener('change', function () {
      if (inlineCb.checked) {
        img.setAttribute('data-inline', '1');
        img.style.verticalAlign = 'middle';
        img.style.display = 'inline';
      } else {
        img.removeAttribute('data-inline');
        img.style.verticalAlign = '';
        img.style.display = '';
      }
    });
    inlineCbLabel.appendChild(inlineCb);
    inlineCbLabel.appendChild(document.createTextNode('Display inline'));
    inlineCbRow.appendChild(inlineCbLabel);
    dropdown.appendChild(inlineCbRow);

    var btnRow = document.createElement('div');
    btnRow.className = 'md-image-gear-btn-row';

    var restoreOrigBtn = document.createElement('button');
    restoreOrigBtn.type = 'button';
    restoreOrigBtn.className = 'md-image-gear-btn';
    restoreOrigBtn.textContent = 'Original size';
    restoreOrigBtn.addEventListener('mousedown', function (ev) {
      ev.preventDefault();
      img.removeAttribute('width');
      img.removeAttribute('height');
      img.style.width = '';
      img.style.height = '';
      if (wysiwygEditor && wysiwygEditor._finalizeUpdate && wysiwygEditor.editableArea) {
        wysiwygEditor._finalizeUpdate(wysiwygEditor.editableArea.innerHTML);
      }
      dismissImageGearDropdown();
    });
    btnRow.appendChild(restoreOrigBtn);

    var docSizeKey = _imageDocSizeKey(img);
    var docSize = docSizeKey ? _imageDocumentSizes[docSizeKey] : null;
    var initW = docSize ? docSize.w : img.getAttribute('data-initial-width');
    var initH = docSize ? docSize.h : img.getAttribute('data-initial-height');
    if (initW && initH) {
      var restoreDocBtn = document.createElement('button');
      restoreDocBtn.type = 'button';
      restoreDocBtn.className = 'md-image-gear-btn';
      restoreDocBtn.textContent = 'Document size';
      restoreDocBtn.addEventListener('mousedown', function (ev) {
        ev.preventDefault();
        img.setAttribute('width', initW);
        img.setAttribute('height', initH);
        img.style.width = initW + 'px';
        img.style.height = initH + 'px';
        if (wysiwygEditor && wysiwygEditor._finalizeUpdate && wysiwygEditor.editableArea) {
          wysiwygEditor._finalizeUpdate(wysiwygEditor.editableArea.innerHTML);
        }
        dismissImageGearDropdown();
      });
      btnRow.appendChild(restoreDocBtn);
    }

    dropdown.appendChild(btnRow);

    function positionDropdown() {
      var rect = gearBtn.getBoundingClientRect();
      var left = rect.right - 240;
      if (left < 0) left = rect.left;
      dropdown.style.top = (rect.bottom + 2) + 'px';
      dropdown.style.left = left + 'px';
    }

    altInput.tabIndex = 1;
    cb.tabIndex = 2;
    inlineCb.tabIndex = 3;
    restoreOrigBtn.tabIndex = 4;

    if (!altInput.value.trim() && img.src) {
      var srcPath = img.getAttribute('data-orig-src') || img.src;
      var fn = srcPath.split('/').pop().split('?')[0];
      var dot = fn.lastIndexOf('.');
      if (dot > 0) fn = fn.substring(0, dot);
      var derived = fn.replace(/[-_]/g, ' ').trim();
      if (derived) {
        altInput.value = derived;
        img.setAttribute('alt', derived);
      }
    }

    _attachDialogKeyboard(dropdown, {
      category: 'settings',
      onDismiss: function () { dismissImageGearDropdown(); },
      autoFocus: function () { altInput.focus(); altInput.select(); }
    });

    document.body.appendChild(dropdown);
    positionDropdown();
    _attachContainerExpandBehavior(dropdown, {
      selector: '.md-image-gear-input',
      onResize: positionDropdown
    });

    var closeHandler = function (ev) {
      if (dropdown.contains(ev.target) || ev.target === gearBtn || gearBtn.contains(ev.target)) return;
      dismissImageGearDropdown();
    };
    var scrollHandler = function () { positionDropdown(); };
    document.addEventListener('mousedown', closeHandler, true);
    window.addEventListener('scroll', scrollHandler, true);
    _activeImageGearDropdown = { el: dropdown, closeHandler: closeHandler, scrollHandler: scrollHandler };
  }

  // ---- enhanceImages ----

  function enhanceImages(editableArea) {
    if (!editableArea) return;
    var imgs = editableArea.querySelectorAll('img');
    for (var i = 0; i < imgs.length; i++) {
      var img = imgs[i];
      if (img.getAttribute('data-emoji-shortcode')) continue;
      if (img.parentNode && img.parentNode.classList && img.parentNode.classList.contains('md-image-wrapper')) {
        continue;
      }
      if (img.closest && img.closest('[data-live-wysiwyg-raw-html-block]')) continue;

      if (!img.hasAttribute('data-size-syntax')) {
        img.setAttribute('data-size-syntax', _getSetting('live_wysiwyg_image_attr_syntax') === '0' ? 'html' : 'attr');
      }

      if (!img.hasAttribute('data-inline') && img.style && /vertical-align\s*:\s*middle/i.test(img.style.cssText || '')) {
        img.setAttribute('data-inline', '1');
      }
      if (img.getAttribute('data-inline') === '1') {
        img.style.verticalAlign = 'middle';
        img.style.display = 'inline';
      }

      var wrapper = document.createElement('span');
      wrapper.className = 'md-image-wrapper';
      wrapper.setAttribute('contenteditable', 'false');
      img.parentNode.insertBefore(wrapper, img);
      wrapper.appendChild(img);

      var existW = img.getAttribute('width');
      var existH = img.getAttribute('height');
      if (existW && existH && !img.style.width) {
        img.style.width = existW + 'px';
        img.style.height = existH + 'px';
      }

      var sizeKey = _imageDocSizeKey(img);
      var stored = sizeKey ? _imageDocumentSizes[sizeKey] : null;
      if (stored) {
        img.setAttribute('data-initial-width', stored.w);
        img.setAttribute('data-initial-height', stored.h);
      } else if (existW && existH) {
        if (sizeKey) _imageDocumentSizes[sizeKey] = { w: existW, h: existH };
        img.setAttribute('data-initial-width', existW);
        img.setAttribute('data-initial-height', existH);
      } else if (existW && !existH) {
        (function (theImg, wVal, key) {
          var setH = function () {
            if (theImg.naturalWidth > 0) {
              var computed = Math.round(parseInt(wVal, 10) * theImg.naturalHeight / theImg.naturalWidth);
              theImg.setAttribute('height', String(computed));
              theImg.style.width = wVal + 'px';
              theImg.style.height = computed + 'px';
              theImg.setAttribute('data-initial-width', wVal);
              theImg.setAttribute('data-initial-height', String(computed));
              if (key && !_imageDocumentSizes[key]) {
                _imageDocumentSizes[key] = { w: wVal, h: String(computed) };
              }
            }
          };
          if (theImg.complete && theImg.naturalWidth > 0) { setH(); }
          else { theImg.addEventListener('load', setH, { once: true }); }
        })(img, existW, sizeKey);
      }

      (function (w, im) {
        var gearBtn = document.createElement('button');
        gearBtn.type = 'button';
        gearBtn.className = 'md-image-settings-btn';
        gearBtn.setAttribute('contenteditable', 'false');
        gearBtn.innerHTML = GEAR_SVG;
        gearBtn.addEventListener('mousedown', function (ev) {
          ev.preventDefault();
          ev.stopPropagation();
          _showImageGearDropdown(gearBtn, im, w);
        });
        w.appendChild(gearBtn);

        w.addEventListener('click', function (ev) {
          if (ev.target === gearBtn || gearBtn.contains(ev.target)) return;
          ev.preventDefault();
          _createResizeOverlay(w, im);
        });
      })(wrapper, img);
    }
  }

  (function patchAdmonitionHtmlToMarkdown() {
    var proto = MarkdownWYSIWYG.prototype;
    var orig = proto._nodeToMarkdownRecursive;
    if (!orig) return;
    proto._nodeToMarkdownRecursive = function (node, options) {
      // INPUT type=checkbox: checklist items from GFM task lists
      if (node.nodeName === 'INPUT' && node.type === 'checkbox') {
        return (node.checked ? '[x]' : '[ ]');
      }
      if (node.nodeType === 1 && node.hasAttribute && (node.hasAttribute('data-live-wysiwyg-cursor') || node.hasAttribute('data-live-wysiwyg-cursor-end'))) {
        return '';
      }
      if (node.nodeType === 8) {
        if (node._liveWysiwygConsumed) return '';
        var commentData = (node.data || '').trim();
        if (commentData.indexOf(RAW_HTML_CLOSE_PREFIX) === 0) {
          var prev = node.previousSibling;
          if (prev && prev.nodeType === 1 && prev.getAttribute) {
            var prevRaw = prev.getAttribute(RAW_HTML_ATTR);
            if (prevRaw) {
              var prevDecoded = _b64Decode(prevRaw);
              if (prevDecoded && prevDecoded.indexOf('data-live-wysiwyg-cursor') >= 0) return '';
            }
          }
          var closePayload = commentData.substring(RAW_HTML_CLOSE_PREFIX.length);
          var pipeIdx = closePayload.indexOf('|');
          var closeB64 = pipeIdx >= 0 ? closePayload.substring(0, pipeIdx) : closePayload;
          var closeNewlines = pipeIdx >= 0 ? parseInt(closePayload.substring(pipeIdx + 1), 10) : 1;
          if (isNaN(closeNewlines) || closeNewlines < 0) closeNewlines = 1;
          return _b64Decode(closeB64) + '\n'.repeat(closeNewlines);
        }
        return '';
      }
      if (node.nodeType === 1 && node.getAttribute) {
        var rawBlockB64 = node.getAttribute(RAW_HTML_BLOCK_ATTR);
        if (rawBlockB64) {
          var decoded = _b64Decode(rawBlockB64);
          var blockNewlinesAfter = parseInt(node.getAttribute(RAW_HTML_NEWLINES_AFTER_ATTR), 10);
          if (isNaN(blockNewlinesAfter) || blockNewlinesAfter < 0) blockNewlinesAfter = 1;
          if (!this._rawHtmlPlaceholders) this._rawHtmlPlaceholders = [];
          var idx = this._rawHtmlPlaceholders.length;
          this._rawHtmlPlaceholders.push({ content: decoded, newlinesAfter: blockNewlinesAfter });
          return '\u0000__RAWHTMLBLOCK_' + idx + '__\u0000\n';
        }
        var commentB64 = node.getAttribute(RAW_HTML_COMMENT_ATTR);
        if (commentB64) {
          var decoded = _b64Decode(commentB64);
          var newlinesAfter = parseInt(node.getAttribute(RAW_HTML_NEWLINES_AFTER_ATTR), 10);
          if (isNaN(newlinesAfter) || newlinesAfter < 1) newlinesAfter = 1;
          if (!this._rawHtmlPlaceholders) this._rawHtmlPlaceholders = [];
          var idx = this._rawHtmlPlaceholders.length;
          this._rawHtmlPlaceholders.push({ content: decoded, newlinesAfter: newlinesAfter });
          return '\u0000__RAWHTMLBLOCK_' + idx + '__\u0000\n';
        }
        var rawTagB64 = node.getAttribute(RAW_HTML_ATTR);
        if (rawTagB64) {
          var originalOpenTag = _b64Decode(rawTagB64);
          if (originalOpenTag && originalOpenTag.indexOf('data-live-wysiwyg-cursor') >= 0) return '';
          var childMd = '';
          for (var ri = 0; ri < node.childNodes.length; ri++) {
            var rChild = node.childNodes[ri];
            if (rChild.nodeType === 8) {
              var rData = (rChild.data || '').trim();
              if (rData.indexOf(RAW_HTML_CLOSE_PREFIX) === 0) continue;
            }
            if (rChild.nodeType === 1 && rChild.getAttribute) {
              if (rChild.getAttribute(RAW_HTML_COMMENT_ATTR) || rChild.getAttribute(RAW_HTML_ATTR)) {
                childMd += this._nodeToMarkdownRecursive(rChild, options || {});
              } else {
                childMd += _serializeElementAsHtml(rChild);
              }
            } else if (rChild.nodeType === 3) {
              childMd += rChild.textContent;
            } else {
              childMd += this._nodeToMarkdownRecursive(rChild, options || {});
            }
          }
          var closeTag = '';
          var nextSib = node.nextSibling;
          while (nextSib) {
            if (nextSib.nodeType === 8) {
              var nd = (nextSib.data || '').trim();
              if (nd.indexOf(RAW_HTML_CLOSE_PREFIX) === 0) {
                var closePayload = nd.substring(RAW_HTML_CLOSE_PREFIX.length);
                var pipeIdx = closePayload.indexOf('|');
                var closeB64 = pipeIdx >= 0 ? closePayload.substring(0, pipeIdx) : closePayload;
                closeTag = _b64Decode(closeB64);
                var closeNewlines = pipeIdx >= 0 ? parseInt(closePayload.substring(pipeIdx + 1), 10) : 1;
                if (isNaN(closeNewlines) || closeNewlines < 0) closeNewlines = 1;
                closeTag = closeTag + '\n'.repeat(closeNewlines);
                nextSib._liveWysiwygConsumed = true;
                break;
              }
            }
            if (nextSib.nodeType === 1 || (nextSib.nodeType === 3 && nextSib.textContent.trim())) break;
            nextSib = nextSib.nextSibling;
          }
          return originalOpenTag + '\n' + childMd + (closeTag || '');
        }
      }
      if (node.nodeType === 1 && node.classList) {
        if (node.classList.contains('md-image-settings-btn')) return '';
        if (node.classList.contains('md-image-resize-container')) return '';
        if (node.classList.contains('md-image-dimension-label')) return '';
        if (node.classList.contains('md-image-wrapper')) {
          var inner = '';
          for (var wi = 0; wi < node.childNodes.length; wi++) {
            inner += this._nodeToMarkdownRecursive(node.childNodes[wi], options || {});
          }
          return inner;
        }
      }
      if (node.nodeName === 'IMG') {
        var imgSrc = node.getAttribute('data-orig-src') || node.getAttribute('src') || '';
        var imgAlt = node.getAttribute('alt') || '';
        var imgW = node.getAttribute('width');
        var imgH = node.getAttribute('height');
        var sizeSyntax = node.getAttribute('data-size-syntax');
        if (node.getAttribute('data-emoji-shortcode')) {
          return orig.call(this, node, options);
        }
        var explicitH = node.getAttribute('data-attr-height') === '1';
        var isInline = node.getAttribute('data-inline') === '1';
        var imgSuffix = (this._findParentElement(node, 'A') || isInline) ? '' : '\n\n';
        if (imgW || (imgH && sizeSyntax === 'attr' && explicitH) || isInline) {
          if (sizeSyntax === 'attr') {
            var attrParts = [];
            if (imgW) attrParts.push('width=' + imgW);
            if (imgH && explicitH) attrParts.push('height=' + imgH);
            if (isInline) attrParts.push('align=middle');
            return '![' + imgAlt + '](' + imgSrc + '){ ' + attrParts.join(' ') + ' }' + imgSuffix;
          }
          var htmlW = imgW ? ' width="' + imgW + '"' : '';
          var htmlH = imgH ? ' height="' + imgH + '"' : '';
          var htmlStyle = isInline ? ' style="vertical-align: middle"' : '';
          return '<img src="' + imgSrc.replace(/"/g, '&quot;') + '" alt="' + imgAlt.replace(/"/g, '&quot;') + '"' + htmlW + htmlH + htmlStyle + '>' + imgSuffix;
        }
        return '![' + imgAlt + '](' + imgSrc + ')' + imgSuffix;
      }
      // #text: preserve multiple spaces (upstream collapses with /  +/g)
      if (node.nodeName === '#text') {
        var text = node.textContent.replace(/\u00a0/g, ' ');
        if (options && options.inTableCell) {
          text = text.replace(/\|/g, '\\|');
          if (!this._findParentElement(node, 'PRE') && !this._findParentElement(node, 'CODE')) {
            text = text.replace(/\n/g, '<br>');
          }
        }
        return text;
      }
      // PRE: robust handling when contenteditable splits code blocks (e.g. DIV children, multiple PRE)
      if (node.nodeName === 'PRE' && !(options && options.inTableCell)) {
        var effectiveChildren = 0;
        var codeChild = null;
        for (var ci = 0; ci < node.childNodes.length; ci++) {
          var cn = node.childNodes[ci];
          if (cn.nodeType === 1 && cn.classList && cn.classList.contains('md-code-line-numbers')) continue;
          if (cn.nodeType === 1 && cn.classList && (cn.classList.contains('md-code-lang-btn') || cn.classList.contains('md-code-lang-dropdown') || cn.classList.contains('md-code-settings-btn') || cn.classList.contains('md-code-settings-btn-advanced'))) continue;
          if (cn.nodeType === 1 && cn.nodeName === 'CODE') { codeChild = cn; effectiveChildren++; }
          else effectiveChildren++;
        }
        var dataLang = (node.getAttribute && node.getAttribute('data-lang')) || '';
        var dataTitle = (node.getAttribute && node.getAttribute('data-title')) || '';
        var dataLinenums = (node.getAttribute && node.getAttribute('data-linenums')) || '';
        var dataHlLines = (node.getAttribute && node.getAttribute('data-hl-lines')) || '';
        function buildFenceInfo(lang) {
          var info = lang;
          if (dataTitle) info += ' title="' + dataTitle + '"';
          if (dataLinenums) info += ' linenums="' + dataLinenums + '"';
          if (dataHlLines) info += ' hl_lines="' + dataHlLines + '"';
          return info;
        }
        if (effectiveChildren === 1 && codeChild) {
          var langMatch = codeChild.className && codeChild.className.match(/language-(\S+)/);
          var lang = dataLang || (langMatch ? langMatch[1] : '');
          var preContent = codeChild.textContent;
          if (preContent.length > 0 && !preContent.endsWith('\n')) preContent += '\n';
          return '```' + buildFenceInfo(lang) + '\n' + preContent + '```\n\n';
        }
        var parts = [];
        for (var k = 0; k < node.childNodes.length; k++) {
          var ch = node.childNodes[k];
          if (ch.nodeType === 1 && ch.classList && ch.classList.contains('md-code-line-numbers')) continue;
          if (ch.nodeType === 1 && ch.classList && (ch.classList.contains('md-code-lang-btn') || ch.classList.contains('md-code-lang-dropdown') || ch.classList.contains('md-code-settings-btn') || ch.classList.contains('md-code-settings-btn-advanced'))) continue;
          if (ch.nodeType === 3) parts.push(ch.textContent);
          else if (ch.nodeType === 1) parts.push(ch.textContent);
        }
        var preContent2 = parts.join('\n');
        if (preContent2.length > 0 && !preContent2.endsWith('\n')) preContent2 += '\n';
        var codeEl = node.querySelector && node.querySelector('code');
        var langMatch2 = codeEl && codeEl.className && codeEl.className.match(/language-(\S+)/);
        var lang2 = dataLang || (langMatch2 ? langMatch2[1] : '');
        return '```' + buildFenceInfo(lang2) + '\n' + preContent2 + '```\n\n';
      }
      if (node.nodeName === 'DIV' && node.classList && node.classList.contains('md-code-block')) {
        var preChild = node.querySelector('pre');
        if (preChild) {
          var titleDiv = node.querySelector('.md-code-title');
          if (titleDiv) {
            var editedTitle = titleDiv.textContent.trim();
            preChild.setAttribute('data-title', editedTitle);
          }
          return this._nodeToMarkdownRecursive(preChild, options);
        }
        return '';
      }
      if (node.nodeName === 'DIV' && node.classList &&
          (node.classList.contains('md-code-title') || node.classList.contains('md-code-lang') || node.classList.contains('md-code-line-numbers') || node.classList.contains('md-code-lang-dropdown') || node.classList.contains('md-code-btn-group-advanced'))) {
        return '';
      }
      if (node.nodeName === 'BUTTON' && node.classList &&
          (node.classList.contains('md-code-lang-btn') || node.classList.contains('md-code-lang-btn-advanced') || node.classList.contains('md-code-settings-btn') || node.classList.contains('md-code-settings-btn-advanced'))) {
        return '';
      }
      if (node.nodeName === 'BUTTON' && node.classList &&
          node.classList.contains('md-admonition-settings-btn')) {
        return '';
      }
      var _admonitionTypes = ['note', 'warning', 'danger', 'tip', 'hint', 'important', 'caution', 'error', 'attention', 'abstract', 'info', 'success', 'question', 'failure', 'bug', 'example', 'quote'];
      var _isAdmonitionDiv = node.nodeName === 'DIV' && node.classList && node.classList.contains('admonition');
      var _isDetailsAdmonition = node.nodeName === 'DETAILS' && node.classList;
      if (_isAdmonitionDiv || _isDetailsAdmonition) {
        var type = null;
        for (var i = 0; i < _admonitionTypes.length; i++) {
          if (node.classList.contains(_admonitionTypes[i])) {
            type = _admonitionTypes[i];
            break;
          }
        }
        if (type) {
          var isCollapsible = (node.nodeName === 'DETAILS');
          var isExpanded = isCollapsible && !node.hasAttribute('data-default-collapsed');
          var hasInline = node.classList.contains('inline');
          var hasEnd = node.classList.contains('end');
          var hideTitle = node.hasAttribute('data-hide-title');

          var titleEl = isCollapsible ? node.querySelector(':scope > summary') : node.querySelector(':scope > .admonition-title');
          var title = titleEl ? titleEl.textContent.replace(/\u00a0/g, ' ').trim() : '';

          if (isCollapsible && node.hasAttribute('data-details-tag')) {
            var detailsSummary = title || 'Details';
            var detailsBodyParts = [];
            for (var dj = 0; dj < node.childNodes.length; dj++) {
              var dc = node.childNodes[dj];
              if (dc === titleEl) continue;
              if (dc.nodeType === 1 && dc.classList && dc.classList.contains('md-admonition-settings-btn')) continue;
              if (dc.nodeType === 3) {
                var dtxt = dc.textContent;
                if (dtxt && !/^[\s\u200B\u200C\u200D\uFEFF]*$/.test(dtxt)) detailsBodyParts.push(dtxt);
                continue;
              }
              if (dc.nodeType !== 1) continue;
              detailsBodyParts.push(this._nodeToMarkdownRecursive(dc, options || {}));
            }
            var detailsBody = detailsBodyParts.join('\n').trim();
            return '<details>\n<summary>' + detailsSummary + '</summary>\n\n' + detailsBody + '\n\n</details>\n\n';
          }

          var contentParts = [];
          for (var j = 0; j < node.childNodes.length; j++) {
            var c = node.childNodes[j];
            if (c === titleEl) continue;
            if (c.nodeType === 1 && c.classList && c.classList.contains('md-admonition-settings-btn')) continue;
            if (c.nodeType === 3) {
              var txt = c.textContent;
              if (txt && !/^[\s\u200B\u200C\u200D\uFEFF]*$/.test(txt)) contentParts.push(txt);
              continue;
            }
            if (c.nodeType !== 1) continue;
            contentParts.push(this._nodeToMarkdownRecursive(c, options || {}));
          }
          var body = contentParts.join('\n').trim();
          if (body) {
            var listLineRe = /^(\s*)([-*+])(\s+\[[ xX]\]\s*|\s)|^(\s*)(\d+)(\.)\s/;
            var codeFenceRe = /^(`{3,}|~{3,})\s*$/;
            var codeBlockInListRe = /^[-*+]\s+(`{3,}|~{3,})/;
            var blockquoteLineRe = /^>\s*(.*)$/;
            var lines = body.split(/\r?\n/);
            var outLines = [];
            for (var li = 0; li < lines.length; li++) {
              var line = lines[li];
              var trimmed = line.trim();
              var isListLine = listLineRe.test(trimmed);
              var isCodeFence = codeFenceRe.test(trimmed);
              var isCodeBlockStartInList = codeBlockInListRe.test(trimmed);
              var isBlockquoteLine = blockquoteLineRe.test(line);
              if (isListLine && outLines.length > 0) {
                var prev = outLines[outLines.length - 1];
                if (prev && prev.trim() && !listLineRe.test(prev.trim())) {
                  outLines.push('');
                }
              }
              if ((isCodeFence || isCodeBlockStartInList) && outLines.length > 0) {
                var prev = outLines[outLines.length - 1];
                if (prev && listLineRe.test(prev.trim())) {
                  outLines.push('');
                }
              }
              if ((trimmed || line === '') && outLines.length > 0 && !isBlockquoteLine) {
                var prevNonBlank = null;
                for (var p = outLines.length - 1; p >= 0; p--) {
                  if (outLines[p].trim()) { prevNonBlank = outLines[p]; break; }
                }
                if (prevNonBlank && prevNonBlank.trim() !== '>' && blockquoteLineRe.test(prevNonBlank)) {
                  outLines.push('>');
                }
              }
              outLines.push(line);
              if (isCodeFence && li + 1 < lines.length) {
                var next = lines[li + 1];
                if (next && listLineRe.test(next.trim())) {
                  outLines.push('');
                }
              }
            }
            body = outLines.join('\n').replace(/\n\s*\n\s*\n+/g, '\n\n');
          }
          var bodyIndented = body ? body.split('\n').map(function (l) { return l ? '    ' + l : ''; }).join('\n') : '';

          var prefix = isCollapsible ? (isExpanded ? '???+' : '???') : '!!!';
          var out = prefix + ' ' + type;
          if (hasInline) out += ' inline';
          if (hasEnd) out += ' end';

          var defaultTitle = type.charAt(0).toUpperCase() + type.slice(1);
          if (hideTitle && !isCollapsible) {
            out += ' ""';
          } else if (title && title !== defaultTitle) {
            out += ' "' + title.replace(/"/g, '\\"') + '"';
          }
          out += '\n' + (bodyIndented ? bodyIndented + '\n' : '');
          return out + '\n';
        }
      }
      if (node.nodeName === 'A') {
        var href = node.getAttribute('href') || '';
        var linkText = this._processInlineContainerRecursive ? this._processInlineContainerRecursive(node, options || {}).trim() : node.textContent.trim();
        var linkData = this._liveWysiwygLinkData;
        if (linkData && linkData.linkOriginals) {
          var cleanUrl = normalizeUrl(href);
          var cleanText = (linkText || '').replace(CURSOR_UNICODE_RE, '').replace(/\s+/g, ' ').replace(/\u00a0/g, ' ').trim();
          for (var k = 0; k < linkData.linkOriginals.length; k++) {
            var o = linkData.linkOriginals[k];
            if (o.isImage) continue;
            var origUrl = normalizeUrl(o.url);
            var origText = (o.text || '').replace(CURSOR_UNICODE_RE, '').replace(/\s+/g, ' ').replace(/\u00a0/g, ' ').trim();
            if (origUrl === cleanUrl && origText === cleanText) {
              if (o.isAutolink) {
                return '<' + href + '>';
              }
              var shortMatch = (o.original || '').match(/^\[([^\]]+)\]$/);
              if (shortMatch) {
                return '[' + linkText + ']';
              }
              break;
            }
          }
        }
        var bareText = (linkText || '').replace(CURSOR_UNICODE_RE, '').trim();
        if (bareText && href && normalizeUrl(bareText) === normalizeUrl(href)) {
          return bareText;
        }
      }
      return orig.apply(this, arguments);
    };
  })();

  function removeZeroWidthFromNodes(node) {
    if (node.nodeType === 3) {
      if (node.textContent.indexOf('\u200B') !== -1) {
        node.textContent = node.textContent.replace(/\u200B/g, '');
      }
      return;
    }
    if (node.nodeType === 1) {
      if (node.hasAttribute && node.hasAttribute('href')) {
        var h = node.getAttribute('href');
        if (/[\u200C\u200D]/.test(h)) {
          node.setAttribute('href', h.replace(/[\u200C\u200D]/g, ''));
        }
      }
      if (node.childNodes) {
        for (var i = 0; i < node.childNodes.length; i++) {
          removeZeroWidthFromNodes(node.childNodes[i]);
        }
      }
    }
  }

  (function patchListToMarkdownRecursiveForMarkerPreservation() {
    var proto = MarkdownWYSIWYG.prototype;
    var origListToMarkdown = proto._listToMarkdownRecursive;
    if (!origListToMarkdown) return;
    proto._listToMarkdownRecursive = function (listNode, indent, listType, listCounter, options) {
      var result = origListToMarkdown.apply(this, arguments);
      var listData = this._liveWysiwygListMarkerData;
      if (!listData || !listData.listItems || !listData.listItems.length) return result;
      if (listType === 'OL') {
        var olOriginals = listData.listItems;
        var olUsed = listData._olUsed || 0;
        var olLines = result.split('\n');
        var olStyle = listData.olStyle;
        for (var oi = 0; oi < olLines.length; oi++) {
          var olm = olLines[oi].match(/^(\s*)(\d+)\.\s+(.*)$/);
          if (!olm) continue;
          var olIndent = olm[1];
          var olContent = olm[3];
          var olNorm = normalizeContentForListMatch(olContent);
          var matched = false;
          for (var oj = olUsed; oj < olOriginals.length; oj++) {
            var oo = olOriginals[oj];
            if (!oo.isOrdered) continue;
            if (oo.indent !== olIndent) continue;
            if (normalizeContentForListMatch(oo.content) === olNorm) {
              olUsed = oj + 1;
              olLines[oi] = olIndent + oo.number + '. ' + olContent;
              matched = true;
              break;
            }
          }
          if (!matched && olStyle === 'all-ones') {
            olLines[oi] = olIndent + '1. ' + olContent;
          }
        }
        listData._olUsed = olUsed;
        var olResult = olLines.join('\n');
        olResult = _compactOlBlankLines(olResult);
        return olResult;
      }
      var originals = listData.listItems;
      var used = 0;
      var lines = result.split('\n');
      for (var i = 0; i < lines.length; i++) {
        var line = lines[i];
        var m = line.match(/^(\s*)(-\s+)(.*)$/);
        if (!m) continue;
        var lineIndent = m[1];
        var content = m[3];
        var normContent = normalizeContentForListMatch(content);
        var checklistMatch = content.match(/^\[([ xX])\]\s+/);
        var isChecklist = !!checklistMatch;
        var contentOnly = isChecklist ? content.replace(/^\[[ xX]\]\s+/, '') : content;
        var normContentOnly = normalizeContentForListMatch(contentOnly);
        for (var j = used; j < originals.length; j++) {
          var o = originals[j];
          if (o.indent !== lineIndent) continue;
          if (o.isChecklist && isChecklist) {
            if (normalizeContentForListMatch(o.content) === normContentOnly) {
              used = j + 1;
              var currentCheck = checklistMatch[1];
              var check = /[xX]/.test(currentCheck) ? '[x]' : '[ ]';
              lines[i] = lineIndent + o.marker + check + ' ' + contentOnly;
              break;
            }
          } else if (!o.isChecklist && !isChecklist) {
            if (normalizeContentForListMatch(o.content) === normContent) {
              used = j + 1;
              lines[i] = lineIndent + o.marker + content;
              break;
            }
          }
        }
      }
      var ulResult = lines.join('\n');
      ulResult = _compactUlBlankLines(ulResult);
      return ulResult;
    };
  })();

  (function patchNodeToMarkdownForCheckbox() {
    var proto = MarkdownWYSIWYG.prototype;
    var origNodeToMarkdown = proto._nodeToMarkdownRecursive;
    if (!origNodeToMarkdown) return;
    proto._nodeToMarkdownRecursive = function (node, options) {
      if (node.nodeName === 'INPUT' && node.type === 'checkbox') {
        return (node.checked ? '[x]' : '[ ]');
      }
      return origNodeToMarkdown.apply(this, arguments);
    };
  })();

  function captureWysiwygCursor(editable) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return null;
    var range = sel.getRangeAt(0);
    if (!editable.contains(range.commonAncestorContainer)) return null;
    try {
      var preRange = document.createRange();
      preRange.selectNodeContents(editable);
      preRange.setEnd(range.startContainer, range.startOffset);
      var startOff = preRange.toString().length;
      var endOff = startOff;
      if (!range.collapsed) {
        var preEndRange = document.createRange();
        preEndRange.selectNodeContents(editable);
        preEndRange.setEnd(range.endContainer, range.endOffset);
        endOff = preEndRange.toString().length;
      }
      return { start: startOff, end: endOff };
    } catch (e) { return null; }
  }

  (function patchUndoRedoCursorPreservation() {
    var proto = MarkdownWYSIWYG.prototype;

    function getEntryContent(entry) {
      return (entry && typeof entry === 'object' && 'content' in entry) ? entry.content : entry;
    }
    function getEntryCursor(entry) {
      return (entry && typeof entry === 'object' && 'cursor' in entry) ? entry.cursor : null;
    }

    function restoreWysiwygCursor(editable, cursor) {
      if (!cursor || cursor.start == null) return false;
      editable.focus();
      var si = findTextNodeAtOffset(editable, cursor.start);
      if (!si) return false;
      var ei = (cursor.start === cursor.end) ? si : (findTextNodeAtOffset(editable, cursor.end) || si);
      try {
        var range = document.createRange();
        range.setStart(si.node, si.offset);
        range.setEnd(ei.node, ei.offset);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        return true;
      } catch (e) { return false; }
    }

    function captureCursor(editor) {
      if (editor.currentMode === 'wysiwyg' && editor.editableArea) {
        return captureWysiwygCursor(editor.editableArea);
      } else if (editor.currentMode === 'markdown' && editor.markdownArea) {
        return { start: editor.markdownArea.selectionStart, end: editor.markdownArea.selectionEnd, mode: 'markdown' };
      }
      return null;
    }

    var origPush = proto._pushToUndoStack;
    proto._pushToUndoStack = function (content) {
      if (this.editableArea && !this.editableArea.__undoCursorTracker) {
        this.editableArea.__undoCursorTracker = true;
        var self = this;
        this.editableArea.addEventListener('beforeinput', function () {
          self.__cursorBeforeInput = captureWysiwygCursor(self.editableArea);
        }, true);
      }

      var stack = this.undoStack;
      if (!stack) return;
      var lastContent = stack.length > 0 ? getEntryContent(stack[stack.length - 1]) : null;
      if (lastContent === content) return;

      if (stack.length > 0 && this.__cursorBeforeInput) {
        var topEntry = stack[stack.length - 1];
        if (topEntry && typeof topEntry === 'object') {
          topEntry.cursor = this.__cursorBeforeInput;
        } else if (typeof topEntry === 'string') {
          stack[stack.length - 1] = { content: topEntry, cursor: this.__cursorBeforeInput };
        }
      }
      this.__cursorBeforeInput = null;

      var cursor = captureCursor(this);
      stack.push({ content: content, cursor: cursor });
      this.redoStack = [];
      if (stack.length > 50) stack.shift();
    };

    proto._performUndoRedo = function (sourceStack, targetStack, isUndoOperation) {
      this.isUpdatingFromUndoRedo = true;
      var canProceed = isUndoOperation ? sourceStack.length > 1 : sourceStack.length > 0;

      if (canProceed) {
        var idx = sourceStack.length - 1;
        var topEntry = sourceStack[idx];
        if (typeof topEntry === 'string') {
          topEntry = { content: topEntry, cursor: captureCursor(this) };
          sourceStack[idx] = topEntry;
        } else if (topEntry && typeof topEntry === 'object') {
          topEntry.cursor = captureCursor(this);
        }

        var stateToMove = sourceStack.pop();
        targetStack.push(stateToMove);

        var restoreIdx = isUndoOperation ? sourceStack.length - 1 : -1;
        var entryToRestore = isUndoOperation ? sourceStack[restoreIdx] : stateToMove;
        if (isUndoOperation && typeof entryToRestore === 'string') {
          entryToRestore = { content: entryToRestore, cursor: null };
          sourceStack[restoreIdx] = entryToRestore;
        }
        var contentToRestore = getEntryContent(entryToRestore);
        var cursorToRestore = getEntryCursor(entryToRestore);

        if (this.currentMode === 'wysiwyg') {
          this.editableArea.innerHTML = contentToRestore;
          enhanceChecklists(this.editableArea);
          if (typeof enhanceCodeBlocks === 'function') enhanceCodeBlocks(this.editableArea);
          if (typeof enhanceAdmonitions === 'function') enhanceAdmonitions(this.editableArea);

          if (!cursorToRestore || !restoreWysiwygCursor(this.editableArea, cursorToRestore)) {
            this._moveCursorToEnd();
          }
        } else {
          this.markdownArea.value = contentToRestore;
          this._updateMarkdownLineNumbers();
          if (cursorToRestore && cursorToRestore.mode === 'markdown') {
            this.markdownArea.focus();
            this.markdownArea.setSelectionRange(cursorToRestore.start, cursorToRestore.end);
          } else {
            this._moveCursorToEnd();
          }
        }

        if (this.options.onUpdate) this.options.onUpdate(this.getValue());
        this._updateToolbarActiveStates();
      }
      this.isUpdatingFromUndoRedo = false;
    };
  })();

  (function patchHtmlToMarkdownPreserveCodeBlockNewlines() {
    var proto = MarkdownWYSIWYG.prototype;
    var origHtmlToMarkdown = proto._htmlToMarkdown;
    if (!origHtmlToMarkdown) return;
    proto._htmlToMarkdown = function (elementOrHtml) {
      var tempDiv;
      if (typeof elementOrHtml === 'string') {
        tempDiv = document.createElement('div');
        tempDiv.innerHTML = elementOrHtml;
      } else {
        tempDiv = elementOrHtml.cloneNode(true);
      }
      removeZeroWidthFromNodes(tempDiv);
      var markdown = '';
      this._normalizeNodes(tempDiv);
      for (var i = 0; i < tempDiv.childNodes.length; i++) {
        markdown += this._nodeToMarkdownRecursive(tempDiv.childNodes[i]);
      }
      var codeBlockRe = /(```[^\n]*\n[\s\S]*?```)/g;
      var codeBlocks = [];
      var placeholderPrefix = '\u0000__CODEBLOCK_';
      var placeholderSuffix = '__\u0000';
      var protected_ = markdown.replace(codeBlockRe, function (m) {
        var idx = codeBlocks.length;
        codeBlocks.push(m);
        return placeholderPrefix + idx + placeholderSuffix;
      });
      protected_ = protected_.replace(/\n\s*\n\s*\n+/g, '\n\n');
      protected_ = protected_.replace(/ +\n/g, '\n');
      var cleanBlockquoteTrailing = function (s) {
        var lines = s.split('\n');
        var result = [];
        var i = 0;
        var isEmptyQuoteLine = function (l) { return /^>/.test(l) && !l.replace(/^>/, '').replace(/[\s\u00a0]/g, ''); };
        while (i < lines.length) {
          if (/^>/.test(lines[i])) {
            var block = [];
            while (i < lines.length && /^>/.test(lines[i])) {
              block.push(lines[i]);
              i++;
            }
            while (block.length > 0 && isEmptyQuoteLine(block[block.length - 1])) block.pop();
            for (var bi = 0; bi < block.length; bi++) result.push(block[bi]);
          } else {
            result.push(lines[i]);
            i++;
          }
        }
        return result.join('\n');
      };
      protected_ = cleanBlockquoteTrailing(protected_);
      for (var j = 0; j < codeBlocks.length; j++) {
        codeBlocks[j] = codeBlocks[j].replace(/[ \t]+$/gm, '');
        protected_ = protected_.split(placeholderPrefix + j + placeholderSuffix).join(codeBlocks[j]);
      }
      var rawHtmlBlocks = this._rawHtmlPlaceholders || [];
      this._rawHtmlPlaceholders = null;
      var rawPrefix = '\u0000__RAWHTMLBLOCK_';
      var rawSuffix = '__\u0000';
      for (var ri = 0; ri < rawHtmlBlocks.length; ri++) {
        var rawPh = rawPrefix + ri + rawSuffix;
        var rawIdx = protected_.indexOf(rawPh);
        if (rawIdx === -1) continue;
        var lineStart = protected_.lastIndexOf('\n', rawIdx - 1);
        lineStart = lineStart === -1 ? 0 : lineStart + 1;
        var beforePh = protected_.substring(lineStart, rawIdx);
        var lineEnd = protected_.indexOf('\n', rawIdx + rawPh.length);
        if (lineEnd === -1) lineEnd = protected_.length;
        if (/^\s*$/.test(beforePh)) {
          var ph = rawHtmlBlocks[ri];
          var decoded = typeof ph === 'object' ? ph.content : ph;
          var newlinesAfter = typeof ph === 'object' ? ph.newlinesAfter : null;
          var after = protected_.substring(lineEnd);
          var afterStripped = after.replace(/^\n+/, '');
          var nextIsHtmlComment = /^\s*<span\s[^>]*data-live-wysiwyg-html-comment/.test(afterStripped) || /^\s*<!--/.test(afterStripped);
          if (nextIsHtmlComment && newlinesAfter != null && newlinesAfter > 1) {
            newlinesAfter = 1;
          }
          if (decoded && /^\s*<!--[\s\S]*?-->\s*$/.test(decoded.trim())) {
            if (newlinesAfter != null && newlinesAfter >= 1) {
              after = '\n'.repeat(newlinesAfter) + after.replace(/^\n+/, '');
            } else {
              after = after.replace(/^\n+/, '\n');
            }
            protected_ = protected_.substring(0, lineStart) + decoded + after;
          } else if (newlinesAfter != null) {
            after = newlinesAfter >= 1 ? '\n'.repeat(newlinesAfter) + after.replace(/^\n+/, '') : after.replace(/^\n+/, '');
            protected_ = protected_.substring(0, lineStart) + decoded + after;
          } else {
            protected_ = protected_.substring(0, lineStart) + decoded + after;
          }
        } else {
          var phInline = rawHtmlBlocks[ri];
          var decodedInline = typeof phInline === 'object' ? phInline.content : phInline;
          protected_ = protected_.substring(0, rawIdx) + decodedInline + protected_.substring(rawIdx + rawPh.length);
        }
      }
      return protected_.trim();
    };
  })();

  /**
   * Parse YAML frontmatter from document content.
   * Returns { frontmatter: string, body: string }.
   * Frontmatter must be at the very start: --- newline, YAML, newline ---
   */
  function parseFrontmatter(content) {
    if (!content || typeof content !== 'string') return { frontmatter: '', body: content || '' };
    var m = content.match(/^(---\s*[\r\n]+[\s\S]*?[\r\n]+---\s*[\r\n]*)([\s\S]*)$/);
    if (m) return { frontmatter: m[1].replace(/\s+$/, ''), body: m[2] };
    return { frontmatter: '', body: content };
  }

  function serializeWithFrontmatter(frontmatter, body) {
    if (!frontmatter) return body || '';
    return frontmatter + '\n' + (body || '');
  }

  /**
   * Preprocess unordered list markers (*, -, +) and checklist items from markdown.
   * Returns { listItems: [{ indent, marker, content, isChecklist?, checked? }] } for preservation.
   */
  function preprocessListMarkers(markdown) {
    if (!markdown || typeof markdown !== 'string') return { listItems: [], olStyle: null };
    var listItems = [];
    var lines = markdown.split('\n');
    var checklistRe = /^(\s*)([-*+])\s+\[([ xX])\]\s+(.*)$/;
    var regularRe = /^(\s*)([-*+])\s+(.*)$/;
    var orderedRe = /^(\s*)(\d+)(\.)\s+(.*)$/;
    var olNumbers = [];
    for (var i = 0; i < lines.length; i++) {
      var m = lines[i].match(checklistRe);
      if (m) {
        listItems.push({
          indent: m[1],
          marker: m[2] + ' ',
          content: m[4],
          isChecklist: true,
          checked: /[xX]/.test(m[3])
        });
        continue;
      }
      m = lines[i].match(orderedRe);
      if (m) {
        var num = m[2];
        olNumbers.push(parseInt(num, 10));
        listItems.push({ indent: m[1], marker: num + '. ', content: m[4], isOrdered: true, number: num });
        continue;
      }
      m = lines[i].match(regularRe);
      if (m) {
        listItems.push({ indent: m[1], marker: m[2] + ' ', content: m[3] });
      }
    }
    var olStyle = null;
    if (olNumbers.length > 1) {
      var allOnes = olNumbers.every(function(n) { return n === 1; });
      olStyle = allOnes ? 'all-ones' : 'incrementing';
    }
    return { listItems: listItems, olStyle: olStyle };
  }

  /**
   * Postprocess markdown to restore original list markers where content matches.
   * Handles both regular list items and checklist items (- [ ] / - [x]).
   * New or modified list items use '- '; new checklists use '- [ ] '.
   */
  function normalizeContentForListMatch(s) {
    if (typeof s !== 'string') return '';
    return s.replace(/\s+/g, ' ').replace(/\u00a0/g, ' ').trim();
  }

  function postprocessListMarkers(markdown, listData) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    if (!listData || !listData.listItems || !listData.listItems.length) return markdown;
    var originals = listData.listItems;
    var used = 0;
    var olUsed = 0;
    function restoreRegular(match, indent, marker, content) {
      var normContent = normalizeContentForListMatch(content);
      for (var i = used; i < originals.length; i++) {
        var o = originals[i];
        if (!o.isChecklist && !o.isOrdered && o.indent === indent && normalizeContentForListMatch(o.content) === normContent) {
          used = i + 1;
          return indent + o.marker + content;
        }
      }
      return match;
    }
    function restoreChecklist(match, indent, marker, checkChar, content) {
      var normContent = normalizeContentForListMatch(content);
      for (var i = used; i < originals.length; i++) {
        var o = originals[i];
        if (o.isChecklist && o.indent === indent && normalizeContentForListMatch(o.content) === normContent) {
          used = i + 1;
          var check = /[xX]/.test(checkChar) ? '[x]' : '[ ]';
          return indent + o.marker + check + ' ' + content;
        }
      }
      return match;
    }
    function restoreOrdered(match, indent, num, content) {
      var normContent = normalizeContentForListMatch(content);
      for (var i = olUsed; i < originals.length; i++) {
        var o = originals[i];
        if (o.isOrdered && o.indent === indent && normalizeContentForListMatch(o.content) === normContent) {
          olUsed = i + 1;
          return indent + o.number + '. ' + content;
        }
      }
      if (listData.olStyle === 'all-ones') {
        return indent + '1. ' + content;
      }
      return match;
    }
    var result = markdown
      .replace(/^(\s*)(-\s+)\[([ xX])\]\s+(.*)$/gm, restoreChecklist)
      .replace(/^(\s*)(-\s+)(.*)$/gm, restoreRegular)
      .replace(/^(\s*)(\d+)\.\s+(.*)$/gm, restoreOrdered);
    result = _compactOlBlankLines(result);
    result = _compactUlBlankLines(result);
    return result;
  }

  function preprocessCodeBlocks(markdown) {
    if (!markdown || typeof markdown !== 'string') return { blocks: [] };
    var blocks = [];
    var lines = markdown.split('\n');
    var i = 0;
    while (i < lines.length) {
      var fenceMatch = lines[i].match(/^(`{3,}|~{3,})(.*)/);
      if (fenceMatch) {
        var openFence = lines[i];
        var fence = fenceMatch[1];
        var contentLines = [];
        i++;
        while (i < lines.length && !lines[i].match(new RegExp('^' + fence.charAt(0) + '{' + fence.length + ',}\\s*$'))) {
          contentLines.push(lines[i]);
          i++;
        }
        var closeFence = i < lines.length ? lines[i] : fence;
        blocks.push({ type: 'fenced', openFence: openFence, closeFence: closeFence, content: contentLines.join('\n') });
        i++;
        continue;
      }
      if (/^(    |\t)/.test(lines[i]) && (i === 0 || /^\s*$/.test(lines[i - 1]))) {
        var indentLines = [];
        while (i < lines.length && (/^(    |\t)/.test(lines[i]) || /^\s*$/.test(lines[i]))) {
          if (/^\s*$/.test(lines[i]) && (i + 1 >= lines.length || !/^(    |\t)/.test(lines[i + 1]))) break;
          indentLines.push(lines[i]);
          i++;
        }
        var content = indentLines.map(function (l) { return l.replace(/^    |\t/, ''); }).join('\n');
        blocks.push({ type: 'indented', content: content });
        continue;
      }
      i++;
    }
    return { blocks: blocks };
  }

  function postprocessCodeBlocks(markdown, codeData) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    if (!codeData || !codeData.blocks || !codeData.blocks.length) return markdown;
    var originals = codeData.blocks;
    var used = 0;
    var lines = markdown.split('\n');
    var result = [];
    var i = 0;
    while (i < lines.length) {
      var fenceMatch = lines[i].match(/^(`{3,}|~{3,})(.*)/);
      if (fenceMatch) {
        var fence = fenceMatch[1];
        var contentLines = [];
        var openIdx = i;
        i++;
        while (i < lines.length && !lines[i].match(new RegExp('^' + fence.charAt(0) + '{' + fence.length + ',}\\s*$'))) {
          contentLines.push(lines[i]);
          i++;
        }
        var closeIdx = i;
        var currentContent = contentLines.join('\n');
        var matched = false;
        for (var j = used; j < originals.length; j++) {
          if (originals[j].content.replace(/\s+$/g, '') === currentContent.replace(/\s+$/g, '')) {
            used = j + 1;
            matched = true;
            if (originals[j].type === 'indented') {
              var indentedLines = originals[j].content.split('\n');
              for (var k = 0; k < indentedLines.length; k++) {
                result.push('    ' + indentedLines[k]);
              }
            } else {
              var restoredFence = originals[j].openFence;
              var currentFenceLine = lines[openIdx];
              var currentLangMatch = currentFenceLine.match(/^(?:`{3,}|~{3,})(\S*)/);
              var origLangMatch = restoredFence.match(/^(?:`{3,}|~{3,})(\S*)/);
              var currentLang = (currentLangMatch && currentLangMatch[1]) || '';
              var origLang = (origLangMatch && origLangMatch[1]) || '';
              if (currentLang !== origLang) {
                if (origLang) {
                  restoredFence = restoredFence.replace(/^(`{3,}|~{3,})\S+/, '$1' + currentLang);
                } else {
                  restoredFence = restoredFence.replace(/^(`{3,}|~{3,})/, '$1' + currentLang);
                }
              }
              var currentTitleMatch = currentFenceLine.match(/title="([^"]*)"/);
              var origTitleMatch = restoredFence.match(/title="([^"]*)"/);
              if (currentTitleMatch && origTitleMatch && currentTitleMatch[1] !== origTitleMatch[1]) {
                restoredFence = restoredFence.replace(/title="[^"]*"/, 'title="' + currentTitleMatch[1] + '"');
              } else if (currentTitleMatch && !origTitleMatch) {
                restoredFence = restoredFence.replace(/(\S)(\s*)$/, '$1 title="' + currentTitleMatch[1] + '"$2');
              } else if (!currentTitleMatch && origTitleMatch) {
                restoredFence = restoredFence.replace(/\s*title="[^"]*"/, '');
              }
              result.push(restoredFence);
              for (var k = 0; k < contentLines.length; k++) result.push(contentLines[k]);
              result.push(originals[j].closeFence);
            }
            break;
          }
        }
        if (!matched) {
          result.push(lines[openIdx]);
          for (var k = 0; k < contentLines.length; k++) result.push(contentLines[k]);
          if (closeIdx < lines.length) result.push(lines[closeIdx]);
        }
        i++;
        continue;
      }
      result.push(lines[i]);
      i++;
    }
    return result.join('\n');
  }

  function preprocessTableSeparators(markdown) {
    if (!markdown || typeof markdown !== 'string') return { separators: [] };
    var separators = [];
    var lines = markdown.split('\n');
    for (var i = 1; i < lines.length; i++) {
      if (/^\|[\s:=-]+(\|[\s:=-]+)+\|?\s*$/.test(lines[i]) && /\|/.test(lines[i - 1])) {
        separators.push({ header: lines[i - 1].replace(/\s+/g, ''), separator: lines[i] });
      }
    }
    return { separators: separators };
  }

  function postprocessTableSeparators(markdown, tableData) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    if (!tableData || !tableData.separators || !tableData.separators.length) return markdown;
    var originals = tableData.separators;
    var used = 0;
    var lines = markdown.split('\n');
    for (var i = 1; i < lines.length; i++) {
      if (/^\|(\s*---\s*\|)+\s*$/.test(lines[i]) && /\|/.test(lines[i - 1])) {
        var normHeader = lines[i - 1].replace(/\s+/g, '');
        for (var j = used; j < originals.length; j++) {
          if (originals[j].header === normHeader) {
            lines[i] = originals[j].separator;
            used = j + 1;
            break;
          }
        }
      }
    }
    return lines.join('\n');
  }

  function preprocessHorizontalRules(markdown) {
    if (!markdown || typeof markdown !== 'string') return { rules: [] };
    var rules = [];
    var lines = markdown.split('\n');
    var inFencedCode = false;
    var fencePattern = null;
    var hrRe = /^\s*([-*_])(\s*\1){2,}\s*$/;
    for (var i = 0; i < lines.length; i++) {
      var line = lines[i];
      if (inFencedCode) {
        if (fencePattern && fencePattern.test(line)) {
          inFencedCode = false;
          fencePattern = null;
        }
        continue;
      }
      var fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})/);
      if (fenceMatch) {
        inFencedCode = true;
        var fc = fenceMatch[2];
        fencePattern = new RegExp('^\\s*' + fc.charAt(0) + '{' + fc.length + ',}\\s*$');
        continue;
      }
      if (!hrRe.test(line)) continue;
      if (/^\s*-/.test(line)) {
        var isSetext = false;
        for (var j = i - 1; j >= 0; j--) {
          if (/^\s*$/.test(lines[j])) break;
          isSetext = true;
          break;
        }
        if (isSetext) continue;
      }
      rules.push(line);
    }
    return { rules: rules };
  }

  function postprocessHorizontalRules(markdown, hrData) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    if (!hrData || !hrData.rules || !hrData.rules.length) return markdown;
    var originals = hrData.rules;
    var used = 0;
    var lines = markdown.split('\n');
    var inFencedCode = false;
    var fencePattern = null;
    for (var i = 0; i < lines.length; i++) {
      if (used >= originals.length) break;
      var line = lines[i];
      if (inFencedCode) {
        if (fencePattern && fencePattern.test(line)) {
          inFencedCode = false;
          fencePattern = null;
        }
        continue;
      }
      var fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})/);
      if (fenceMatch) {
        inFencedCode = true;
        var fc = fenceMatch[2];
        fencePattern = new RegExp('^\\s*' + fc.charAt(0) + '{' + fc.length + ',}\\s*$');
        continue;
      }
      if (/^\s*---\s*$/.test(line)) {
        lines[i] = originals[used];
        used++;
      }
    }
    return lines.join('\n');
  }

  function _scanInlineCodeSpans(markdown) {
    var spans = [];
    if (!markdown) return spans;
    var i = 0;
    var len = markdown.length;
    while (i < len) {
      var ch = markdown.charAt(i);
      if (ch !== '`' && ch !== '~') { i++; continue; }
      var indent = 0;
      var k = i - 1;
      while (k >= 0 && markdown.charAt(k) === ' ') { indent++; k--; }
      var atLineStart = (k < 0 || markdown.charAt(k) === '\n');
      var runStart = i;
      var runChar = ch;
      var runLen = 0;
      while (i < len && markdown.charAt(i) === runChar) { runLen++; i++; }
      if (atLineStart && runLen >= 3) {
        while (i < len && markdown.charAt(i) !== '\n') i++;
        if (i < len) i++;
        while (i < len) {
          var closeIndent = 0;
          while (i < len && markdown.charAt(i) === ' ') { closeIndent++; i++; }
          if (i < len && markdown.charAt(i) === runChar && closeIndent === indent) {
            var cl = 0;
            while (i < len && markdown.charAt(i) === runChar) { cl++; i++; }
            if (cl >= runLen) {
              var trailingOk = true;
              while (i < len && markdown.charAt(i) !== '\n') {
                if (markdown.charAt(i) !== ' ' && markdown.charAt(i) !== '\t') trailingOk = false;
                i++;
              }
              if (trailingOk) {
                if (i < len) i++;
                break;
              }
              continue;
            }
          }
          while (i < len && markdown.charAt(i) !== '\n') i++;
          if (i < len) i++;
        }
        continue;
      }
      if (runChar === '~') continue;
      var contentStart = i;
      var found = false;
      while (i < len) {
        if (markdown.charAt(i) === '`') {
          var closeStart = i;
          var closeLen = 0;
          while (i < len && markdown.charAt(i) === '`') { closeLen++; i++; }
          if (closeLen === runLen) {
            spans.push({
              start: runStart,
              end: i,
              content: markdown.substring(contentStart, closeStart),
              full: markdown.substring(runStart, i)
            });
            found = true;
            break;
          }
        } else { i++; }
      }
      if (!found) i = runStart + runLen;
    }
    return spans;
  }

  function preprocessInlineCode(markdown) {
    if (!markdown || typeof markdown !== 'string') return { inlineCodeOriginals: [] };
    var spans = _scanInlineCodeSpans(markdown);
    var originals = [];
    for (var i = 0; i < spans.length; i++) {
      if (spans[i].content.indexOf('\n') >= 0) {
        originals.push({
          original: spans[i].full,
          normalized: spans[i].content.replace(/\s+/g, ' ').trim()
        });
      }
    }
    return { inlineCodeOriginals: originals };
  }

  function postprocessInlineCode(markdown, data) {
    if (!data || !data.inlineCodeOriginals || !data.inlineCodeOriginals.length) return markdown;
    if (!markdown || typeof markdown !== 'string') return markdown;
    var spans = _scanInlineCodeSpans(markdown);
    if (spans.length === 0) return markdown;
    var used = [];
    var replacements = [];
    for (var i = 0; i < spans.length; i++) {
      var normalized = spans[i].content.replace(/\s+/g, ' ').trim();
      for (var j = 0; j < data.inlineCodeOriginals.length; j++) {
        if (!used[j] && data.inlineCodeOriginals[j].normalized === normalized) {
          used[j] = true;
          replacements.push({ start: spans[i].start, end: spans[i].end, replacement: data.inlineCodeOriginals[j].original });
          break;
        }
      }
    }
    if (replacements.length === 0) return markdown;
    replacements.sort(function (a, b) { return b.start - a.start; });
    var result = markdown;
    for (var i = 0; i < replacements.length; i++) {
      var r = replacements[i];
      result = result.slice(0, r.start) + r.replacement + result.slice(r.end);
    }
    return result;
  }

  var RAW_HTML_ATTR = 'data-live-wysiwyg-raw-html';
  var RAW_HTML_CLOSE_PREFIX = 'live-wysiwyg-raw-close:';
  var RAW_HTML_COMMENT_ATTR = 'data-live-wysiwyg-html-comment';
  var RAW_HTML_NEWLINES_AFTER_ATTR = 'data-live-wysiwyg-newlines-after';
  var RAW_HTML_BLOCK_ATTR = 'data-live-wysiwyg-raw-html-block';

  function _serializeElementAsHtml(node) {
    if (node.nodeType === 3) return node.textContent;
    if (node.nodeType !== 1) return '';
    if (node.hasAttribute && (node.hasAttribute('data-live-wysiwyg-cursor') || node.hasAttribute('data-live-wysiwyg-cursor-end'))) return '';
    var tag = node.nodeName.toLowerCase();
    var attrs = '';
    if (node.attributes) {
      for (var ai = 0; ai < node.attributes.length; ai++) {
        var attr = node.attributes[ai];
        if (attr.name === RAW_HTML_ATTR || attr.name === RAW_HTML_COMMENT_ATTR || attr.name === RAW_HTML_BLOCK_ATTR) continue;
        attrs += ' ' + attr.name + '="' + attr.value.replace(/"/g, '&quot;') + '"';
      }
    }
    var voidTags = ['br','hr','img','input','col','area','base','link','meta','source','track','wbr'];
    if (voidTags.indexOf(tag) >= 0) return '<' + tag + attrs + '>';
    var inner = '';
    for (var ci = 0; ci < node.childNodes.length; ci++) {
      inner += _serializeElementAsHtml(node.childNodes[ci]);
    }
    return '<' + tag + attrs + '>' + inner + '</' + tag + '>';
  }

  function _countBlockTagDepth(line, tagName) {
    var re = new RegExp('<(/??)\\s*' + tagName + '\\b([^>]*?)(/?)\\s*>', 'gi');
    var depth = 0;
    var m;
    while ((m = re.exec(line)) !== null) {
      var isClose = m[1] === '/';
      var isSelfClose = m[3] === '/';
      if (isClose) depth--;
      else if (!isSelfClose) depth++;
    }
    return depth;
  }

  var _rawHtmlVoidTags = ['br','hr','img','input','col','area','base','link','meta','source','track','wbr'];

  function _b64Encode(str) {
    try { return btoa(unescape(encodeURIComponent(str))); }
    catch (e) { return btoa(str); }
  }

  function _b64Decode(str) {
    try { return decodeURIComponent(escape(atob(str))); }
    catch (e) { try { return atob(str); } catch (e2) { return str; } }
  }

  function _stripCommonLeadingWhitespace(text) {
    var lines = text.split('\n');
    var minIndent = Infinity;
    for (var i = 0; i < lines.length; i++) {
      if (lines[i].trim().length === 0) continue;
      var leading = lines[i].match(/^(\s*)/)[1].length;
      if (leading < minIndent) minIndent = leading;
    }
    if (minIndent > 0 && minIndent < Infinity) {
      for (var i = 0; i < lines.length; i++) {
        if (lines[i].trim().length === 0) continue;
        lines[i] = lines[i].substring(minIndent);
      }
    }
    return lines.join('\n');
  }

  var _keepBlankBeforeListRe = /^\s*(`{3,}|~{3,})\s*$|^\s*<|^\s*>|\u0000__RAWHTMLBLOCK_/;
  var _isOlContextLineRe = /^\s*\d+\.\s/;
  var _isUlContextLineRe = /^\s*[-*+]\s/;
  var _listLineStartsCodeBlockRe = /^\s*[-*+]\s+(`{3,}|~{3,})/;
  var _olLineStartsCodeBlockRe = /^\s*\d+\.\s+(`{3,}|~{3,})/;

  function _compactOlBlankLines(text) {
    return text.replace(/([^\n]*)\n[ \t]*\n(?=(\s*\d+\.\s[^\n]*))/g, function (match, prevLine, nextLine) {
      if (_keepBlankBeforeListRe.test(prevLine)) return match;
      if (!_isOlContextLineRe.test(prevLine)) return match;
      if (nextLine && _olLineStartsCodeBlockRe.test(nextLine)) return match;
      return prevLine + '\n';
    });
  }

  function _compactUlBlankLines(text) {
    return text.replace(/([^\n]*)\n[ \t]*\n(?=(\s*[-*+]\s[^\n]*))/g, function (match, prevLine, nextLine) {
      if (_keepBlankBeforeListRe.test(prevLine)) return match;
      if (!_isUlContextLineRe.test(prevLine)) return match;
      if (nextLine && _listLineStartsCodeBlockRe.test(nextLine)) return match;
      return prevLine + '\n';
    });
  }

  function _isHtmlTagKnownToMarkdown(tag) {
    var m = tag.match(/^<\/?([a-zA-Z][a-zA-Z0-9]*)/);
    if (!m) return false;
    var name = m[1].toLowerCase();
    var mdTags = ['p','br','hr','em','strong','del','s','strike','b','i','u',
      'h1','h2','h3','h4','h5','h6','ul','ol','li','blockquote',
      'pre','code','a','img','table','thead','tbody','tr','th','td',
      'input','sup','sub'];
    return mdTags.indexOf(name) >= 0;
  }

  /**
   * Ref definitions between HTML comments (e.g. <!-- prettier-ignore-start --> ... <!-- prettier-ignore-end -->)
   * are not parsed by marked because the comment placeholders create a block context where ref defs are ignored.
   * Extract such ref defs and move them to the end of the document so marked can resolve shortcut links.
   */
  function extractRefDefsFromCommentBlocks(markdown) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    var refDefRe = /^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/;
    var commentRe = /^\s*<!--\s*[\s\S]*?-->\s*$/;
    var lines = markdown.split('\n');
    var extracted = [];
    var i = 0;
    while (i < lines.length) {
      var line = lines[i];
      if (commentRe.test(line)) {
        var blockStart = i;
        i++;
        var between = [];
        while (i < lines.length && !commentRe.test(lines[i])) {
          between.push(lines[i]);
          i++;
        }
        if (i < lines.length && commentRe.test(lines[i])) {
          var refDefLines = [];
          var otherLines = [];
          for (var j = 0; j < between.length; j++) {
            if (refDefRe.test(between[j])) {
              refDefLines.push(between[j]);
            } else {
              otherLines.push(between[j]);
            }
          }
          if (refDefLines.length > 0) {
            extracted = extracted.concat(refDefLines);
            lines = lines.slice(0, blockStart + 1).concat(otherLines).concat(lines.slice(i));
            i = blockStart + 1 + otherLines.length;
          }
        }
        i++;
      } else {
        i++;
      }
    }
    if (extracted.length === 0) return markdown;
    var suffix = (lines.length > 0 && lines[lines.length - 1] !== '') ? '\n\n' : '\n';
    return lines.join('\n') + suffix + extracted.join('\n');
  }

  /**
   * Move ref definitions from the end of the document to the beginning.
   * When ref defs are at the end after a comment placeholder span, marked may parse them
   * as paragraph content (with URLs autolinked), causing them to appear in the HTML.
   * Placing them at the start ensures they are parsed as metadata and never rendered.
   * Preserves frontmatter: ref defs are inserted after the frontmatter block if present.
   */
  function moveRefDefsFromEndToStart(markdown) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    var refDefRe = /^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/;
    var lines = markdown.split('\n');
    var i = lines.length - 1;
    var refDefLines = [];
    while (i >= 0 && refDefRe.test(lines[i])) {
      refDefLines.unshift(lines[i]);
      i--;
    }
    while (i >= 0 && /^\s*$/.test(lines[i])) i--;
    if (refDefLines.length === 0) return markdown;
    var bodyContent = lines.slice(0, i + 1).join('\n');
    var parsed = parseFrontmatter(bodyContent);
    var refDefBlock = refDefLines.join('\n') + '\n\n';
    if (parsed.frontmatter) {
      return parsed.frontmatter + '\n' + refDefBlock + parsed.body;
    }
    return refDefBlock + parsed.body;
  }

  /**
   * Restore ref definitions between HTML comment pairs when serializing to markdown.
   * extractRefDefsFromCommentBlocks moves ref defs to the end for marked parsing; this
   * restores the original structure (ref defs between comments) and removes extra newlines.
   */
  function restoreRefDefsToCommentBlocks(markdown) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    var refDefRe = /^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/;
    var commentRe = /^\s*<!--\s*[\s\S]*?-->\s*$/;
    var lines = markdown.split('\n');
    var i = lines.length - 1;
    var refDefLines = [];
    while (i >= 0 && refDefRe.test(lines[i])) {
      refDefLines.unshift(lines[i]);
      i--;
    }
    while (i >= 0 && /^\s*$/.test(lines[i])) i--;
    if (refDefLines.length === 0 || i < 1) return markdown;
    var endCommentIdx = i;
    if (!commentRe.test(lines[endCommentIdx])) return markdown;
    var startCommentIdx = endCommentIdx - 1;
    while (startCommentIdx >= 0 && /^\s*$/.test(lines[startCommentIdx])) startCommentIdx--;
    if (startCommentIdx < 0 || !commentRe.test(lines[startCommentIdx])) return markdown;
    var before = lines.slice(0, startCommentIdx + 1);
    var otherBetween = lines.slice(startCommentIdx + 1, endCommentIdx);
    var afterEndLines = lines.slice(endCommentIdx + 1);
    var afterEndIdx = afterEndLines.length - 1;
    while (afterEndIdx >= 0 && (refDefRe.test(afterEndLines[afterEndIdx]) || /^\s*$/.test(afterEndLines[afterEndIdx]))) {
      afterEndIdx--;
    }
    var afterEnd = afterEndLines.slice(0, afterEndIdx + 1);
    var restored = before.concat(refDefLines).concat(otherBetween).concat([lines[endCommentIdx]]).concat(afterEnd);
    return restored.join('\n');
  }

  function preprocessRawHtml(markdown) {
    if (!markdown || typeof markdown !== 'string') return { markdown: markdown, comments: [], tags: [] };
    markdown = extractRefDefsFromCommentBlocks(markdown);
    markdown = moveRefDefsFromEndToStart(markdown);
    var comments = [];
    var tags = [];

    var lines = markdown.split('\n');
    var inFencedCode = false;
    var fencePattern = null;
    var result = [];

    for (var i = 0; i < lines.length; i++) {
      var line = lines[i];

      if (inFencedCode) {
        if (fencePattern && fencePattern.test(line)) {
          inFencedCode = false;
          fencePattern = null;
        }
        result.push(line);
        continue;
      }

      var fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})/);
      if (fenceMatch) {
        inFencedCode = true;
        var fc = fenceMatch[2];
        fencePattern = new RegExp('^\\s*' + fc.charAt(0) + '{' + fc.length + ',}\\s*$');
        result.push(line);
        continue;
      }

      var admonitionMatch = line.match(/^(\s*)(\?\?\?\+|\?\?\?|!!!)\s+\w+/);
      if (admonitionMatch) {
        result.push(line);
        continue;
      }

      var blockOpenMatch = line.match(/^(\s*)<([a-zA-Z][a-zA-Z0-9]*)\b([^>]*)>/);
      if (blockOpenMatch && !/\/\s*>$/.test(blockOpenMatch[0])) {
        if (line.indexOf(RAW_HTML_COMMENT_ATTR) >= 0) {
          result.push(line);
          continue;
        }
        var bTagName = blockOpenMatch[2].toLowerCase();
        if (!_isHtmlTagKnownToMarkdown('<' + bTagName + '>') && _rawHtmlVoidTags.indexOf(bTagName) < 0) {
          var blockLines = [line];
          var depth = _countBlockTagDepth(line, bTagName);
          var blockClosed = (depth <= 0);
          if (depth > 0) {
            var j = i + 1;
            while (j < lines.length && depth > 0) {
              blockLines.push(lines[j]);
              depth += _countBlockTagDepth(lines[j], bTagName);
              j++;
            }
            blockClosed = (depth <= 0);
            if (blockClosed) i = j - 1;
          }
          if (blockClosed) {
            var fullBlock = blockLines.join('\n');
            var encoded = _b64Encode(fullBlock);
            var blockIndent = blockOpenMatch[1] || '';
            var lastBlockLine = blockLines[blockLines.length - 1];
            var lastCloseIdx = lastBlockLine.lastIndexOf('>');
            var afterCloseOnLine = lastCloseIdx >= 0 ? lastBlockLine.substring(lastCloseIdx + 1) : '';
            var blockNewlinesAfter;
            if (/[^\s]/.test(afterCloseOnLine)) {
              blockNewlinesAfter = 0;
            } else {
              var jBlock = i + blockLines.length;
              var blanksBlock = 0;
              while (jBlock < lines.length && /^\s*$/.test(lines[jBlock])) {
                blanksBlock++;
                jBlock++;
              }
              blockNewlinesAfter = blanksBlock + 1;
            }
            result.push(blockIndent + '<div ' + RAW_HTML_BLOCK_ATTR + '="' + encoded + '" ' + RAW_HTML_NEWLINES_AFTER_ATTR + '="' + blockNewlinesAfter + '"></div>');
            continue;
          }
        }
      }

      var commentProcessed = _preprocessLineComments(line, lines, i, comments, result);
      if (commentProcessed !== false) {
        i = commentProcessed;
        continue;
      }

      var tagProcessed = _preprocessLineTags(line, lines, i, tags, result);
      if (tagProcessed) {
        continue;
      }

      result.push(line);
    }

    return { markdown: result.join('\n'), comments: comments, tags: tags };
  }

  var _blockCommentRe = /^\s*<!--[\s\S]*?-->\s*$/;

  function _preprocessLineComments(line, lines, idx, comments, result) {
    var commentStart = line.indexOf('<!--');
    if (commentStart === -1) return false;

    var commentEnd = line.indexOf('-->', commentStart + 4);
    if (commentEnd !== -1) {
      var before = line.substring(0, commentStart);
      var comment = line.substring(commentStart, commentEnd + 3);
      var after = line.substring(commentEnd + 3);
      var isBlockComment = !before.trim() && !after.trim();
      if (isBlockComment) {
        var blockLines = [line];
        var j = idx + 1;
        while (j < lines.length && _blockCommentRe.test(lines[j])) {
          blockLines.push(lines[j]);
          j++;
        }
        var blanks = 0;
        while (j < lines.length && /^\s*$/.test(lines[j])) {
          blanks++;
          j++;
        }
        var newlinesAfter = blanks + 1;
        var collapsedBlock = blockLines.join('\n').replace(/\s+$/, '');
        var encoded = _b64Encode(collapsedBlock);
        comments.push({ original: collapsedBlock, leading: before, lineIdx: idx });
        var placeholder = '<span ' + RAW_HTML_COMMENT_ATTR + '="' + encoded + '" ' + RAW_HTML_NEWLINES_AFTER_ATTR + '="' + newlinesAfter + '" style="display:none"></span>';
        result.push(before + placeholder + after);
        return j - 1;
      }
      var blanks = 0;
      var k = idx + 1;
      while (k < lines.length && /^\s*$/.test(lines[k])) {
        blanks++;
        k++;
      }
      var newlinesAfterInline = blanks + 1;
      var originalForEncode = comment.replace(/\s+$/, '');
      var encoded = _b64Encode(originalForEncode);
      comments.push({ original: comment, leading: '', lineIdx: idx });
      var placeholder = '<span ' + RAW_HTML_COMMENT_ATTR + '="' + encoded + '" ' + RAW_HTML_NEWLINES_AFTER_ATTR + '="' + newlinesAfterInline + '" style="display:none"></span>';
      result.push(before + placeholder + after);
      return idx;
    }

    var multiLines = [line];
    var j = idx + 1;
    while (j < lines.length) {
      multiLines.push(lines[j]);
      if (lines[j].indexOf('-->') !== -1) break;
      j++;
    }
    var fullComment = multiLines.join('\n');
    var endPos = fullComment.indexOf('-->');
    if (endPos === -1) {
      result.push(line);
      return false;
    }
    var leading = line.substring(0, commentStart);
    var commentText = fullComment.substring(commentStart, endPos + 3);
    var afterComment = fullComment.substring(endPos + 3);
    var isBlockComment = !leading.trim();
    var originalForEncode = (isBlockComment ? leading + commentText : commentText).replace(/\s+$/, '');

    var blanksMulti = 0;
    var kMulti = j + 1;
    while (kMulti < lines.length && /^\s*$/.test(lines[kMulti])) {
      blanksMulti++;
      kMulti++;
    }
    var newlinesAfterMulti = blanksMulti + 1;

    var encoded = _b64Encode(originalForEncode);
    comments.push({ original: commentText, leading: isBlockComment ? leading : '', lineIdx: idx });
    var placeholder = '<span ' + RAW_HTML_COMMENT_ATTR + '="' + encoded + '" ' + RAW_HTML_NEWLINES_AFTER_ATTR + '="' + newlinesAfterMulti + '" style="display:none"></span>';
    var afterLines = afterComment.split('\n');
    result.push(leading + placeholder + afterLines[0]);
    for (var k = 1; k < afterLines.length; k++) {
      result.push(afterLines[k]);
    }
    return j;
  }

  function _preprocessLineTags(line, lines, idx, tags, result) {
    var tagRe = /<(\/?)\s*([a-zA-Z][a-zA-Z0-9]*)\b([^>]*?)(\/?)>/g;
    var out = '';
    var lastIdx = 0;
    var changed = false;
    var m;

    var codeSpans = [];
    var csm;
    var csReDouble = /``(?:[^`]|`(?!`))*``/g;
    while ((csm = csReDouble.exec(line)) !== null) {
      codeSpans.push({ start: csm.index, end: csm.index + csm[0].length });
    }
    function isInsideCodeSpan(pos) {
      for (var k = 0; k < codeSpans.length; k++) {
        if (pos >= codeSpans[k].start && pos < codeSpans[k].end) return true;
      }
      return false;
    }
    var csReSingle = /`[^`\n]+`/g;
    while ((csm = csReSingle.exec(line)) !== null) {
      if (!isInsideCodeSpan(csm.index)) codeSpans.push({ start: csm.index, end: csm.index + csm[0].length });
    }

    while ((m = tagRe.exec(line)) !== null) {
      if (isInsideCodeSpan(m.index)) continue;

      var fullTag = m[0];
      var tagName = m[2];
      var isClose = m[1] === '/';
      var isSelfClose = m[4] === '/';

      if (_isHtmlTagKnownToMarkdown(fullTag)) continue;

      var tagContent = m[3] || '';
      if (!isClose && /^:\/\//.test(tagContent)) continue;
      var innerText = tagName + tagContent;
      if (!isClose && innerText.indexOf('@') >= 0 && innerText.indexOf(' ') === -1) continue;

      changed = true;

      var prefixText = line.substring(lastIdx, m.index);
      var onlyWhitespace = /^[ \t]*$/.test(prefixText);
      var originalForEncode = (onlyWhitespace && lastIdx === 0) ? prefixText + fullTag : fullTag;

      out += prefixText;

      if (isSelfClose) {
        var encoded = _b64Encode(originalForEncode);
        tags.push({ original: originalForEncode, type: 'selfclose' });
        out += fullTag.replace(/\/?>$/, ' ' + RAW_HTML_ATTR + '="' + encoded + '"/>');
      } else if (isClose) {
        var restOfLine = line.substring(m.index + fullTag.length);
        var newlinesAfterTag = 0;
        if (/^\s*$/.test(restOfLine)) {
          var jTag = idx + 1;
          while (jTag < lines.length && /^\s*$/.test(lines[jTag])) jTag++;
          newlinesAfterTag = 1 + (jTag - idx - 1);
        }
        var encoded = _b64Encode(originalForEncode);
        tags.push({ original: originalForEncode, type: 'close' });
        out += fullTag + '<!--' + RAW_HTML_CLOSE_PREFIX + encoded + '|' + newlinesAfterTag + '-->';
      } else {
        var encoded = _b64Encode(originalForEncode);
        tags.push({ original: originalForEncode, type: 'open' });
        out += fullTag.replace(/>$/, ' ' + RAW_HTML_ATTR + '="' + encoded + '">');
      }
      lastIdx = m.index + fullTag.length;
    }

    if (!changed) return false;
    out += line.substring(lastIdx);
    result.push(out);
    return true;
  }

  function postprocessRawHtml(markdown, rawHtmlData) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    markdown = restoreRefDefsToCommentBlocks(markdown);
    if (!rawHtmlData) return markdown;
    return markdown;
  }

  var CURSOR_SPAN_HTML_RE = /<span\s+data-live-wysiwyg-cursor(?:-end)?[^>]*>\s*<\/span>/gi;
  var CURSOR_UNICODE_RE = /[\u200C\u200D]{2,}/g;

  function stripCursorSpanHtml(s) {
    if (!s || typeof s !== 'string') return s || '';
    return s.replace(CURSOR_SPAN_HTML_RE, '');
  }

  function normalizeUrl(url) {
    if (!url || typeof url !== 'string') return '';
    url = url.replace(/^<|>$/g, '').replace(CURSOR_UNICODE_RE, '').trim();
    try {
      url = decodeURIComponent(url);
    } catch (e) {}
    return url.replace(/\/+$/, '') || url;
  }

  function preprocessMarkdownLinks(markdown) {
    if (!markdown || typeof markdown !== 'string') {
      return { linkOriginals: [], refDefinitions: '' };
    }
    var linkOriginals = [];
    var refs = {};
    var refDefLines = [];
    var lines = markdown.split('\n');
    var i, m, refId, url, text;

    for (i = 0; i < lines.length; i++) {
      m = lines[i].match(/^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/);
      if (m) {
        refId = m[1];
        url = (m[2] || m[3] || '').trim();
        refs[refId.toLowerCase()] = url;
        refDefLines.push(lines[i]);
      }
    }
    var refDefinitions = refDefLines.length ? refDefLines.join('\n') : '';

    var pos = 0;
    var inlineLinkRe = /\[([^\]]*)\]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
    var inlineImgRe = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
    var fullRefRe = /\[([^\]]*)\]\[([^\]]*)\]/g;
    var fullImgRefRe = /!\[([^\]]*)\]\[([^\]]*)\]/g;
    var shortcutRe = /\[([^\]]+)\](?!\s*[(\[])/g;
    var shortcutImgRe = /!\[([^\]]+)\](?!\s*[(\[])/g;
    var autolinkRe = /<(https?:\/\/[^>]+)>/g;
    var match, best, bestPos;

    while (pos < markdown.length) {
      best = null;
      bestPos = markdown.length;

      inlineLinkRe.lastIndex = pos;
      match = inlineLinkRe.exec(markdown);
      if (match && match.index < bestPos) {
        bestPos = match.index;
        best = { url: normalizeUrl(match[2]), text: match[1], original: match[0] };
      }

      inlineImgRe.lastIndex = pos;
      match = inlineImgRe.exec(markdown);
      if (match && match.index < bestPos) {
        bestPos = match.index;
        best = { url: normalizeUrl(match[2]), text: match[1], original: match[0], isImage: true };
      }

      fullRefRe.lastIndex = pos;
      match = fullRefRe.exec(markdown);
      if (match && refs[match[2].toLowerCase()] && match.index < bestPos) {
        bestPos = match.index;
        best = { url: normalizeUrl(refs[match[2].toLowerCase()]), text: match[1], original: match[0] };
      }

      fullImgRefRe.lastIndex = pos;
      match = fullImgRefRe.exec(markdown);
      if (match && refs[match[2].toLowerCase()] && match.index < bestPos) {
        bestPos = match.index;
        best = { url: normalizeUrl(refs[match[2].toLowerCase()]), text: match[1], original: match[0], isImage: true };
      }

      shortcutRe.lastIndex = pos;
      match = shortcutRe.exec(markdown);
      if (match && refs[match[1].toLowerCase()] && match.index < bestPos) {
        bestPos = match.index;
        best = { url: normalizeUrl(refs[match[1].toLowerCase()]), text: match[1], original: match[0] };
      }

      shortcutImgRe.lastIndex = pos;
      match = shortcutImgRe.exec(markdown);
      if (match && refs[match[1].toLowerCase()] && match.index < bestPos) {
        bestPos = match.index;
        best = { url: normalizeUrl(refs[match[1].toLowerCase()]), text: match[1], original: match[0], isImage: true };
      }

      autolinkRe.lastIndex = pos;
      match = autolinkRe.exec(markdown);
      if (match && match.index < bestPos) {
        bestPos = match.index;
        best = { url: normalizeUrl(match[1]), text: match[1], original: match[0], isAutolink: true };
      }

      if (!best) break;
      linkOriginals.push(best);
      pos = bestPos + best.original.length;
    }

    return { linkOriginals: linkOriginals, refDefinitions: refDefinitions };
  }

  function postprocessMarkdownLinks(markdown, linkData) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    if (!linkData) return markdown;

    var linkOriginals = linkData.linkOriginals || [];
    var refDefinitions = linkData.refDefinitions || '';
    var refDefsByUrl = {};
    if (refDefinitions) {
      var refDefRe = /^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/gm;
      var rd;
      while ((rd = refDefRe.exec(refDefinitions)) !== null) {
        var rDefName = rd[1];
        var rDefUrl = normalizeUrl(rd[2] || rd[3] || '');
        if (rDefUrl && !refDefsByUrl[rDefUrl]) refDefsByUrl[rDefUrl] = rDefName;
      }
    }

    var inlineLinkRe = /\[([^\]]*)\]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
    var inlineImgRe = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
    var spanCursorRe = new RegExp('<span\\s+' + CURSOR_SPAN_ATTR + '\\s*></span>', 'g');
    var spanCursorEndRe = new RegExp('<span\\s+' + CURSOR_SPAN_ATTR_END + '\\s*></span>', 'g');
    var used = [];

    function stripMarkers(s) {
      return s.replace(CURSOR_MARKER_RE, '').replace(CURSOR_MARKER_END_RE, '').replace(spanCursorRe, '').replace(spanCursorEndRe, '');
    }

    function normalizeLinkText(s) {
      return (stripMarkers(s) || '').replace(/\s+/g, ' ').replace(/\u00a0/g, ' ').trim();
    }
    function replaceMatch(match, text, url, isImage) {
      var cleanUrl = normalizeUrl(url);
      var cleanText = normalizeLinkText(text);
      for (var i = 0; i < linkOriginals.length; i++) {
        var origText = normalizeLinkText(linkOriginals[i].text);
        var origUrl = normalizeUrl(linkOriginals[i].url);
        if (!used[i] && origUrl === cleanUrl && origText === cleanText && !!linkOriginals[i].isImage === !!isImage) {
          used[i] = true;
          var orig = stripMarkers(linkOriginals[i].original);
          if (cleanText !== text) {
            var textStart = orig.indexOf('[') + 1;
            var textEnd = orig.indexOf(']', textStart);
            orig = orig.slice(0, textStart) + text + orig.slice(textEnd);
          }
          return orig;
        }
      }
      if (!isImage) {
        var shortcutRefName = refDefsByUrl[cleanUrl];
        if (shortcutRefName && shortcutRefName.toLowerCase() === cleanText.toLowerCase()) {
          return '[' + text + ']';
        }
      }
      return match;
    }

    var result = markdown
      .replace(inlineLinkRe, function (match, text, url) { return replaceMatch(match, text, url, false); })
      .replace(inlineImgRe, function (match, text, url) { return replaceMatch(match, text, url, true); });

    if (refDefinitions) {
      var refDefNameRe = /^\s{0,3}\[([^\]]+)\]:/;
      var existingRefNames = {};
      var resultLines = result.split('\n');
      for (var ri = 0; ri < resultLines.length; ri++) {
        var rm = resultLines[ri].match(refDefNameRe);
        if (rm) existingRefNames[rm[1].toLowerCase()] = true;
      }
      var defLines = refDefinitions.split('\n');
      var missingDefs = [];
      for (var di = 0; di < defLines.length; di++) {
        if (!defLines[di].trim()) continue;
        var dm = defLines[di].match(refDefNameRe);
        if (dm && existingRefNames[dm[1].toLowerCase()]) continue;
        missingDefs.push(defLines[di]);
      }
      if (missingDefs.length > 0) {
        var defsToAppend = missingDefs.join('\n');
        var trimmed = result.replace(/\s+$/, '');
        var lastOpenIdx = trimmed.lastIndexOf('<!--');
        var inserted = false;
        if (lastOpenIdx >= 0) {
          var afterLastOpen = trimmed.slice(lastOpenIdx);
          var closingIdx = afterLastOpen.indexOf('-->');
          if (closingIdx >= 0 && afterLastOpen.slice(closingIdx + 3).trim() === '') {
            var before = trimmed.slice(0, lastOpenIdx).replace(/\s+$/, '');
            var after = trimmed.slice(lastOpenIdx);
            var lastLineBefore = before.slice(before.lastIndexOf('\n') + 1);
            var endsWithRefDef = refDefNameRe.test(lastLineBefore);
            var endsWithHtmlComment = /^\s*<!--[\s\S]*?-->\s*$/.test(lastLineBefore);
            var sep = endsWithRefDef ? '\n' : (endsWithHtmlComment ? '\n' : '\n\n');
            result = before + sep + defsToAppend + '\n' + after + '\n';
            inserted = true;
          }
        }
        if (!inserted) {
          var lastLine = trimmed.slice(trimmed.lastIndexOf('\n') + 1);
          var endsWithRefDef = refDefNameRe.test(lastLine);
          result = trimmed + (endsWithRefDef ? '\n' : '\n\n') + defsToAppend + '\n';
        }
      }
    }
    return result;
  }

  /**
   * Convert redundant reference-style links [text][ref] back to shortcut form [text]
   * when ref id equals link text (case-insensitive). Preserves original shortcut style.
   */
  function collapseRedundantReferenceToShortcut(markdown) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    return markdown.replace(/\[([^\]]+)\]\[([^\]]+)\]/g, function (match, text, ref) {
      if (text.toLowerCase() === ref.toLowerCase()) return '[' + text + ']';
      return match;
    });
  }

  function removeUnusedRefDefs(markdown) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    var parsed = parseFrontmatter(markdown);
    var body = parsed.body;
    if (!body) return markdown;

    var refDefLineRe = /^\s{0,3}\[([^\]]+)\]:\s/gm;
    var defNames = {};
    var m;
    while ((m = refDefLineRe.exec(body)) !== null) {
      defNames[m[1].toLowerCase()] = true;
    }
    if (Object.keys(defNames).length === 0) return markdown;

    var usedNames = {};
    var fullRefRe = /!?\[[^\]]*\]\[([^\]]+)\]/g;
    while ((m = fullRefRe.exec(body)) !== null) {
      usedNames[m[1].toLowerCase()] = true;
    }
    for (var name in defNames) {
      if (usedNames[name]) continue;
      var escaped = name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      var shortcutRe = new RegExp('(?:^|[^!])\\[' + escaped + '\\](?!\\s*[:\\[(])', 'im');
      if (shortcutRe.test(body)) usedNames[name] = true;
    }

    var hasUnused = false;
    for (var name in defNames) {
      if (!usedNames[name]) { hasUnused = true; break; }
    }
    if (!hasUnused) return markdown;

    var lines = body.split('\n');
    var filtered = [];
    for (var i = 0; i < lines.length; i++) {
      var dm = lines[i].match(/^\s{0,3}\[([^\]]+)\]:\s/);
      if (dm && !usedNames[dm[1].toLowerCase()]) continue;
      filtered.push(lines[i]);
    }
    var result = filtered.join('\n').replace(/\n{3,}/g, '\n\n');
    return serializeWithFrontmatter(parsed.frontmatter, result);
  }

  function renumberRefDefs(markdown) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    var parsed = parseFrontmatter(markdown);
    var body = parsed.body;
    if (!body) return markdown;

    var firstAppearance = {};
    var m;
    var useRe = /\]\[(\d+)\]/g;
    while ((m = useRe.exec(body)) !== null) {
      if (!(m[1] in firstAppearance)) firstAppearance[m[1]] = m.index;
    }
    var defRe = /^\s{0,3}\[(\d+)\]:\s/gm;
    while ((m = defRe.exec(body)) !== null) {
      if (!(m[1] in firstAppearance)) firstAppearance[m[1]] = m.index;
    }

    var refKeys = Object.keys(firstAppearance);
    if (refKeys.length === 0) return markdown;

    var sorted = refKeys.sort(function (a, b) {
      return firstAppearance[a] - firstAppearance[b];
    });

    var needsRenumber = false;
    for (var i = 0; i < sorted.length; i++) {
      if (sorted[i] !== String(i + 1)) { needsRenumber = true; break; }
    }
    if (!needsRenumber) return markdown;

    var mapping = {};
    for (var i = 0; i < sorted.length; i++) {
      mapping[sorted[i]] = String(i + 1);
    }

    var PH = '\uFFFF';
    var result = body.replace(/\]\[(\d+)\]/g, function (m, num) {
      return mapping[num] ? '][' + PH + mapping[num] + PH + ']' : m;
    });
    result = result.replace(/^(\s{0,3})\[(\d+)\]:/gm, function (m, indent, num) {
      return mapping[num] ? indent + '[' + PH + mapping[num] + PH + ']:' : m;
    });
    var phRe = new RegExp(PH + '(\\d+)' + PH, 'g');
    result = result.replace(phRe, function (m, num) { return num; });

    var lines = result.split('\n');
    var defLineRe = /^\s{0,3}\[(\d+)\]:\s/;
    var defIndices = [];
    var defEntries = [];
    for (var i = 0; i < lines.length; i++) {
      var dm = lines[i].match(defLineRe);
      if (dm) {
        defIndices.push(i);
        defEntries.push({ num: parseInt(dm[1], 10), line: lines[i] });
      }
    }
    if (defEntries.length > 1) {
      defEntries.sort(function (a, b) { return a.num - b.num; });
      for (var i = 0; i < defIndices.length; i++) {
        lines[defIndices[i]] = defEntries[i].line;
      }
      result = lines.join('\n');
    }

    return serializeWithFrontmatter(parsed.frontmatter, result);
  }

  function dryDuplicateInlineLinks(markdown, linkData) {
    if (!markdown || typeof markdown !== 'string') return markdown;

    var parsed = parseFrontmatter(markdown);
    var body = parsed.body;
    if (!body) return markdown;


    var codeRanges = [];
    var fencedRe = /^(`{3,}|~{3,}).*\n[\s\S]*?\n\1\s*$/gm;
    var fm;
    var bodyNoFences = body;
    while ((fm = fencedRe.exec(body)) !== null) {
      codeRanges.push({ start: fm.index, end: fm.index + fm[0].length });
      var blank = body.slice(fm.index, fm.index + fm[0].length).replace(/[^\n]/g, ' ');
      bodyNoFences = bodyNoFences.slice(0, fm.index) + blank + bodyNoFences.slice(fm.index + fm[0].length);
    }
    var inlineCodeReDouble = /``(?:[^`]|`(?!`))*``/g;
    while ((fm = inlineCodeReDouble.exec(bodyNoFences)) !== null) {
      codeRanges.push({ start: fm.index, end: fm.index + fm[0].length });
    }
    function insideCodeBlock(idx) {
      for (var fi = 0; fi < codeRanges.length; fi++) {
        if (idx >= codeRanges[fi].start && idx < codeRanges[fi].end) return true;
      }
      return false;
    }
    var inlineCodeReSingle = /`[^`]+`/g;
    while ((fm = inlineCodeReSingle.exec(bodyNoFences)) !== null) {
      if (!insideCodeBlock(fm.index)) codeRanges.push({ start: fm.index, end: fm.index + fm[0].length });
    }

    function _balancedBracketScan(str, startAfterBracket) {
      var depth = 1;
      var i = startAfterBracket;
      while (i < str.length && depth > 0) {
        if (str.charAt(i) === '`') { i++; while (i < str.length && str.charAt(i) !== '`') i++; if (i < str.length) i++; continue; }
        if (str.charAt(i) === '[') depth++;
        else if (str.charAt(i) === ']') depth--;
        if (depth > 0) i++;
      }
      return depth === 0 ? i : -1;
    }
    function _balancedParenScan(str, startAfterParen) {
      var depth = 1;
      var i = startAfterParen;
      while (i < str.length && depth > 0) {
        if (str.charAt(i) === '(') depth++;
        else if (str.charAt(i) === ')') depth--;
        if (depth > 0) i++;
      }
      return depth === 0 ? i : -1;
    }

    function findInlineImages(str) {
      var results = [];
      var i = 0;
      while (i < str.length) {
        if (str.charAt(i) === '`') { i++; while (i < str.length && str.charAt(i) !== '`') i++; if (i < str.length) i++; continue; }
        if (str.charAt(i) !== '!' || i + 1 >= str.length || str.charAt(i + 1) !== '[') { i++; continue; }
        var matchStart = i;
        var bracketEnd = _balancedBracketScan(str, matchStart + 2);
        if (bracketEnd < 0 || bracketEnd + 1 >= str.length || str.charAt(bracketEnd + 1) !== '(') { i = matchStart + 2; continue; }
        var parenEnd = _balancedParenScan(str, bracketEnd + 2);
        if (parenEnd < 0) { i = bracketEnd + 1; continue; }
        results.push({
          text: str.substring(matchStart + 2, bracketEnd),
          rawUrl: str.substring(bracketEnd + 2, parenEnd),
          fullMatch: str.substring(matchStart, parenEnd + 1),
          index: matchStart,
          endIndex: parenEnd + 1,
          isImage: true
        });
        i = parenEnd + 1;
      }
      return results;
    }

    function findInlineLinks(str) {
      var results = [];
      var i = 0;
      while (i < str.length) {
        if (str.charAt(i) === '`') { i++; while (i < str.length && str.charAt(i) !== '`') i++; if (i < str.length) i++; continue; }
        if (str.charAt(i) !== '[') { i++; continue; }
        if (i > 0 && str.charAt(i - 1) === '!') { i++; continue; }
        var bracketStart = i;
        var bracketEnd = _balancedBracketScan(str, bracketStart + 1);
        if (bracketEnd < 0 || bracketEnd + 1 >= str.length || str.charAt(bracketEnd + 1) !== '(') { i = (bracketEnd < 0 ? bracketStart : bracketEnd) + 1; continue; }
        var parenEnd = _balancedParenScan(str, bracketEnd + 2);
        if (parenEnd < 0) { i = bracketEnd + 1; continue; }
        results.push({
          text: str.substring(bracketStart + 1, bracketEnd),
          rawUrl: str.substring(bracketEnd + 2, parenEnd),
          fullMatch: str.substring(bracketStart, parenEnd + 1),
          index: bracketStart,
          endIndex: parenEnd + 1,
          isImage: false
        });
        i = parenEnd + 1;
      }
      return results;
    }

    var imageMatches = findInlineImages(body).filter(function (m) { return !insideCodeBlock(m.index); });
    var linkMatches = findInlineLinks(body).filter(function (m) {
      return !insideCodeBlock(m.index) && normalizeUrl(m.text) !== normalizeUrl(m.rawUrl);
    });

    var refsToCreate = {};
    var usedRefNames = {};
    var refCounter = 1;

    var existingRefDefRe = /^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/gm;
    var existingRef;
    var existingRefsByUrl = {};
    while ((existingRef = existingRefDefRe.exec(body)) !== null) {
      var defName = existingRef[1];
      var defUrl = normalizeUrl(existingRef[2] || existingRef[3] || '');
      usedRefNames[defName.toLowerCase()] = true;
      if (defUrl && !existingRefsByUrl[defUrl]) {
        existingRefsByUrl[defUrl] = defName;
      }
    }
    var linkDataRefsByUrl = {};
    if (linkData && linkData.refDefinitions) {
      var refDefRe = /^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/gm;
      var rd;
      while ((rd = refDefRe.exec(linkData.refDefinitions)) !== null) {
        var rDefName = rd[1];
        var rDefUrl = normalizeUrl(rd[2] || rd[3] || '');
        if (rDefUrl && !linkDataRefsByUrl[rDefUrl]) {
          linkDataRefsByUrl[rDefUrl] = rDefName;
        }
      }
    }

    function lookupOrigRefName(url, forImage) {
      var name = linkDataRefsByUrl[url] || null;
      if (!name && linkData && linkData.linkOriginals) {
        for (var i = 0; i < linkData.linkOriginals.length; i++) {
          var o = linkData.linkOriginals[i];
          if (normalizeUrl(o.url) === url && !!o.isImage === forImage) {
            var refM = o.original.match(/\]\[([^\]]+)\]\s*(?:\{[^}]*\})?\s*$/);
            if (refM && refM[1]) return refM[1];
            if (!forImage) {
              var shortM = o.original.match(/^\[([^\]]+)\]$/);
              if (shortM) return shortM[1];
            }
          }
        }
      }
      return name;
    }

    function assignRef(url, forImage, entries) {
      if (refsToCreate[url]) return refsToCreate[url].refName;
      var hasExistingDef = !!existingRefsByUrl[url];
      var origRefName = lookupOrigRefName(url, forImage);
      var hasRefInfo = hasExistingDef || origRefName;
      if (entries.length < 2 && !hasRefInfo) return null;
      var refName = null;
      if (hasExistingDef) refName = existingRefsByUrl[url];
      if (!refName && origRefName) refName = origRefName;
      if (!refName) {
        while (usedRefNames[String(refCounter)]) refCounter++;
        refName = String(refCounter);
        refCounter++;
      }
      usedRefNames[refName.toLowerCase()] = true;
      refsToCreate[url] = { refName: refName, rawUrl: entries[0].rawUrl };
      return refName;
    }

    var imageUrlGroups = {};
    for (var li = 0; li < imageMatches.length; li++) {
      var normUrl = normalizeUrl(imageMatches[li].rawUrl);
      if (!imageUrlGroups[normUrl]) imageUrlGroups[normUrl] = [];
      imageUrlGroups[normUrl].push(imageMatches[li]);
    }
    var linkUrlGroups = {};
    for (var li = 0; li < linkMatches.length; li++) {
      var normUrl = normalizeUrl(linkMatches[li].rawUrl);
      if (!linkUrlGroups[normUrl]) linkUrlGroups[normUrl] = [];
      linkUrlGroups[normUrl].push(linkMatches[li]);
    }

    for (var url in imageUrlGroups) assignRef(url, true, imageUrlGroups[url]);
    for (var url in linkUrlGroups) assignRef(url, false, linkUrlGroups[url]);

    var imageRefByIndex = {};
    for (var url in imageUrlGroups) {
      if (!refsToCreate[url]) continue;
      var entries = imageUrlGroups[url];
      for (var j = 0; j < entries.length; j++) {
        imageRefByIndex[entries[j].index] = {
          text: entries[j].text,
          refName: refsToCreate[url].refName,
          origLen: entries[j].fullMatch.length
        };
      }
    }

    var replacements = [];

    for (var imgIdxStr in imageRefByIndex) {
      var imgIdx = parseInt(imgIdxStr, 10);
      var insideConvertedLink = false;
      for (var li = 0; li < linkMatches.length; li++) {
        var lnkNormUrl = normalizeUrl(linkMatches[li].rawUrl);
        if (!refsToCreate[lnkNormUrl]) continue;
        var textStart = linkMatches[li].index + 1;
        var textEnd = textStart + linkMatches[li].text.length;
        if (imgIdx >= textStart && imgIdx < textEnd) { insideConvertedLink = true; break; }
      }
      if (!insideConvertedLink) {
        var ir = imageRefByIndex[imgIdx];
        replacements.push({
          index: imgIdx,
          length: ir.origLen,
          replacement: '![' + ir.text + '][' + ir.refName + ']'
        });
      }
    }

    for (var url in linkUrlGroups) {
      if (!refsToCreate[url]) continue;
      var entries = linkUrlGroups[url];
      for (var j = 0; j < entries.length; j++) {
        var e = entries[j];
        var modifiedText = e.text;
        var tStart = e.index + 1;
        var innerRepls = [];
        for (var k = 0; k < imageMatches.length; k++) {
          var im = imageMatches[k];
          if (im.index >= tStart && im.endIndex <= tStart + e.text.length) {
            var imRef = imageRefByIndex[im.index];
            if (imRef) {
              innerRepls.push({
                offset: im.index - tStart,
                origLen: im.fullMatch.length,
                replacement: '![' + imRef.text + '][' + imRef.refName + ']'
              });
            }
          }
        }
        innerRepls.sort(function (a, b) { return b.offset - a.offset; });
        for (var k = 0; k < innerRepls.length; k++) {
          var rp = innerRepls[k];
          modifiedText = modifiedText.slice(0, rp.offset) + rp.replacement + modifiedText.slice(rp.offset + rp.origLen);
        }
        replacements.push({
          index: e.index,
          length: e.fullMatch.length,
          replacement: '[' + modifiedText + '][' + refsToCreate[url].refName + ']'
        });
      }
    }

    if (replacements.length === 0) return markdown;

    replacements.sort(function (a, b) { return b.index - a.index; });

    var result = body;
    for (var k = 0; k < replacements.length; k++) {
      var r = replacements[k];
      result = result.slice(0, r.index) + r.replacement + result.slice(r.index + r.length);
    }

    var newDefs = [];
    for (var url in refsToCreate) {
      var info = refsToCreate[url];
      var escapedRefName = info.refName.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      var defRegex = new RegExp('^\\s{0,3}\\[' + escapedRefName + '\\]:', 'mi');
      if (!defRegex.test(result)) {
        newDefs.push('[' + info.refName + ']: ' + info.rawUrl);
      }
    }

    if (newDefs.length > 0) {
      var trimmed = result.replace(/\s+$/, '');
      var lastOpenIdx = trimmed.lastIndexOf('<!--');
      var insertedDefs = false;
      if (lastOpenIdx >= 0) {
        var afterLastOpen = trimmed.slice(lastOpenIdx);
        var closingIdx = afterLastOpen.indexOf('-->');
        if (closingIdx >= 0 && afterLastOpen.slice(closingIdx + 3).trim() === '') {
          var before = trimmed.slice(0, lastOpenIdx).replace(/\s+$/, '');
          var after = trimmed.slice(lastOpenIdx);
          var lastLineBefore = before.slice(before.lastIndexOf('\n') + 1);
          var endsWithRefDef = /^\s{0,3}\[([^\]]+)\]:\s/.test(lastLineBefore);
          result = before + (endsWithRefDef ? '\n' : '\n\n') + newDefs.join('\n') + '\n' + after;
          insertedDefs = true;
        }
      }
      if (!insertedDefs) {
        var lastLine = trimmed.slice(trimmed.lastIndexOf('\n') + 1);
        var endsWithRefDef = /^\s{0,3}\[([^\]]+)\]:\s/.test(lastLine);
        result = trimmed + (endsWithRefDef ? '\n' : '\n\n') + newDefs.join('\n');
      }
    }

    return serializeWithFrontmatter(parsed.frontmatter, result);
  }

  (function patchSetValueAndSwitchToModeForLinkPrePost() {
    var proto = MarkdownWYSIWYG.prototype;
    var origSetValue = proto.setValue;
    var origSwitchToMode = proto.switchToMode;
    if (!origSetValue || !origSwitchToMode) return;
    proto.setValue = function (markdown, isInitialSetup) {
      var mdToUse = markdown;
      if (markdown) {
        var mdWithRefsExtracted = extractRefDefsFromCommentBlocks(markdown);
        this._liveWysiwygLinkData = preprocessMarkdownLinks(mdWithRefsExtracted);
        this._liveWysiwygListMarkerData = preprocessListMarkers(mdWithRefsExtracted);
        this._liveWysiwygTableSepData = preprocessTableSeparators(mdWithRefsExtracted);
        this._liveWysiwygCodeBlockData = preprocessCodeBlocks(mdWithRefsExtracted);
        this._liveWysiwygHrData = preprocessHorizontalRules(mdWithRefsExtracted);
        this._liveWysiwygInlineCodeData = preprocessInlineCode(mdWithRefsExtracted);
        mdToUse = mdWithRefsExtracted;
      }
      return origSetValue.apply(this, [mdToUse, isInitialSetup]);
    };
    proto.switchToMode = function (mode, isInitialSetup) {
      if (mode === 'wysiwyg' && !isInitialSetup && this.markdownArea && this.markdownArea.value) {
        var body = parseFrontmatter(this.markdownArea.value).body;
        var cleanBody = stripCursorSpanHtml(body);
        var bodyWithRefsExtracted = extractRefDefsFromCommentBlocks(cleanBody);
        var newLinkData = preprocessMarkdownLinks(bodyWithRefsExtracted);
        var newListData = preprocessListMarkers(cleanBody);
        this._liveWysiwygTableSepData = preprocessTableSeparators(cleanBody);
        this._liveWysiwygCodeBlockData = preprocessCodeBlocks(cleanBody);
        this._liveWysiwygHrData = preprocessHorizontalRules(cleanBody);
        this._liveWysiwygInlineCodeData = preprocessInlineCode(cleanBody);
        if (newLinkData.refDefinitions) {
          this._liveWysiwygLinkData = newLinkData;
        }
        if (newListData.listItems && newListData.listItems.length) {
          this._liveWysiwygListMarkerData = newListData;
        }
      }
      var result = origSwitchToMode.apply(this, arguments);
      if (mode === 'markdown') {
        var md = this.markdownArea.value;
        if (this._liveWysiwygRawHtmlData) {
          md = postprocessRawHtml(md, this._liveWysiwygRawHtmlData);
        }
        if (this._liveWysiwygLinkData) {
          md = postprocessMarkdownLinks(md, this._liveWysiwygLinkData);
        }
        if (this._liveWysiwygListMarkerData) {
          md = postprocessListMarkers(md, this._liveWysiwygListMarkerData);
        }
        if (this._liveWysiwygTableSepData) {
          md = postprocessTableSeparators(md, this._liveWysiwygTableSepData);
        }
        if (this._liveWysiwygCodeBlockData) {
          md = postprocessCodeBlocks(md, this._liveWysiwygCodeBlockData);
        }
        if (this._liveWysiwygHrData) {
          md = postprocessHorizontalRules(md, this._liveWysiwygHrData);
        }
        if (this._liveWysiwygInlineCodeData) {
          md = postprocessInlineCode(md, this._liveWysiwygInlineCodeData);
        }
        if (this._liveWysiwygLinkData) {
          md = dryDuplicateInlineLinks(md, this._liveWysiwygLinkData);
          md = collapseRedundantReferenceToShortcut(md);
          md = removeUnusedRefDefs(md);
          md = renumberRefDefs(md);
        }
        if (md !== this.markdownArea.value) {
          this.markdownArea.value = md;
          if (this.options && this.options.onUpdate) this.options.onUpdate(this.getValue());
        }
      }
      return result;
    };
  })();

  (function patchGetValueForListMarkers() {
    var proto = MarkdownWYSIWYG.prototype;
    var origGetValue = proto.getValue;
    if (!origGetValue) return;
    proto.getValue = function () {
      var raw = origGetValue.call(this);
      var parsed = parseFrontmatter(raw);
      if (parsed.frontmatter) {
        this._liveWysiwygFrontmatter = parsed.frontmatter;
      }
      var body = parsed.body;
      if (this._liveWysiwygRawHtmlData) {
        body = postprocessRawHtml(body, this._liveWysiwygRawHtmlData);
      }
      if (this._liveWysiwygLinkData) {
        body = postprocessMarkdownLinks(body, this._liveWysiwygLinkData);
      }
      if (this._liveWysiwygListMarkerData) {
        body = postprocessListMarkers(body, this._liveWysiwygListMarkerData);
      }
      if (this._liveWysiwygTableSepData) {
        body = postprocessTableSeparators(body, this._liveWysiwygTableSepData);
      }
      if (this._liveWysiwygCodeBlockData) {
        body = postprocessCodeBlocks(body, this._liveWysiwygCodeBlockData);
      }
      if (this._liveWysiwygHrData) {
        body = postprocessHorizontalRules(body, this._liveWysiwygHrData);
      }
      if (this._liveWysiwygInlineCodeData) {
        body = postprocessInlineCode(body, this._liveWysiwygInlineCodeData);
      }
      if (this._liveWysiwygLinkData) {
        body = dryDuplicateInlineLinks(body, this._liveWysiwygLinkData);
        body = collapseRedundantReferenceToShortcut(body);
        body = removeUnusedRefDefs(body);
        body = renumberRefDefs(body);
      }
      body = stripCursorSpanHtml(body).replace(CURSOR_UNICODE_RE, '');
      return body;
    };
  })();

  var CURSOR_MARKER = '\u200C\u200C\u200C\u200C\u200C\u200C';
  var CURSOR_MARKER_RE = /\u200C\u200C\u200C\u200C\u200C\u200C/g;
  var CURSOR_MARKER_END = '\u200D\u200D\u200D\u200D\u200D\u200D';
  var CURSOR_MARKER_END_RE = /\u200D\u200D\u200D\u200D\u200D\u200D/g;
  var CURSOR_SPAN_ATTR = 'data-live-wysiwyg-cursor';
  var CURSOR_SPAN_ATTR_END = 'data-live-wysiwyg-cursor-end';
  var CURSOR_PLACEHOLDER = 'LIVEWYSIWYG_CURSOR_9X7K2';
  var CURSOR_PLACEHOLDER_END = 'LIVEWYSIWYG_CURSOR_END_9X7K2';
  var lastWysiwygSemanticSelection = null;

  (function patchMarkdownToHtmlForCursorMarker() {
    var proto = MarkdownWYSIWYG.prototype;
    var orig = proto._markdownToHtml;
    if (!orig) return;
    var spanPattern = new RegExp('<span\\s+' + CURSOR_SPAN_ATTR.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*></span>', 'g');
    var spanEndPattern = new RegExp('<span\\s+' + CURSOR_SPAN_ATTR_END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*></span>', 'g');
    proto._markdownToHtml = function (markdown) {
      var s = (markdown || '').replace(spanPattern, CURSOR_PLACEHOLDER).replace(spanEndPattern, CURSOR_PLACEHOLDER_END);
      var html = orig.call(this, s);
      return (html || '').split(CURSOR_PLACEHOLDER).join(CURSOR_MARKER).split(CURSOR_PLACEHOLDER_END).join(CURSOR_MARKER_END);
    };
  })();

  function insertTextNodeAt(container, offset, textNode) {
    if (container.nodeType === 3) {
      var next = container.splitText(offset);
      container.parentNode.insertBefore(textNode, next);
    } else {
      var ref = container.childNodes[offset] || null;
      container.insertBefore(textNode, ref);
    }
  }

  function injectMarkerAtCaretInEditable(editable) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return false;
    var range = sel.getRangeAt(0);
    if (!editable.contains(range.commonAncestorContainer)) return false;
    if (lastWysiwygSemanticSelection) {
      var startParent = range.startContainer;
      if (startParent.nodeType === 3) startParent = startParent.parentNode;
      var currentPrimary = startParent && startParent.className ? startParent.className.split(/\s+/)[0] : '';
      var expectedPrimary = lastWysiwygSemanticSelection.start.parentClass ? lastWysiwygSemanticSelection.start.parentClass.split(/\s+/)[0] : '';
      if (currentPrimary !== expectedPrimary && expectedPrimary) {
        var restored = restoreSelectionFromSemantic(editable, lastWysiwygSemanticSelection);
        if (restored) {
          sel = window.getSelection();
          if (sel && sel.rangeCount > 0) {
            range = sel.getRangeAt(0);
          }
        }
      }
      lastWysiwygSemanticSelection = null;
    }
    var collapsed = range.collapsed;
    try {
      if (collapsed) {
        var textNode = document.createTextNode(CURSOR_MARKER);
        range.collapse(true);
        range.insertNode(textNode);
      } else {
        var startContainer = range.startContainer;
        var startOffset = range.startOffset;
        var endContainer = range.endContainer;
        var endOffset = range.endOffset;
        insertTextNodeAt(endContainer, endOffset, document.createTextNode(CURSOR_MARKER_END));
        insertTextNodeAt(startContainer, startOffset, document.createTextNode(CURSOR_MARKER));
      }
    } catch (e) {
      if (!collapsed) {
        try {
          range.collapse(true);
          range.insertNode(document.createTextNode(CURSOR_MARKER));
        } catch (e2) {
          console.warn('live-wysiwyg: could not inject selection marker', e2);
        }
      }
    }
    return true;
  }

  function getCaretOffsetInEditable(editable) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return 0;
    var range = sel.getRangeAt(0);
    if (!editable.contains(range.commonAncestorContainer)) return 0;
    var preCaretRange = range.cloneRange();
    preCaretRange.selectNodeContents(editable);
    preCaretRange.setEnd(range.startContainer, range.startOffset);
    return preCaretRange.toString().length;
  }

  function getTextOffsetOfMarkerInEditable(editable) {
    var walker = document.createTreeWalker(editable, NodeFilter.SHOW_TEXT, null, false);
    var pos = 0;
    var node;
    while ((node = walker.nextNode())) {
      var idx = node.textContent.indexOf(CURSOR_MARKER);
      if (idx >= 0) return pos + idx;
      pos += node.textContent.length;
    }
    return -1;
  }

  function stripCursorMarkersFromDOM(element) {
    var walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
    var node;
    var toUpdate = [];
    while ((node = walker.nextNode())) {
      if (node.nodeValue.indexOf(CURSOR_MARKER) >= 0 || node.nodeValue.indexOf(CURSOR_MARKER_END) >= 0) {
        toUpdate.push(node);
      }
    }
    for (var i = 0; i < toUpdate.length; i++) {
      toUpdate[i].nodeValue = toUpdate[i].nodeValue.replace(CURSOR_MARKER_RE, '').replace(CURSOR_MARKER_END_RE, '');
    }
    var pres = element.querySelectorAll('pre[data-title], pre[data-lang]');
    for (var j = 0; j < pres.length; j++) {
      var attrNames = ['data-title', 'data-lang'];
      for (var k = 0; k < attrNames.length; k++) {
        var val = pres[j].getAttribute(attrNames[k]);
        if (val && (val.indexOf(CURSOR_MARKER) >= 0 || val.indexOf(CURSOR_MARKER_END) >= 0)) {
          pres[j].setAttribute(attrNames[k], val.replace(CURSOR_MARKER_RE, '').replace(CURSOR_MARKER_END_RE, ''));
        }
      }
    }
  }

  function findAndStripCursorMarkerPositions(editable) {
    var walker = document.createTreeWalker(editable, NodeFilter.SHOW_TEXT, null, false);
    var node;
    var startInfo = null, endInfo = null;
    while ((node = walker.nextNode())) {
      var text = node.textContent;
      if (!startInfo) {
        var is = text.indexOf(CURSOR_MARKER);
        if (is >= 0) startInfo = { node: node, idx: is };
      }
      if (!endInfo) {
        var ie = text.indexOf(CURSOR_MARKER_END);
        if (ie >= 0) endInfo = { node: node, idx: ie };
      }
      if (startInfo && endInfo) break;
    }
    if (!startInfo) return null;
    var sameNode = endInfo && startInfo.node === endInfo.node;
    var startOffset = startInfo.idx;
    var endNode, endOffset, hasSelection;
    if (endInfo) {
      endNode = endInfo.node;
      endOffset = sameNode ? endInfo.idx - CURSOR_MARKER.length : endInfo.idx;
      hasSelection = sameNode ? endOffset > startOffset : true;
    } else {
      endNode = startInfo.node;
      endOffset = startInfo.idx;
      hasSelection = false;
    }
    stripCursorMarkersFromDOM(editable);
    return {
      startNode: startInfo.node, startOffset: startOffset,
      endNode: endNode, endOffset: endOffset,
      hasSelection: hasSelection
    };
  }

  function getTextOffsetsOfMarkersInEditable(editable) {
    var walker = document.createTreeWalker(editable, NodeFilter.SHOW_TEXT, null, false);
    var pos = 0;
    var node;
    var startOffset = -1;
    var endOffset = -1;
    while ((node = walker.nextNode())) {
      var text = node.textContent;
      var idxStart = text.indexOf(CURSOR_MARKER);
      var idxEnd = text.indexOf(CURSOR_MARKER_END);
      if (idxStart >= 0) startOffset = pos + idxStart;
      if (idxEnd >= 0) endOffset = pos + idxEnd;
      pos += text.length;
    }
    return { start: startOffset, end: endOffset };
  }

  function getBlockIndexForLine(md, lineIdx) {
    var lines = md.split('\n');
    var blockIdx = -1;
    var inBlock = false;
    for (var i = 0; i <= Math.min(lineIdx, lines.length - 1); i++) {
      if (lines[i].trim() === '') {
        inBlock = false;
      } else if (!inBlock) {
        blockIdx++;
        inBlock = true;
      }
    }
    return Math.max(0, blockIdx);
  }

  function findCursorSpanAndSetCaret(editable) {
    var span = editable.querySelector('[' + CURSOR_SPAN_ATTR + ']');
    if (!span) return false;
    var range = document.createRange();
    range.setStartBefore(span);
    range.collapse(true);
    var sel = window.getSelection();
    if (sel) {
      sel.removeAllRanges();
      sel.addRange(range);
    }
    span.parentNode.removeChild(span);
    return true;
  }

  function setCaretInEditable(editable, offset) {
    setSelectionInEditable(editable, offset, offset);
  }

  function setSelectionInEditable(editable, startOffset, endOffset) {
    var sel = window.getSelection();
    if (!sel) return;
    var range = document.createRange();
    var walker = document.createTreeWalker(editable, NodeFilter.SHOW_TEXT, null, false);
    var pos = 0;
    var startNode, startNodeOffset, endNode, endNodeOffset;
    var node;
    while ((node = walker.nextNode())) {
      var len = node.textContent.length;
      if (startNode === undefined && pos + len >= startOffset) {
        startNode = node;
        startNodeOffset = startOffset - pos;
      }
      if (endNode === undefined && pos + len >= endOffset) {
        endNode = node;
        endNodeOffset = endOffset - pos;
        break;
      }
      pos += len;
    }
    if (startNode && endNode) {
      range.setStart(startNode, startNodeOffset);
      range.setEnd(endNode, endNodeOffset);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }

  function focusCursorAtDocStart(editable) {
    var first = editable.firstElementChild;
    if (first && /^H[1-6]$/.test(first.nodeName)) {
      var walker = document.createTreeWalker(first, NodeFilter.SHOW_TEXT, null, false);
      var textNode = walker.nextNode();
      if (textNode) {
        var stripMarkers = /[\u200B\u200C\u200D\uFEFF]/g;
        var offset = 0;
        var raw = textNode.textContent || '';
        while (offset < raw.length && stripMarkers.test(raw[offset])) { offset++; stripMarkers.lastIndex = 0; }
        var range = document.createRange();
        range.setStart(textNode, offset);
        range.collapse(true);
        var sel = window.getSelection();
        if (sel) { sel.removeAllRanges(); sel.addRange(range); }
        return;
      }
    }
    setSelectionInEditable(editable, 0, 0);
  }

  function captureSemanticSelection(editable) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return null;
    var range = sel.getRangeAt(0);
    if (!editable.contains(range.commonAncestorContainer)) return null;
    function describeEndpoint(container, offset) {
      var parent = container.nodeType === 3 ? container.parentNode : container;
      var cls = (parent && parent.className) ? String(parent.className) : '';
      var tag = parent ? parent.nodeName : '';
      var parentText = parent ? parent.textContent : '';
      var localOffset = offset;
      if (container.nodeType === 3 && parent && parent !== container) {
        var w = document.createTreeWalker(parent, NodeFilter.SHOW_TEXT, null, false);
        var n, pos = 0;
        while ((n = w.nextNode())) {
          if (n === container) { localOffset = pos + offset; break; }
          pos += n.textContent.length;
        }
      }
      var nthOfClass = 0;
      if (cls && parent.parentNode) {
        var sibs = parent.parentNode.children;
        for (var i = 0; i < sibs.length; i++) {
          if (sibs[i] === parent) break;
          if (sibs[i].className === cls) nthOfClass++;
        }
      }
      var nested = false;
      var anc = parent;
      while (anc && anc !== editable) {
        if (anc.getAttribute && anc.getAttribute('contenteditable') === 'true') {
          nested = true;
          break;
        }
        anc = anc.parentNode;
      }
      return {
        parentClass: cls, parentTag: tag, parentText: parentText,
        localOffset: localOffset, nthOfClass: nthOfClass, nestedEditable: nested
      };
    }
    var startD = describeEndpoint(range.startContainer, range.startOffset);
    var endD = range.collapsed ? startD : describeEndpoint(range.endContainer, range.endOffset);
    return { selectedText: range.toString(), collapsed: range.collapsed, start: startD, end: endD };
  }

  function restoreSelectionFromSemantic(editable, sem) {
    if (!sem || !sem.start) return false;
    function findEl(desc) {
      if (!desc.parentClass) return null;
      var primary = desc.parentClass.split(/\s+/)[0];
      if (!primary) return null;
      var elems = editable.getElementsByClassName(primary);
      for (var i = 0; i < elems.length; i++) {
        if (elems[i].textContent === desc.parentText) return elems[i];
      }
      if (elems.length > desc.nthOfClass) return elems[desc.nthOfClass];
      return elems.length > 0 ? elems[0] : null;
    }
    function findTextAt(parent, targetOffset) {
      var w = document.createTreeWalker(parent, NodeFilter.SHOW_TEXT, null, false);
      var n, pos = 0, last = null;
      while ((n = w.nextNode())) {
        last = n;
        var len = n.textContent.length;
        if (pos + len >= targetOffset) return { node: n, offset: Math.min(targetOffset - pos, len) };
        pos += len;
      }
      if (last) return { node: last, offset: last.textContent.length };
      return null;
    }
    var startEl = findEl(sem.start);
    if (!startEl) return false;
    var endEl = sem.collapsed ? startEl : (findEl(sem.end) || startEl);
    var si = findTextAt(startEl, sem.start.localOffset);
    if (!si) return false;
    var ei = sem.collapsed ? si : (findTextAt(endEl, sem.end.localOffset) || si);
    try {
      var range = document.createRange();
      range.setStart(si.node, si.offset);
      range.setEnd(ei.node, ei.offset);
      var sel = window.getSelection();
      if (!sel) return false;
      sel.removeAllRanges();
      sel.addRange(range);
      if (sem.start.nestedEditable) {
        var anc = si.node.parentNode;
        while (anc && anc !== editable) {
          if (anc.getAttribute && anc.getAttribute('contenteditable') === 'true') {
            anc.focus();
            sel = window.getSelection();
            if (sel) { sel.removeAllRanges(); sel.addRange(range); }
            break;
          }
          anc = anc.parentNode;
        }
      }
      return true;
    } catch (e) {
      return false;
    }
  }

  function findTextNodeAtOffset(editable, targetOffset) {
    var walker = document.createTreeWalker(editable, NodeFilter.SHOW_TEXT, null, false);
    var pos = 0;
    var node;
    while ((node = walker.nextNode())) {
      var len = node.textContent.length;
      if (pos + len >= targetOffset) {
        return { node: node, offset: Math.min(targetOffset - pos, len) };
      }
      pos += len;
    }
    if (node) return { node: node, offset: node.textContent.length };
    return null;
  }

  function findNestedContenteditable(node, boundary) {
    var anc = node.nodeType === 3 ? node.parentNode : node;
    while (anc && anc !== boundary) {
      if (anc.getAttribute && anc.getAttribute('contenteditable') === 'true') {
        return anc;
      }
      anc = anc.parentNode;
    }
    return null;
  }

  function installSemanticClearListeners(editable) {
    if (editable._semanticClearInstalled) return;
    editable._semanticClearInstalled = true;
    var handler = function () {
      lastWysiwygSemanticSelection = null;
    };
    editable.addEventListener('mousedown', handler);
    editable.addEventListener('keydown', handler);
  }

  function restoreScrollPosition(container, scrollTop) {
    if (container && typeof scrollTop === 'number') {
      container.scrollTop = Math.min(scrollTop, Math.max(0, container.scrollHeight - container.clientHeight));
    }
  }

  function findSelectedTextInContent(content, selectedText, contextBefore, contextAfter) {
    if (!content || !selectedText) return null;
    var matchLen = selectedText.length;
    var norm = selectedText.replace(/\s+/g, ' ').trim();
    var searchTexts = norm && norm !== selectedText ? [selectedText, norm] : [selectedText];

    function tryContextMatch(ctxBefore, ctxAfter) {
      if (!ctxBefore && !ctxAfter) return null;
      var needle = (ctxBefore || '') + selectedText + (ctxAfter || '');
      var idx = content.indexOf(needle);
      if (idx >= 0) return { start: idx + (ctxBefore || '').length, end: idx + (ctxBefore || '').length + matchLen };
      if (norm && norm !== selectedText) {
        needle = (ctxBefore || '') + norm + (ctxAfter || '');
        idx = content.indexOf(needle);
        if (idx >= 0) return { start: idx + (ctxBefore || '').length, end: idx + (ctxBefore || '').length + norm.length };
      }
      return null;
    }

    if (contextBefore || contextAfter) {
      var pos = tryContextMatch(contextBefore, contextAfter);
      if (pos) return pos;
      pos = tryContextMatch(contextBefore, null);
      if (pos) return pos;
      pos = tryContextMatch(null, contextAfter);
      if (pos) return pos;
      if (contextBefore && contextBefore.length > 20) {
        pos = tryContextMatch(contextBefore.slice(-20), null);
        if (pos) return pos;
      }
      if (contextAfter && contextAfter.length > 20) {
        pos = tryContextMatch(null, contextAfter.slice(0, 20));
        if (pos) return pos;
      }
    }

    var allMatches = [];
    var idx = -1;
    while ((idx = content.indexOf(selectedText, idx + 1)) >= 0) allMatches.push({ idx: idx, len: selectedText.length });
    if (norm && norm !== selectedText) {
      idx = -1;
      while ((idx = content.indexOf(norm, idx + 1)) >= 0) allMatches.push({ idx: idx, len: norm.length });
    }
    if (allMatches.length === 0) return null;
    if (allMatches.length === 1) {
      var m = allMatches[0];
      return { start: m.idx, end: m.idx + m.len };
    }

    var best = null;
    var bestScore = -1;
    var trimCtxBefore = contextBefore ? contextBefore.replace(/\s+$/, '') : '';
    var trimCtxAfter = contextAfter ? contextAfter.replace(/^\s+/, '') : '';
    for (var i = 0; i < allMatches.length; i++) {
      var start = allMatches[i].idx;
      var len = allMatches[i].len;
      var before = trimCtxBefore ? content.substring(Math.max(0, start - CONTEXT_LEN - 1), start).replace(/\s+$/, '') : '';
      var after = trimCtxAfter ? content.substring(start + len, Math.min(content.length, start + len + CONTEXT_LEN + 1)).replace(/^\s+/, '') : '';
      var score = 0;
      if (trimCtxBefore && before) {
        var overlap = Math.min(trimCtxBefore.length, before.length);
        for (var j = 1; j <= overlap; j++) {
          if (trimCtxBefore.slice(-j) === before.slice(-j)) score += j;
        }
      }
      if (trimCtxAfter && after) {
        overlap = Math.min(trimCtxAfter.length, after.length);
        for (var k = 1; k <= overlap; k++) {
          if (trimCtxAfter.slice(0, k) === after.slice(0, k)) score += k;
        }
      }
      if (score > bestScore) {
        bestScore = score;
        best = { start: start, end: start + len };
      }
    }
    return best || { start: allMatches[0].idx, end: allMatches[0].idx + allMatches[0].len };
  }

  function findSelectedTextInMarkdown(markdown, selectedText, contextBefore, contextAfter) {
    return findSelectedTextInContent(markdown, selectedText, contextBefore, contextAfter);
  }

  function emojiToShortcode(emoji) {
    var map = typeof liveWysiwygEmojiMap !== 'undefined' ? liveWysiwygEmojiMap : {};
    for (var key in map) {
      if (map[key] === emoji) return ':' + key + ':';
    }
    return null;
  }

  function replaceEmojiCharsWithShortcodes(text) {
    var map = typeof liveWysiwygEmojiMap !== 'undefined' ? liveWysiwygEmojiMap : {};
    var result = text;
    for (var key in map) {
      if (map.hasOwnProperty(key) && result.indexOf(map[key]) >= 0) {
        result = result.split(map[key]).join(':' + key + ':');
      }
    }
    return result;
  }

  // applyPendingReadModeSelection logic is now unified into
  // readonly_to_edit_mode_text_selection (pseudo-markdown first, then
  // direct/normalized search, then WYSIWYG DOM fallbacks).

  // ---- Read-only to edit-mode selection heuristics ----

  function extractCodeText(codeEl) {
    var result = '';
    (function walkCode(node) {
      if (node.nodeType === 3) {
        result += node.textContent;
        return;
      }
      if (node.nodeType !== 1) return;
      if (node.nodeName === 'SCRIPT' || node.nodeName === 'STYLE') return;
      if (node.nodeName === 'BUTTON') return;
      if (node.classList && (
        node.classList.contains('md-annotation') ||
        node.classList.contains('md-clipboard') ||
        node.classList.contains('md-code-copy__button') ||
        node.classList.contains('linenos') ||
        node.classList.contains('linenodiv')
      )) return;
      for (var c = node.firstChild; c; c = c.nextSibling) walkCode(c);
    })(codeEl);
    return result;
  }

  function buildPseudoMarkdown(root) {
    var md = '';
    var hashTable = {};
    var hid = 0;
    var listStack = [];
    var olCounters = [];

    function ensureTrailingNewlines(n) {
      if (md.length === 0 && n > 0) return;
      var trailing = 0;
      for (var k = md.length - 1; k >= 0 && md[k] === '\n'; k--) trailing++;
      while (trailing < n) { md += '\n'; trailing++; }
    }

    function isBlockTag(t) {
      return /^(P|DIV|H[1-6]|LI|TR|HR|BLOCKQUOTE|PRE|TABLE|THEAD|TBODY|UL|OL|DL|DT|DD|DETAILS|SUMMARY|SECTION|HEADER|FOOTER|FIGURE|FIGCAPTION)$/.test(t);
    }

    function walk(node) {
      if (node.nodeType === 3) {
        var t = node.textContent;
        if (/^\s+$/.test(t) && node.parentNode) {
          var prev = node.previousSibling;
          var next = node.nextSibling;
          if ((prev && prev.nodeType === 1 && isBlockTag(prev.nodeName)) ||
              (next && next.nodeType === 1 && isBlockTag(next.nodeName))) return;
        }
        md += t;
        return;
      }
      if (node.nodeType !== 1) return;

      var tag = node.nodeName;
      if (tag === 'SCRIPT' || tag === 'STYLE') return;
      if (node.classList && (
        node.classList.contains('live-edit-controls') ||
        node.classList.contains('live-wysiwyg-selection-edit-popup') ||
        node.classList.contains('live-edit-source') ||
        node.classList.contains('live-edit-wysiwyg-wrapper') ||
        node.classList.contains('md-wysiwyg-editor-wrapper')
      )) return;
      if (tag === 'A' && node.classList && node.classList.contains('headerlink')) return;
      if (tag === 'TD' && node.classList && node.classList.contains('linenos')) return;
      if (tag === 'TH' && node.classList && node.classList.contains('filename')) return;
      if (tag === 'BUTTON' && node.classList && (node.classList.contains('md-clipboard') || node.classList.contains('md-code-copy__button'))) return;
      if (node.classList && node.classList.contains('md-annotation')) return;

      if (/^H([1-6])$/.test(tag)) {
        var level = parseInt(tag.charAt(1));
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        for (var h = 0; h < level; h++) md += '#';
        md += ' ';
        walkChildren(node);
        ensureTrailingNewlines(2);
        return;
      }

      if (tag === 'P') {
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        walkChildren(node);
        ensureTrailingNewlines(2);
        return;
      }

      if (tag === 'STRONG' || tag === 'B') {
        md += '**';
        walkChildren(node);
        md += '**';
        return;
      }

      if (tag === 'EM' || tag === 'I') {
        md += '*';
        walkChildren(node);
        md += '*';
        return;
      }

      if (tag === 'CODE') {
        var inPre = false;
        var p = node.parentNode;
        while (p) { if (p.nodeName === 'PRE') { inPre = true; break; } p = p.parentNode; }
        if (!inPre) {
          var inner = (node.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
          if (inner.indexOf('`') >= 0) {
            md += '`` ';
            walkChildren(node);
            md += ' ``';
          } else {
          md += '`';
          walkChildren(node);
          md += '`';
          }
          return;
        }
      }

      if (tag === 'IMG') {
        var sc = node.getAttribute('data-emoji-shortcode');
        var title = node.getAttribute('title') || '';
        var alt = node.alt || '';
        var key = '_h' + (hid++);
        var shortcode = null;
        if (sc) {
          shortcode = ':' + sc + ':';
        } else if (title && /^:[a-z0-9_+-]+:$/.test(title)) {
          shortcode = title;
        }
        hashTable[key] = { kind: sc ? 'emoji' : 'image', alt: alt, shortcode: shortcode };
        md += shortcode || alt;
        return;
      }

      if (tag === 'BR') { md += '\n'; return; }

      if (tag === 'UL') {
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        listStack.push('ul');
        walkChildren(node);
        listStack.pop();
        ensureTrailingNewlines(2);
        return;
      }

      if (tag === 'OL') {
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        listStack.push('ol');
        olCounters.push(0);
        walkChildren(node);
        listStack.pop();
        olCounters.pop();
        ensureTrailingNewlines(2);
        return;
      }

      if (tag === 'LI') {
        if (md.length > 0 && md[md.length - 1] !== '\n') md += '\n';
        var curList = listStack.length > 0 ? listStack[listStack.length - 1] : 'ul';
        if (curList === 'ol') {
          var cnt = olCounters.length > 0 ? ++olCounters[olCounters.length - 1] : 1;
          md += cnt + '. ';
        } else {
          md += '- ';
        }
        walkChildren(node);
        if (md.length > 0 && md[md.length - 1] !== '\n') md += '\n';
        return;
      }

      if (tag === 'BLOCKQUOTE') {
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        md += '> ';
        walkChildren(node);
        ensureTrailingNewlines(2);
        return;
      }

      if (tag === 'PRE') {
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        var lang = '';
        var wrapper = node.parentNode;
        while (wrapper && wrapper !== root) {
          var cls = wrapper.className || '';
          var m = cls.match(/language-(\S+)/);
          if (m) { lang = m[1]; break; }
          wrapper = wrapper.parentNode;
        }
        md += '```' + lang + '\n';
        var codeEl = node.querySelector('code');
        if (codeEl) {
          md += extractCodeText(codeEl);
        } else {
          md += node.textContent;
        }
        if (md.length > 0 && md[md.length - 1] !== '\n') md += '\n';
        md += '```';
        ensureTrailingNewlines(2);
        return;
      }

      if (tag === 'DIV' && node.classList && node.classList.contains('admonition')) {
        var adType = null;
        var adTypes = ['note', 'warning', 'danger', 'tip', 'hint', 'important', 'caution', 'error', 'attention', 'abstract', 'info', 'success', 'question', 'failure', 'bug', 'example', 'quote'];
        for (var ati = 0; ati < adTypes.length; ati++) {
          if (node.classList.contains(adTypes[ati])) { adType = adTypes[ati]; break; }
        }
        if (adType) {
          ensureTrailingNewlines(md.length > 0 ? 2 : 0);
          var adPrefix = '!!! ' + adType;
          if (node.classList.contains('inline')) adPrefix += ' inline';
          if (node.classList.contains('end')) adPrefix += ' end';
          var adTitleEl = null;
          for (var tc = node.firstChild; tc; tc = tc.nextSibling) {
            if (tc.nodeType === 1 && tc.classList && tc.classList.contains('admonition-title')) { adTitleEl = tc; break; }
          }
          if (node.hasAttribute('data-hide-title')) {
            adPrefix += ' ""';
          } else if (adTitleEl) {
            var adTitleText = adTitleEl.textContent.replace(/\u00b6/g, '').trim();
            var adDefaultTitle = adType.charAt(0).toUpperCase() + adType.slice(1);
            if (adTitleText && adTitleText !== adDefaultTitle) adPrefix += ' "' + adTitleText + '"';
          }
          md += adPrefix + '\n';
          var savedMdLen = md.length;
          for (var ac = node.firstChild; ac; ac = ac.nextSibling) {
            if (ac === adTitleEl) continue;
            if (ac.nodeType === 1 && ac.classList && ac.classList.contains('md-admonition-settings-btn')) continue;
            walk(ac);
          }
          var bodyContent = md.slice(savedMdLen);
          md = md.slice(0, savedMdLen);
          var bodyLines = bodyContent.split('\n');
          for (var bli = 0; bli < bodyLines.length; bli++) {
            md += bodyLines[bli] ? '    ' + bodyLines[bli] : '';
            if (bli < bodyLines.length - 1) md += '\n';
          }
          ensureTrailingNewlines(2);
          return;
        }
      }

      if (tag === 'DETAILS' && node.classList) {
        var detType = null;
        var detTypes = ['note', 'warning', 'danger', 'tip', 'hint', 'important', 'caution', 'error', 'attention', 'abstract', 'info', 'success', 'question', 'failure', 'bug', 'example', 'quote'];
        for (var dti = 0; dti < detTypes.length; dti++) {
          if (node.classList.contains(detTypes[dti])) { detType = detTypes[dti]; break; }
        }
        if (detType) {
          ensureTrailingNewlines(md.length > 0 ? 2 : 0);
          var detIsExpanded = node.hasAttribute('open') && !node.hasAttribute('data-default-collapsed');
          var detPrefix = detIsExpanded ? '???+ ' + detType : '??? ' + detType;
          if (node.classList.contains('inline')) detPrefix += ' inline';
          if (node.classList.contains('end')) detPrefix += ' end';
          var summaryEl = null;
          for (var sc = node.firstChild; sc; sc = sc.nextSibling) {
            if (sc.nodeType === 1 && sc.nodeName === 'SUMMARY') { summaryEl = sc; break; }
          }
          if (summaryEl) {
            var summaryText = summaryEl.textContent.replace(/\u00b6/g, '').trim();
            var detDefaultTitle = detType.charAt(0).toUpperCase() + detType.slice(1);
            if (summaryText && summaryText !== detDefaultTitle) detPrefix += ' "' + summaryText + '"';
          }
          md += detPrefix + '\n';
          var savedMdLen2 = md.length;
          for (var dc = node.firstChild; dc; dc = dc.nextSibling) {
            if (dc === summaryEl) continue;
            if (dc.nodeType === 1 && dc.classList && dc.classList.contains('md-admonition-settings-btn')) continue;
            walk(dc);
          }
          var bodyContent2 = md.slice(savedMdLen2);
          md = md.slice(0, savedMdLen2);
          var bodyLines2 = bodyContent2.split('\n');
          for (var bli2 = 0; bli2 < bodyLines2.length; bli2++) {
            md += bodyLines2[bli2] ? '    ' + bodyLines2[bli2] : '';
            if (bli2 < bodyLines2.length - 1) md += '\n';
          }
          ensureTrailingNewlines(2);
          return;
        }
      }

      if (tag === 'HR') {
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        md += '---';
        ensureTrailingNewlines(2);
        return;
      }

      walkChildren(node);
    }

    function walkChildren(node) {
      for (var c = node.firstChild; c; c = c.nextSibling) walk(c);
    }

    walk(root);
    return { md: md, hashTable: hashTable };
  }

  function buildSearchable(text) {
    var out = '';
    var posMap = [];
    var i = 0;
    var len = text.length;
    var lastWasSpace = false;
    var inCodeFence = false;

    function atLineStart() { return i === 0 || text[i - 1] === '\n'; }

    function detectFence() {
      if (!atLineStart()) return false;
      var bcount = 0;
      var fi = i;
      while (fi < len && text[fi] === '`') { bcount++; fi++; }
      return bcount >= 3;
    }

    function skipFenceLine() {
      while (i < len && text[i] !== '\n') i++;
      if (i < len) i++;
    }

    while (i < len) {
      if (detectFence()) {
        if (inCodeFence) {
          inCodeFence = false;
          skipFenceLine();
          continue;
        } else {
          inCodeFence = true;
          skipFenceLine();
          continue;
        }
      }

      if (inCodeFence) {
        if (/\s/.test(text[i])) {
          if (!lastWasSpace && out.length > 0) {
            posMap.push(i);
            out += ' ';
            lastWasSpace = true;
          }
          i++;
          continue;
        }
        lastWasSpace = false;
        posMap.push(i);
        out += text[i];
        i++;
        continue;
      }

      if (atLineStart()) {
        var j = i;
        while (j < len && text[j] === '#') j++;
        if (j > i && j - i <= 6 && j < len && text[j] === ' ') {
          i = j + 1;
          continue;
        }
        while (i < len && text[i] === '>' && i + 1 < len && text[i + 1] === ' ') { i += 2; }
        if (i < len && (text[i] === '-' || text[i] === '+' || text[i] === '*') && i + 1 < len && text[i + 1] === ' ') {
          i += 2;
          continue;
        }
        if (i < len && /\d/.test(text[i])) {
          var k = i;
          while (k < len && /\d/.test(text[k])) k++;
          if (k > i && k < len && text[k] === '.' && k + 1 < len && text[k + 1] === ' ') {
            i = k + 2;
            continue;
          }
        }
        if (i + 3 < len && text[i] === ' ' && text[i + 1] === ' ' && (text[i + 2] === '-' || text[i + 2] === '+' || text[i + 2] === '*') && text[i + 3] === ' ') {
          i += 4;
          continue;
        }
        if (i + 3 < len && text[i] === ' ' && text[i + 1] === ' ' && /\d/.test(text[i + 2])) {
          var k2 = i + 2;
          while (k2 < len && /\d/.test(text[k2])) k2++;
          if (k2 > i + 2 && k2 < len && text[k2] === '.' && k2 + 1 < len && text[k2 + 1] === ' ') {
            i = k2 + 2;
            continue;
          }
        }
        if (i + 5 < len && text[i] === ' ' && text[i + 1] === ' ' && text[i + 2] === ' ' && text[i + 3] === ' ' && (text[i + 4] === '-' || text[i + 4] === '+' || text[i + 4] === '*') && text[i + 5] === ' ') {
          i += 6;
          continue;
        }
        if (i + 3 < len && text[i] === ' ' && text[i + 1] === ' ' && text[i + 2] === ' ' && text[i + 3] === ' ') {
          i += 4;
          continue;
        }
        if (i + 3 < len && text[i] === '!' && text[i + 1] === '!' && text[i + 2] === '!' && text[i + 3] === ' ') {
          while (i < len && text[i] !== '\n') i++;
          continue;
        }
        if (i + 3 < len && text[i] === '?' && text[i + 1] === '?' && text[i + 2] === '?' && (text[i + 3] === ' ' || (text[i + 3] === '+' && i + 4 < len && text[i + 4] === ' '))) {
          while (i < len && text[i] !== '\n') i++;
          continue;
        }
      }
      if (i + 3 < len && text[i] === '<' && text[i + 1] === '!' && text[i + 2] === '-' && text[i + 3] === '-') {
        i += 4;
        while (i + 2 < len && !(text[i] === '-' && text[i + 1] === '-' && text[i + 2] === '>')) i++;
        if (i + 2 < len) i += 3;
        continue;
      }
      if (text[i] === '`') { i++; continue; }
      if (text[i] === '*' && i + 1 < len && text[i + 1] === '*') { i += 2; continue; }
      if (/\s/.test(text[i])) {
        if (!lastWasSpace && out.length > 0) {
          posMap.push(i);
          out += ' ';
          lastWasSpace = true;
        }
        i++;
        continue;
      }
      lastWasSpace = false;
      posMap.push(i);
      out += text[i];
      i++;
    }
    while (out.length > 0 && out[out.length - 1] === ' ') {
      out = out.slice(0, -1);
      posMap.pop();
    }
    return { text: out, posMap: posMap };
  }

  function normalizeForSearch(text) {
    return text.replace(/\u00b6/g, '').replace(/\s+/g, ' ').trim();
  }

  function readonly_to_edit_mode_text_selection(editor) {
    if (!pendingReadModeSelection || !pendingReadModeSelection.selectedText) return false;
    var saved = {
      selectedText: pendingReadModeSelection.selectedText,
      contextBefore: pendingReadModeSelection.contextBefore || '',
      contextAfter: pendingReadModeSelection.contextAfter || '',
      pseudoMarkdown: pendingReadModeSelection.pseudoMarkdown || null
    };
    pendingReadModeSelection = null;

    var mdRaw = (editor.markdownArea && editor.markdownArea.value)
      ? editor.markdownArea.value
      : (editor.getValue ? editor.getValue() : '');
    var parsed = parseFrontmatter(mdRaw || '');
    var body = parsed.body || '';
    var frontmatterLen = (mdRaw || '').length - body.length;

    var normSel = normalizeForSearch(saved.selectedText);
    var normCtxBefore = normalizeForSearch(saved.contextBefore);
    var normCtxAfter = normalizeForSearch(saved.contextAfter);

    var pos = null;

    // Collect all candidate matches in the body (exact + emoji variants)
    var searchTexts = [saved.selectedText];
    var sc = emojiToShortcode(saved.selectedText);
    if (sc) searchTexts.push(sc);
    var withShortcodes = replaceEmojiCharsWithShortcodes(saved.selectedText);
    if (withShortcodes !== saved.selectedText) searchTexts.push(withShortcodes);
    var norm = saved.selectedText.replace(/\s+/g, ' ').trim();
    if (norm !== saved.selectedText) searchTexts.push(norm);

    var allBodyMatches = [];
    for (var ti = 0; ti < searchTexts.length; ti++) {
      var needle = searchTexts[ti];
      var idx = -1;
      while ((idx = body.indexOf(needle, idx + 1)) >= 0) {
        allBodyMatches.push({ start: idx, end: idx + needle.length });
      }
    }

    if (allBodyMatches.length === 1) {
      pos = allBodyMatches[0];
    } else if (allBodyMatches.length > 1) {
      // Determine the PM-favored body position (if pseudo-markdown available)
      var pmFavoredStart = -1;
      if (normSel && saved.pseudoMarkdown) {
        var pm = saved.pseudoMarkdown;
        var pmS = buildSearchable(pm.md);
        var pmMatch = findInSearchable(pmS, normSel, normCtxBefore, normCtxAfter);
        if (!pmMatch) {
          var normSelSC = normalizeForSearch(replaceEmojiCharsWithShortcodes(saved.selectedText));
          if (normSelSC !== normSel) pmMatch = findInSearchable(pmS, normSelSC, normCtxBefore, normCtxAfter);
        }
        if (pmMatch) {
          var pmCtxBefore = pm.md.slice(Math.max(0, pmMatch.start - CONTEXT_LEN), pmMatch.start);
          var pmCtxAfter = pm.md.slice(pmMatch.end, Math.min(pm.md.length, pmMatch.end + CONTEXT_LEN));
          var pmSubstr = pm.md.slice(pmMatch.start, pmMatch.end);
          var pmBodyPos = findSelectedTextInContent(body, pmSubstr, pmCtxBefore, pmCtxAfter);
          if (pmBodyPos) pmFavoredStart = pmBodyPos.start;
        }
      }

      // Score each body match with unified heuristics
      var best = null;
      var bestScore = -1;
      var trimCtxBefore = saved.contextBefore.replace(/\s+$/, '');
      var trimCtxAfter = saved.contextAfter.replace(/^\s+/, '');
      for (var bi = 0; bi < allBodyMatches.length; bi++) {
        var bm = allBodyMatches[bi];
        var score = 0;

        // Signal 1: PM agreement — strong boost when PM cross-reference
        // independently identifies this body position
        if (pmFavoredStart >= 0 && bm.start === pmFavoredStart) {
          score += 100000;
        }

        // Signal 2: Direct context scoring against body text
        if (trimCtxBefore) {
          var before = body.substring(Math.max(0, bm.start - trimCtxBefore.length - 1), bm.start).replace(/\s+$/, '');
          for (var j = 1; j <= Math.min(trimCtxBefore.length, before.length); j++) {
            if (trimCtxBefore.slice(-j) === before.slice(-j)) score += j;
          }
        }
        if (trimCtxAfter) {
          var after = body.substring(bm.end, Math.min(body.length, bm.end + trimCtxAfter.length + 1)).replace(/^\s+/, '');
          for (var k = 1; k <= Math.min(trimCtxAfter.length, after.length); k++) {
            if (trimCtxAfter.slice(0, k) === after.slice(0, k)) score += k;
          }
        }

        if (score > bestScore) { bestScore = score; best = bm; }
      }
      pos = best || allBodyMatches[0];
    }

    // Apply: markdown mode
    if (pos && editor.currentMode === 'markdown') {
      var ma = editor.markdownArea;
      if (!ma) return false;
      var selStart = pos.start + frontmatterLen;
      var selEnd = pos.end + frontmatterLen;
      var fullLen = ma.value.length;
      selStart = Math.min(selStart, fullLen);
      selEnd = Math.min(selEnd, fullLen);
      ma.focus();
      ma.setSelectionRange(selStart, selEnd);
      scrollToCenterCursor(ma, true, selStart, editor.markdownEditorContainer);
      return true;
    }

    // Apply: WYSIWYG mode via cursor markers
    var ea = editor.editableArea;
    if (!ea) return false;
    if (pos) {
      var spanMarker = '<span ' + CURSOR_SPAN_ATTR + '></span>';
      var spanMarkerEnd = '<span ' + CURSOR_SPAN_ATTR_END + '></span>';
      var markedBody = body.slice(0, pos.start) + spanMarker +
                       body.slice(pos.start, pos.end) + spanMarkerEnd +
                       body.slice(pos.end);
      ea.innerHTML = editor._markdownToHtml(markedBody);
      if (typeof populateRawHtmlBlocks === 'function') populateRawHtmlBlocks(ea);
      if (typeof enhanceCodeBlocks === 'function') enhanceCodeBlocks(ea);
      if (typeof enhanceChecklists === 'function') enhanceChecklists(ea);
      if (typeof enhanceAdmonitions === 'function') enhanceAdmonitions(ea);
      if (typeof enhanceImages === 'function') enhanceImages(ea);
      var mPos = findAndStripCursorMarkerPositions(ea);
      if (mPos) {
        ea.focus();
        var range = document.createRange();
        range.setStart(mPos.startNode, mPos.startOffset);
        range.setEnd(mPos.endNode, mPos.endOffset);
        var sel = window.getSelection();
        if (sel) { sel.removeAllRanges(); sel.addRange(range); }
        requestAnimationFrame(function () { scrollToCenterCursor(ea, false); });
        return true;
      }
    }

    // Fallback: emoji image match in WYSIWYG
    var imgs = ea.querySelectorAll('img[data-emoji-shortcode]');
    for (var i = 0; i < imgs.length; i++) {
      if (imgs[i].alt === saved.selectedText) {
        var r = document.createRange();
        r.selectNode(imgs[i]);
        var sel2 = window.getSelection();
        sel2.removeAllRanges();
        sel2.addRange(r);
        ea.focus();
        requestAnimationFrame(function () { scrollToCenterCursor(ea, false); });
        return true;
      }
    }

    // Fallback: text search in rendered WYSIWYG DOM
    var fullText = '';
    var walker = document.createTreeWalker(ea, NodeFilter.SHOW_TEXT, null, false);
    var tNode;
    while ((tNode = walker.nextNode())) fullText += tNode.textContent;
    var pos3 = findSelectedTextInContent(fullText, saved.selectedText, saved.contextBefore, saved.contextAfter);
    if (pos3) {
      setSelectionInEditable(ea, pos3.start, pos3.end);
      ea.focus();
      requestAnimationFrame(function () { scrollToCenterCursor(ea, false); });
      return true;
    }
    return false;
  }

  function findInSearchable(searchable, normNeedle, normCtxBefore, normCtxAfter) {
    var allMatches = [];
    var startFrom = 0;
    while (true) {
      var idx = searchable.text.indexOf(normNeedle, startFrom);
      if (idx < 0) break;
      var endIdx = idx + normNeedle.length - 1;
      var oS = idx < searchable.posMap.length ? searchable.posMap[idx] : 0;
      var oE = endIdx < searchable.posMap.length ? searchable.posMap[endIdx] + 1 : searchable.posMap[searchable.posMap.length - 1] + 1;
      allMatches.push({ start: oS, end: oE, sIdx: idx });
      startFrom = idx + 1;
    }
    if (allMatches.length === 0) return null;
    if (allMatches.length === 1) return allMatches[0];

    var best = null;
    var bestScore = -1;
    var trimmedCtxBefore = normCtxBefore ? normCtxBefore.replace(/\s+$/, '') : '';
    var trimmedCtxAfter = normCtxAfter ? normCtxAfter.replace(/^\s+/, '') : '';
    for (var i = 0; i < allMatches.length; i++) {
      var m = allMatches[i];
      var score = 0;
      if (trimmedCtxBefore) {
        var before = searchable.text.substring(Math.max(0, m.sIdx - trimmedCtxBefore.length - 1), m.sIdx).replace(/\s+$/, '');
        for (var j = 1; j <= Math.min(trimmedCtxBefore.length, before.length); j++) {
          if (trimmedCtxBefore.slice(-j) === before.slice(-j)) score += j;
        }
      }
      if (trimmedCtxAfter) {
        var mEnd = m.sIdx + normNeedle.length;
        var after = searchable.text.substring(mEnd, Math.min(searchable.text.length, mEnd + trimmedCtxAfter.length + 1)).replace(/^\s+/, '');
        for (var k = 1; k <= Math.min(trimmedCtxAfter.length, after.length); k++) {
          if (trimmedCtxAfter.slice(0, k) === after.slice(0, k)) score += k;
        }
      }
      if (score > bestScore) { bestScore = score; best = m; }
    }
    return best || allMatches[0];
  }

  function scrollToCenterCursor(container, isTextarea, selectionStart, scrollTarget) {
    if (!container) return;
    var scroller = scrollTarget || container;
    if (!isTextarea && isFocusModeActive && _focusOverlay) {
      var focusMain = _focusOverlay.querySelector('.live-wysiwyg-focus-main');
      if (focusMain) scroller = focusMain;
    }
    var clientHeight = scroller.clientHeight;
    var maxScroll = Math.max(0, scroller.scrollHeight - clientHeight);
    if (maxScroll <= 0) return;
    var cursorPixelPos;
    if (isTextarea && typeof selectionStart === 'number') {
      var mirror = document.createElement('div');
      var style = window.getComputedStyle(container);
      mirror.style.cssText = 'position:absolute;left:-9999px;visibility:hidden;white-space:pre-wrap;word-wrap:break-word;overflow:hidden;pointer-events:none;';
      mirror.style.font = style.font;
      mirror.style.fontSize = style.fontSize;
      mirror.style.fontFamily = style.fontFamily;
      mirror.style.lineHeight = style.lineHeight;
      mirror.style.padding = style.padding;
      mirror.style.width = container.clientWidth + 'px';
      mirror.style.border = style.border;
      mirror.style.boxSizing = style.boxSizing;
      mirror.textContent = container.value.substring(0, selectionStart);
      container.parentNode.appendChild(mirror);
      cursorPixelPos = mirror.offsetHeight;
      mirror.parentNode.removeChild(mirror);
    } else {
      var sel = window.getSelection();
      if (!sel || sel.rangeCount === 0) return;
      var range = sel.getRangeAt(0);
      if (!container.contains(range.commonAncestorContainer)) return;
      var cursorRect = range.getBoundingClientRect();
      var scrollerRect = scroller.getBoundingClientRect();
      cursorPixelPos = scroller.scrollTop + (cursorRect.top - scrollerRect.top);
    }
    var scrollFraction = isFocusModeActive ? (isTextarea ? 0.25 : 0.15) : 0.5;
    var targetScroll = cursorPixelPos - (clientHeight * scrollFraction);
    scroller.scrollTop = Math.max(0, Math.min(targetScroll, maxScroll));
  }

  function _smoothScrollTo(element, target, duration) {
    var start = element.scrollTop;
    var distance = target - start;
    if (Math.abs(distance) < 1) return;
    var startTime = null;
    function step(timestamp) {
      if (!startTime) startTime = timestamp;
      var elapsed = timestamp - startTime;
      var t = Math.min(elapsed / duration, 1);
      var ease = t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
      element.scrollTop = start + distance * ease;
      if (t < 1) requestAnimationFrame(step);
    }
    requestAnimationFrame(step);
  }

  (function patchSetValueAndGetValueForFrontmatter() {
    var proto = MarkdownWYSIWYG.prototype;
    var origSetValue = proto.setValue;
    var origGetValue = proto.getValue;
    var origSwitchToMode = proto.switchToMode;
    if (!origSetValue || !origGetValue || !origSwitchToMode) return;
    proto.setValue = function (markdown, isInitialSetup) {
      var parsed = parseFrontmatter(markdown || '');
      this._liveWysiwygFrontmatter = parsed.frontmatter;
      var ret = origSetValue.call(this, parsed.body, isInitialSetup);
      if (this.editableArea) {
        populateRawHtmlBlocks(this.editableArea);
        enhanceCodeBlocks(this.editableArea);
        enhanceChecklists(this.editableArea);
        enhanceAdmonitions(this.editableArea);
        enhanceImages(this.editableArea);
        if (lastWysiwygSemanticSelection && this.currentMode === 'wysiwyg' && !isInitialSetup) {
          restoreSelectionFromSemantic(this.editableArea, lastWysiwygSemanticSelection);
        }
      }
      return ret;
    };
    proto.getValue = function () {
      var body = origGetValue.call(this);
      return serializeWithFrontmatter(this._liveWysiwygFrontmatter, body);
    };
    proto.switchToMode = function (mode, isInitialSetup) {
      if (!isInitialSetup) _flushHistoryCapture();
      dismissImageSelection();
      dismissImageInsertDropdown();
      dismissImageGearDropdown();
      if (this.currentMode === mode && !isInitialSetup) {
        if (mode === 'markdown' && this.markdownArea) {
          var ss = this.markdownArea.selectionStart;
          var se = this.markdownArea.selectionEnd;
          var ta = this.markdownArea;
          requestAnimationFrame(function () { ta.focus(); ta.setSelectionRange(ss, se); });
        } else if (mode === 'wysiwyg' && this.editableArea) {
          this.editableArea.focus();
        }
        return;
      }
      var savedSelStart = this.markdownArea ? this.markdownArea.selectionStart : 0;
      var frontmatterLen = 0;
      if (mode === 'wysiwyg' && !isInitialSetup && this.markdownArea && this.markdownArea.value) {
        var fullLen = this.markdownArea.value.length;
        var parsed = parseFrontmatter(this.markdownArea.value);
        this._liveWysiwygFrontmatter = parsed.frontmatter;
        frontmatterLen = fullLen - (parsed.body || '').length;
        this.markdownArea.value = parsed.body;
        if (frontmatterLen > 0) {
          var adj = Math.max(0, Math.min(savedSelStart - frontmatterLen, parsed.body.length));
          this.markdownArea.setSelectionRange(adj, adj);
        }
      }
      var cursorInFrontmatter = false;
      if (frontmatterLen > 0) {
        var checkStart = capturedMarkdownSelection ? capturedMarkdownSelection.start : savedSelStart;
        cursorInFrontmatter = checkStart < frontmatterLen;
      }
      var cursorAtDocStart = false;
      var cursorBlockFallback = -1;
      var codeTitleSelection = null;
      var savedScroll = null;
      var markdownMarkerInserted = false;
      if (!isInitialSetup) {
        savedScroll = this.currentMode === 'wysiwyg'
          ? (this.editableArea ? this.editableArea.scrollTop : 0)
          : (this.markdownEditorContainer ? this.markdownEditorContainer.scrollTop : 0);
        if (this.currentMode === 'wysiwyg') {
          injectMarkerAtCaretInEditable(this.editableArea);
        } else if (cursorInFrontmatter) {
          capturedMarkdownSelection = null;
        } else {
          var mdVal = this.markdownArea.value;
          var selStart, selEnd;
          if (capturedMarkdownSelection) {
            selStart = capturedMarkdownSelection.start;
            selEnd = capturedMarkdownSelection.end;
            if (frontmatterLen > 0) {
              selStart = Math.max(0, selStart - frontmatterLen);
              selEnd = Math.max(0, selEnd - frontmatterLen);
            }
            selStart = Math.min(selStart, mdVal.length);
            selEnd = Math.min(selEnd, mdVal.length);
            capturedMarkdownSelection = null;
          } else {
            selStart = Math.min(this.markdownArea.selectionStart, mdVal.length);
            selEnd = Math.min(this.markdownArea.selectionEnd, mdVal.length);
          }
          var insertStart = selStart;
          var insertEnd = selEnd;
          if (insertStart === 0) {
            cursorAtDocStart = true;
          } else if (insertStart === insertEnd) {
            if (insertStart > 0 && mdVal.charAt(insertStart - 1) === '\n') {
              insertStart = insertStart - 1;
              insertEnd = insertEnd - 1;
            }
          } else {
            if (insertEnd > 0 && mdVal.charAt(insertEnd - 1) === '\n' && insertEnd > insertStart) {
              insertEnd = insertEnd - 1;
            }
          }
          if (!cursorAtDocStart) {
            var lines = mdVal.split('\n');
            var cursorLineIdx = mdVal.slice(0, selStart).split('\n').length - 1;
            var cursorLine = lines[cursorLineIdx] || '';
            if (/^(`{3,}|~{3,})/.test(cursorLine)) {
              var fenceTitleMatch = cursorLine.match(/title="([^"]*)"/);
              if (fenceTitleMatch) {
                var titleAttrStart = cursorLine.indexOf(fenceTitleMatch[0]) + 'title="'.length;
                var titleAttrEnd = titleAttrStart + fenceTitleMatch[1].length;
                var lineStartOffset = 0;
                for (var lk = 0; lk < cursorLineIdx; lk++) lineStartOffset += lines[lk].length + 1;
                var selStartInLine = selStart - lineStartOffset;
                var selEndInLine = selEnd - lineStartOffset;
                if (selStartInLine >= titleAttrStart && selEndInLine <= titleAttrEnd) {
                  var fenceCount = 0;
                  for (var fi = 0; fi < lines.length; fi++) {
                    if (fi === cursorLineIdx) break;
                    if (/^(`{3,}|~{3,})/.test(lines[fi])) {
                      var fch = lines[fi].match(/^(`{3,}|~{3,})/)[1];
                      fi++;
                      while (fi < lines.length && !lines[fi].match(new RegExp('^' + fch[0] + '{' + fch.length + ',}\\s*$'))) fi++;
                      fenceCount++;
                    }
                  }
                  codeTitleSelection = {
                    codeBlockIndex: fenceCount,
                    selStart: selStartInLine - titleAttrStart,
                    selEnd: selEndInLine - titleAttrStart,
                    titleText: fenceTitleMatch[1]
                  };
                }
              }
            }
          }
          if (!cursorAtDocStart && !codeTitleSelection) {
            var spanMarker = '<span ' + CURSOR_SPAN_ATTR + '></span>';
            var spanMarkerEnd = '<span ' + CURSOR_SPAN_ATTR_END + '></span>';
            var spanMarkerRe = new RegExp('<span\\s+' + CURSOR_SPAN_ATTR.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\\s*>\\s*</span>', 'gi');
            var spanMarkerEndRe = new RegExp('<span\\s+' + CURSOR_SPAN_ATTR_END.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\\s*>\\s*</span>', 'gi');
            var testMd;
            if (insertStart === insertEnd) {
              testMd = mdVal.slice(0, insertStart) + spanMarker + mdVal.slice(insertStart);
            } else {
              testMd = mdVal.slice(0, insertStart) + spanMarker + mdVal.slice(insertStart, insertEnd) + spanMarkerEnd + mdVal.slice(insertEnd);
            }
            var stripAllMarkers = function (s) {
              return (s || '').replace(CURSOR_MARKER_RE, '').replace(CURSOR_MARKER_END_RE, '').replace(spanMarkerRe, '').replace(spanMarkerEndRe, '');
            };
            var normHtml = function (s) { return stripAllMarkers(s).replace(/\s+/g, ' ').trim(); };
            var cleanHtml = normHtml(this._markdownToHtml(mdVal));
            var markerHtml = normHtml(this._markdownToHtml(testMd));
            if (markerHtml === cleanHtml) {
              this.markdownArea.value = testMd;
              markdownMarkerInserted = true;
            } else {
              var lines2 = mdVal.split('\n');
              var cursorLineIdx2 = mdVal.slice(0, selStart).split('\n').length - 1;
              var cursorLine2 = lines2[cursorLineIdx2] || '';
              if (/^\s*>\s*$/.test(cursorLine2) && cursorLineIdx2 > 0) {
                var prevIdx = cursorLineIdx2 - 1;
                while (prevIdx > 0 && /^\s*>\s*$/.test(lines2[prevIdx])) prevIdx--;
                var prevLineEnd = 0;
                for (var li = 0; li <= prevIdx; li++) prevLineEnd += lines2[li].length + 1;
                prevLineEnd -= 1;
                var retryMd = mdVal.slice(0, prevLineEnd) + spanMarker + mdVal.slice(prevLineEnd);
                var retryHtml = normHtml(this._markdownToHtml(retryMd));
                if (retryHtml === cleanHtml) {
                  this.markdownArea.value = retryMd;
                  markdownMarkerInserted = true;
                } else {
                  cursorBlockFallback = getBlockIndexForLine(mdVal, cursorLineIdx2);
                }
              } else if (/^(`{3,}|~{3,})/.test(cursorLine2)) {
                cursorBlockFallback = getBlockIndexForLine(mdVal, cursorLineIdx2);
              } else {
                cursorBlockFallback = getBlockIndexForLine(mdVal, cursorLineIdx2);
              }
            }
          }
        }
      }
      var result = origSwitchToMode.call(this, mode, isInitialSetup);
      if (mode === 'markdown') {
        capturedMarkdownSelection = null;
        if (this._liveWysiwygFrontmatter) {
          this.markdownArea.value = serializeWithFrontmatter(this._liveWysiwygFrontmatter, this.markdownArea.value);
          if (this._updateMarkdownLineNumbers) this._updateMarkdownLineNumbers();
        }
      }
      if (!isInitialSetup && savedScroll !== null) {
        if (mode === 'wysiwyg') {
          var editableArea = this.editableArea;
          populateRawHtmlBlocks(editableArea);
          enhanceCodeBlocks(editableArea);
          enhanceChecklists(editableArea);
          enhanceAdmonitions(editableArea);
          enhanceImages(editableArea);
          if (cursorInFrontmatter || cursorAtDocStart) {
            requestAnimationFrame(function () {
              editableArea.focus();
              focusCursorAtDocStart(editableArea);
              editableArea.scrollTop = 0;
            });
          } else if (codeTitleSelection) {
            var ctSel = codeTitleSelection;
            requestAnimationFrame(function () {
              var codeBlocks = editableArea.querySelectorAll('.md-code-block');
              var block = codeBlocks[ctSel.codeBlockIndex];
              var titleEl = block ? block.querySelector('.md-code-title') : null;
              if (!titleEl) {
                for (var ti = 0; ti < codeBlocks.length; ti++) {
                  var t = codeBlocks[ti].querySelector('.md-code-title');
                  if (t && t.textContent === ctSel.titleText) { titleEl = t; break; }
                }
              }
              if (titleEl) {
                titleEl.focus();
                var si = findTextNodeAtOffset(titleEl, ctSel.selStart);
                var ei = (ctSel.selStart === ctSel.selEnd) ? si : findTextNodeAtOffset(titleEl, ctSel.selEnd);
                if (si && ei) {
                  var range = document.createRange();
                  range.setStart(si.node, si.offset);
                  range.setEnd(ei.node, ei.offset);
                  var sel = window.getSelection();
                  if (sel) { sel.removeAllRanges(); sel.addRange(range); }
                }
              } else {
                editableArea.focus();
              }
              lastWysiwygSemanticSelection = captureSemanticSelection(editableArea);
              installSemanticClearListeners(editableArea);
              scrollToCenterCursor(editableArea, false);
            });
          } else if (cursorBlockFallback >= 0) {
            var blockIdx = cursorBlockFallback;
            requestAnimationFrame(function () {
              editableArea.focus();
              var blockEls = [];
              for (var c = editableArea.firstElementChild; c; c = c.nextElementSibling) {
                blockEls.push(c);
              }
              var target = blockEls[Math.min(blockIdx, blockEls.length - 1)];
              if (target) {
                var range = document.createRange();
                range.selectNodeContents(target);
                range.collapse(true);
                var sel = window.getSelection();
                if (sel) {
                  sel.removeAllRanges();
                  sel.addRange(range);
                }
              }
              scrollToCenterCursor(editableArea, false);
            });
          } else {
            var cursorSet = findCursorSpanAndSetCaret(editableArea);
            var markerPos = null;
            if (!cursorSet) {
              markerPos = findAndStripCursorMarkerPositions(editableArea);
              if (!markerPos && markdownMarkerInserted) {
                var leftover = editableArea.querySelectorAll('[' + CURSOR_SPAN_ATTR + '], [' + CURSOR_SPAN_ATTR_END + ']');
                for (var i = 0; i < leftover.length; i++) leftover[i].parentNode.removeChild(leftover[i]);
              }
            }
            requestAnimationFrame(function () {
              if (cursorSet) {
                editableArea.focus();
              } else if (markerPos) {
                var nested = findNestedContenteditable(markerPos.startNode, editableArea);
                if (nested) {
                  nested.focus();
                } else {
                  editableArea.focus();
                }
                var range = document.createRange();
                range.setStart(markerPos.startNode, markerPos.startOffset);
                range.setEnd(markerPos.endNode, markerPos.endOffset);
                var sel = window.getSelection();
                if (sel) {
                  sel.removeAllRanges();
                  sel.addRange(range);
                }
              }
              lastWysiwygSemanticSelection = captureSemanticSelection(editableArea);
              installSemanticClearListeners(editableArea);
              scrollToCenterCursor(editableArea, false);
            });
          }
        } else {
          var mdVal = this.markdownArea.value;
          var markerIdx = mdVal.indexOf(CURSOR_MARKER);
          var markerEndIdx = mdVal.indexOf(CURSOR_MARKER_END);
          if (markerIdx >= 0) {
            var selStart = markerIdx;
            var selEnd = markerIdx;
            if (markerEndIdx >= 0 && markerEndIdx > markerIdx) {
              selEnd = markerEndIdx;
            }
            var strippedMd = mdVal.replace(CURSOR_MARKER_RE, '').replace(CURSOR_MARKER_END_RE, '');
            var bqLines = strippedMd.split('\n');
            var bqOut = [];
            var bqi = 0;
            while (bqi < bqLines.length) {
              if (/^>/.test(bqLines[bqi])) {
                var bqBlk = [];
                while (bqi < bqLines.length && /^>/.test(bqLines[bqi])) { bqBlk.push(bqLines[bqi]); bqi++; }
                while (bqBlk.length > 0 && /^>/.test(bqBlk[bqBlk.length - 1]) && !bqBlk[bqBlk.length - 1].replace(/^>/, '').replace(/[\s\u00a0]/g, '')) bqBlk.pop();
                for (var bk = 0; bk < bqBlk.length; bk++) bqOut.push(bqBlk[bk]);
              } else { bqOut.push(bqLines[bqi]); bqi++; }
            }
            this.markdownArea.value = bqOut.join('\n');
            var len = this.markdownArea.value.length;
            if (markerEndIdx >= 0 && markerEndIdx > markerIdx) {
              selEnd = markerEndIdx - 6;
            }
            selStart = Math.min(selStart, len);
            selEnd = Math.min(Math.max(selEnd, selStart), len);
            var selText = this.markdownArea.value.substring(selStart, selEnd);
            var headingMatch = selText.match(/^(\s*#{1,6}\s+)/);
            if (headingMatch) {
              selStart += headingMatch[1].length;
            }
            selStart = Math.min(selStart, len);
            selEnd = Math.min(Math.max(selEnd, selStart), len);
            this.markdownArea.setSelectionRange(selStart, selEnd);
            if (this._updateMarkdownLineNumbers) this._updateMarkdownLineNumbers();
          }
          scrollToCenterCursor(this.markdownArea, true, this.markdownArea.selectionStart, this.markdownEditorContainer);
        }
      } else if (mode === 'wysiwyg' && this.editableArea) {
        populateRawHtmlBlocks(this.editableArea);
        enhanceCodeBlocks(this.editableArea);
        enhanceChecklists(this.editableArea);
        enhanceAdmonitions(this.editableArea);
        enhanceImages(this.editableArea);
      }
      return result;
    };
  })();

  var _LS_EDITOR_KEY = 'liveWysiwygEditorEnabled';

  function getEditorState() {
    var val = _getSetting(_LS_EDITOR_KEY);
    if (val == null) return null;
    if (typeof val === 'object') return val;
    var parts = String(val).split(':');
    var enabled = parts[0] === '1' || parts[0] === 'true';
    var mode = (parts[1] === 'wysiwyg' || parts[1] === 'markdown') ? parts[1] : 'wysiwyg';
    return { enabled: enabled, mode: mode };
  }

  function setEditorState(enabled, mode) {
    var modeVal = (mode === 'markdown' || mode === 'wysiwyg') ? mode : 'wysiwyg';
    _setSetting(_LS_EDITOR_KEY, { enabled: !!enabled, mode: modeVal });
  }

  function isEditorEnabled() {
    var state = getEditorState();
    if (state === null) return null;
    return state.enabled;
  }

  function getEditorMode() {
    var state = getEditorState();
    if (state === null) return 'wysiwyg';
    return state.mode;
  }

  let wysiwygEditor = null;
  let wysiwygContainer = null;
  let cancelObserver = null;
  let toggleButton = null;
  let bodyObserver = null;
  var capturedMarkdownSelection = null;
  var pendingReadModeSelection = null;

  var isFocusModeActive = false;
  var _focusOverlay = null;
  var _focusTocObserver = null;
  var _focusContentScrollHandler = null;
  var _focusTocDebounceTimer = null;
  var _focusHeadingScrollHandler = null;
  var _focusSavedBodyOverflow = '';
  var _focusSavedContentHeight = '';
  var _focusOriginalToolbarParent = null;
  var _focusMdInputHandler = null;
  var _focusMdCursorHandler = null;

  var _focusModeGuardActive = false;
  var _focusModePollerTimer = null;
  var _focusModeRebuildPromptOpen = false;
  var _admonitionDropdownDismiss = null;
  var _reviewPopupDismiss = null;
  var _userActionInProgress = false;
  var _focusModeBuildEpoch = null;
  var _fmgOrigXHROpen = null;
  var _fmgOrigXHRSend = null;
  var _fmgOrigLocationReload = null;
  var _fmgOrigLocationAssign = null;
  var _fmgOrigLocationReplace = null;
  var _fmgOrigLocationHrefDesc = null;

  var FOCUS_MODE_STYLE_ID = 'live-wysiwyg-focus-mode-styles';
  var _ajaxCurrentSrcPath = null;

  function _getCurrentSrcPath() {
    return _ajaxCurrentSrcPath || (typeof liveWysiwygPageSrcPath !== 'undefined' ? liveWysiwygPageSrcPath : '');
  }

  // ======================================================================
  // NAV MENU - State variables
  // ======================================================================
  var _navEditMode = false;
  var _navMigrationPending = false;
  var _navFocusTarget = null;
  var _navBatchQueue = [];
  var _batchClaimedPaths = (typeof Set !== 'undefined' ? new Set() : null);
  var _navSnapshots = [];
  var _navSnapshotIndex = -1;
  var _navBadges = [];
  var _uidCounter = 0;
  var _suppressWarningSnapshot = false;
  var _warningDirectMode = false;
  var _navTopWarnings = [];
  var _navTopInfo = [];
  var _virtualMkdocsYml = null;
  var _virtualOriginalMkdocsYml = null;

  function _ymlHasNavKey(yml) {
    if (!yml || typeof yml !== 'string') return false;
    return /^nav\s*:/m.test(yml);
  }

  function _prefetchMkdocsYml() {
    if (_virtualMkdocsYml != null) return Promise.resolve();
    return _wsGetContents('../mkdocs.yml').then(function (yml) {
      _virtualMkdocsYml = yml || '';
      var origPath = (typeof liveWysiwygOriginalMkdocsYml === 'string' && liveWysiwygOriginalMkdocsYml)
        ? liveWysiwygOriginalMkdocsYml : null;
      if (origPath) {
        return _wsGetContents(origPath).then(function (origYml) {
          _virtualOriginalMkdocsYml = origYml || '';
        });
      }
    }).catch(function (err) {
      console.warn('[nav] Failed to pre-fetch mkdocs.yml:', err);
      _virtualMkdocsYml = '';
    });
  }

  var _navHiddenPagesPrecomputed = false;
  var _navKeyboardActiveItem = null;
  var _navActiveHoverLi = null;
  var _navKeyboardHandler = null;
  var _navSidebarEl = null;
  var _navScrollWrap = null;
  
  var _navEditActionsEl = null;
  var _navMaxWeight = 0;
  var _bulkWs = null;
  var _batchDeletedPaths = {};
  var _batchRenamedPaths = {};
  var _batchLinkIndex = null;
  var _NAV_WEIGHT_FM_KEYS = ['title', 'weight', 'headless', 'empty', 'retitled'];

  function _resolveChainedRename(path) {
    var cur = path;
    var visited = {};
    while (_batchRenamedPaths[cur] && !visited[cur]) {
      visited[cur] = true;
      cur = _batchRenamedPaths[cur];
    }
    return cur;
  }

  var _inMemoryRenderMode = false;
  var _isMaterialTheme = false;

  // ======================================================================
  // Persistent settings — single localStorage JSON object
  // ======================================================================
  var _LS_KEY = 'liveWysiwygSettings';
  var _settingsCache = null;
  var _settingDefaults = {
    'live_wysiwyg_autolaunch': '1',
    'live_wysiwyg_autofocus': '1',
    'live_wysiwyg_focus_remain': '1'
  };

  function _getSettings() {
    if (_settingsCache) return _settingsCache;
    try { _settingsCache = JSON.parse(localStorage.getItem(_LS_KEY)) || {}; }
    catch (e) { _settingsCache = {}; }
    return _settingsCache;
  }

  function _getSetting(key) {
    var val = _getSettings()[key];
    if (val !== undefined) return val;
    return _settingDefaults.hasOwnProperty(key) ? _settingDefaults[key] : undefined;
  }

  function _setSetting(key, value) {
    var s = _getSettings();
    s[key] = value;
    _settingsCache = s;
    try { localStorage.setItem(_LS_KEY, JSON.stringify(s)); } catch (e) {}
  }

  function _deleteSetting(key) {
    var s = _getSettings();
    delete s[key];
    _settingsCache = s;
    try { localStorage.setItem(_LS_KEY, JSON.stringify(s)); } catch (e) {}
  }

  (function _deleteOldCookies() {
    var keys = [
      'liveWysiwygEditorEnabled', 'liveWysiwygIndent',
      'live_wysiwyg_autofocus', 'live_wysiwyg_focus_remain',
      'live_wysiwyg_focus_toolbar', 'live_wysiwyg_focus_nav', 'live_wysiwyg_focus_toc',
      'live_wysiwyg_show_hidden', 'live_wysiwyg_image_attr_syntax',
      'live_wysiwyg_nav_edit_cursor', 'live_wysiwyg_focus_nav_retry',
      'live_wysiwyg_migration_result', 'live_wysiwyg_migration_normalize',
      'live_wysiwyg_migration_adjust_weight'
    ];
    for (var i = 0; i < keys.length; i++) {
      document.cookie = keys[i] + '=;path=/;max-age=0;SameSite=Lax';
    }
  })();

  // ======================================================================
  // Nav storage schema versioning
  // ======================================================================
  // Bump this integer whenever the nav-related localStorage data format
  // changes (e.g. new item types in navData, pipeline op structure changes,
  // caution/dead-link format changes). On mismatch, all nav-operational
  // localStorage is cleared to prevent stale data from corrupting state.
  // User preferences (liveWysiwygSettings) are never cleared.
  var _NAV_STORAGE_SCHEMA = 2;
  var _NAV_SCHEMA_KEY = 'live_wysiwyg_nav_schema';

  function _validateNavStorageSchema() {
    var stored;
    try { stored = parseInt(localStorage.getItem(_NAV_SCHEMA_KEY), 10); }
    catch (e) { stored = NaN; }
    if (stored === _NAV_STORAGE_SCHEMA) return;
    console.log('[storage] Nav schema mismatch (stored=' + stored + ' expected=' + _NAV_STORAGE_SCHEMA + '), clearing stale nav data');
    var keysToRemove = [
      'live_wysiwyg_caution_pages',
      'live_wysiwyg_dead_links',
      'live_wysiwyg_changes_pipeline',
      'live_wysiwyg_post_save_messages'
    ];
    for (var i = 0; i < keysToRemove.length; i++) {
      try { localStorage.removeItem(keysToRemove[i]); } catch (e) {}
    }
    try { localStorage.setItem(_NAV_SCHEMA_KEY, String(_NAV_STORAGE_SCHEMA)); } catch (e) {}
  }

  // ======================================================================
  // ======================================================================
  // NAV MENU - YAML Frontmatter parser/updater
  // ======================================================================
  function _parseFrontmatter(markdown) {
    var result = { raw: '', fields: {}, bodyStart: 0, lines: [], hasBlock: false };
    if (!markdown || !markdown.startsWith('---')) return result;
    var endIdx = markdown.indexOf('\n---', 3);
    if (endIdx === -1) {
      var altEnd = markdown.indexOf('\n...', 3);
      if (altEnd === -1) return result;
      endIdx = altEnd;
    }
    result.hasBlock = true;
    result.raw = markdown.substring(0, endIdx + 4);
    result.bodyStart = endIdx + 4;
    if (markdown[endIdx + 4] === '\n') result.bodyStart++;

    var inner = markdown.substring(4, endIdx);
    var lines = inner.split('\n');
    var inMultiline = false;
    var multilineKey = '';
    for (var i = 0; i < lines.length; i++) {
      var line = lines[i];
      if (inMultiline) {
        if (/^\S/.test(line) && /^[a-zA-Z_][\w-]*\s*:/.test(line)) {
          inMultiline = false;
        } else {
          result.lines.push({ type: 'continuation', key: multilineKey, text: line });
          continue;
        }
      }
      var m = line.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)/);
      if (m) {
        var key = m[1];
        var val = m[2].trimEnd();
        if (val === '|' || val === '>' || val === '|+' || val === '|-' || val === '>+' || val === '>-') {
          inMultiline = true;
          multilineKey = key;
          result.lines.push({ type: 'multiline-start', key: key, text: line });
          continue;
        }
        var parsed;
        if (val === 'true') parsed = true;
        else if (val === 'false') parsed = false;
        else if (/^-?\d+(\.\d+)?$/.test(val)) parsed = parseFloat(val);
        else if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'")))
          parsed = val.slice(1, -1);
        else parsed = val;
        result.fields[key] = parsed;
        result.lines.push({ type: 'field', key: key, value: parsed, text: line });
      } else {
        result.lines.push({ type: 'other', text: line });
      }
    }
    return result;
  }

  function _buildFrontmatterString(fm, isIndex) {
    if (!fm.lines.length && !Object.keys(fm.fields).length) return '';
    var nwKeys = { weight: 1, headless: 1, retitled: 1, empty: 1 };
    var defaults = (typeof liveWysiwygNavWeightConfig !== 'undefined' && liveWysiwygNavWeightConfig.enabled)
      ? (liveWysiwygNavWeightConfig.frontmatter_defaults || {}) : {};
    var weightDefault = isIndex ? (defaults.index_weight !== undefined ? defaults.index_weight : -10)
      : (defaults.weight !== undefined ? defaults.weight : 0);

    function shouldStrip(key, val) {
      if (key === 'title') return false;
      if (key === 'weight') return false;
      if (key === 'empty' && isIndex && fm.fields.retitled === true) return false;
      if (key === 'headless') return val === false;
      if (key === 'retitled') return val === false;
      if (key === 'empty') return val === false;
      return false;
    }

    var origKeys = {};
    for (var li = 0; li < fm.lines.length; li++) {
      if (fm.lines[li].key) origKeys[fm.lines[li].key] = true;
    }

    var outLines = [];
    for (var i = 0; i < fm.lines.length; i++) {
      var entry = fm.lines[i];
      if (entry.type === 'field') {
        if (!(entry.key in fm.fields)) continue;
        var val = fm.fields[entry.key];
        if (entry.key in nwKeys && shouldStrip(entry.key, val)) continue;
        outLines.push(entry.key + ': ' + _fmSerialize(val));
      } else if (entry.type === 'multiline-start') {
        if (!(entry.key in fm.fields)) continue;
        outLines.push(entry.text);
      } else if (entry.type === 'continuation') {
        outLines.push(entry.text);
      } else {
        outLines.push(entry.text);
      }
    }

    var newTitleLine = null;
    var newWeightLine = null;
    for (var key in fm.fields) {
      if (!fm.fields.hasOwnProperty(key)) continue;
      if (origKeys[key]) continue;
      var v = fm.fields[key];
      if (key in nwKeys && shouldStrip(key, v)) continue;
      var newLine = key + ': ' + _fmSerialize(v);
      if (key === 'title') { newTitleLine = newLine; continue; }
      if (key === 'weight') { newWeightLine = newLine; continue; }
      outLines.push(newLine);
    }

    if (newTitleLine) outLines.splice(0, 0, newTitleLine);
    if (newWeightLine) outLines.push(newWeightLine);

    if (!outLines.length) return '';
    return '---\n' + outLines.join('\n') + '\n---\n';
  }

  function _buildFrontmatterFromFm(fm, isIndex, origFm) {
    if (!fm || typeof fm !== 'object') return '';
    var nwKeys = { weight: 1, headless: 1, retitled: 1, empty: 1 };
    var defaults = (typeof liveWysiwygNavWeightConfig !== 'undefined' && liveWysiwygNavWeightConfig.enabled)
      ? (liveWysiwygNavWeightConfig.frontmatter_defaults || {}) : {};
    var weightDefault = isIndex ? (defaults.index_weight !== undefined ? defaults.index_weight : -10)
      : (defaults.weight !== undefined ? defaults.weight : 0);

    function shouldStrip(key, val) {
      if (key === 'title') return false;
      if (key === 'weight') return false;
      if (key === 'empty' && isIndex && fm.retitled === true) return false;
      if (key === 'headless') return val === false;
      if (key === 'retitled') return val === false;
      if (key === 'empty') return val === false;
      return false;
    }

    var origSet = {};
    if (origFm && typeof origFm === 'object') {
      for (var ok in origFm) {
        if (origFm.hasOwnProperty(ok)) origSet[ok] = true;
      }
    }

    function makeLine(key) {
      var val = fm[key];
      if (val == null) return null;
      if (key in nwKeys && shouldStrip(key, val)) return null;
      return key + ': ' + _fmSerialize(val);
    }

    var outLines = [];
    var newTitleLine = null;
    var newWeightLine = null;
    var fmKeys = Object.keys(fm);
    for (var i = 0; i < fmKeys.length; i++) {
      var key = fmKeys[i];
      var line = makeLine(key);
      if (!line) continue;
      if (!origSet[key]) {
        if (key === 'title') { newTitleLine = line; continue; }
        if (key === 'weight') { newWeightLine = line; continue; }
      }
      outLines.push(line);
    }

    if (newTitleLine) outLines.splice(0, 0, newTitleLine);
    if (newWeightLine) outLines.push(newWeightLine);

    if (!outLines.length) return '';
    var fmResult = '---\n' + outLines.join('\n') + '\n---\n';
    return fmResult;
  }

  function _fmSerialize(val) {
    if (val === true) return 'true';
    if (val === false) return 'false';
    if (typeof val === 'number') return String(val);
    if (typeof val === 'string') {
      if (/[:#\[\]{}&*?|>!%@`,]/.test(val) || val === '' || val.trim() !== val)
        return '"' + val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
      return val;
    }
    return String(val);
  }

  function _updateFrontmatter(markdown, updates, isIndex) {
    var fm = _parseFrontmatter(markdown);
    var body = fm.hasBlock ? markdown.substring(fm.bodyStart) : markdown;
    for (var key in updates) {
      if (updates.hasOwnProperty(key)) {
        if (updates[key] === null || updates[key] === undefined) {
          delete fm.fields[key];
        } else {
          fm.fields[key] = updates[key];
        }
      }
    }
    var newFm = _buildFrontmatterString(fm, isIndex);
    return newFm + body;
  }

  // ======================================================================
  // NAV MENU - File naming convention
  // ======================================================================
  function _generateFilename(title) {
    if (!title) return 'untitled.md';
    var name = title.replace(/[^a-zA-Z-]/g, '').toLowerCase();
    if (!name) name = 'untitled';
    var spacedTitle = title.replace(/\s+/g, '-');
    name = spacedTitle.replace(/[^a-zA-Z-]/g, '').toLowerCase();
    if (!name) name = 'untitled';
    return name + '.md';
  }

  function _resolveFilenameConflict(baseName, existingPaths, claimedPaths) {
    var name = baseName.replace(/\.md$/, '');
    var candidate = baseName;
    var i = 2;
    while (existingPaths.indexOf(candidate) !== -1 || (claimedPaths && (claimedPaths.has ? claimedPaths.has(candidate) : claimedPaths.indexOf && claimedPaths.indexOf(candidate) !== -1))) {
      candidate = name + i + '.md';
      i++;
    }
    return candidate;
  }

  // ======================================================================
  // NAV MENU - Dedicated WebSocket for bulk operations
  // ======================================================================
  function _getOrCreateBulkWs() {
    return new Promise(function (resolve, reject) {
      if (_bulkWs && _bulkWs.readyState === WebSocket.OPEN) {
        resolve(_bulkWs);
        return;
      }
      if (typeof ws_port === 'undefined') {
        reject(new Error('ws_port not available'));
        return;
      }
      var ws = new WebSocket('ws://' + location.hostname + ':' + ws_port);
      ws.onerror = function () { reject(new Error('Bulk WS connection failed')); };
      ws.onclose = function () { _bulkWs = null; };
      ws.onopen = function () {
        var connHandler = function (e) {
          ws.removeEventListener('message', connHandler);
          try {
            var data = JSON.parse(e.data);
            if (data && data.action === 'connected') {
              _bulkWs = ws;
              resolve(ws);
              return;
            }
          } catch (err) { /* not JSON */ }
          _bulkWs = ws;
          resolve(ws);
        };
        ws.addEventListener('message', connHandler);
        setTimeout(function () {
          ws.removeEventListener('message', connHandler);
          _bulkWs = ws;
          resolve(ws);
        }, 3000);
      };
    });
  }

  function _wsSendOnce(action, path, contents) {
    return _getOrCreateBulkWs().then(function (ws) {
      return new Promise(function (resolve, reject) {
        var msg = { action: action, path: path };
        if (contents !== undefined) msg.contents = contents;
        var settled = false;
        var handler = function (e) {
          try {
            var data = JSON.parse(e.data);
            if (data && data.action === action) {
              cleanup();
              resolve(data);
            }
          } catch (err) {
            cleanup();
            resolve(e.data);
          }
        };
        var closeHandler = function () {
          cleanup();
          _bulkWs = null;
          reject({ _wsRetryable: true, message: 'WS closed during ' + action + ' ' + path });
        };
        var errorHandler = function () {
          cleanup();
          _bulkWs = null;
          reject({ _wsRetryable: true, message: 'WS error during ' + action + ' ' + path });
        };
        var timer = setTimeout(function () {
          cleanup();
          reject(new Error('WS timeout for ' + action + ' ' + path));
        }, 15000);
        function cleanup() {
          if (settled) return;
          settled = true;
          clearTimeout(timer);
          ws.removeEventListener('message', handler);
          ws.removeEventListener('close', closeHandler);
          ws.removeEventListener('error', errorHandler);
        }
        ws.addEventListener('message', handler);
        ws.addEventListener('close', closeHandler);
        ws.addEventListener('error', errorHandler);
        ws.send(JSON.stringify(msg));
      });
    });
  }

  var _WS_MAX_RETRIES = 3;

  function _wsSend(action, path, contents) {
    var attempt = 0;
    function tryOnce() {
      attempt++;
      return _wsSendOnce(action, path, contents).catch(function (err) {
        if (err && err._wsRetryable && attempt < _WS_MAX_RETRIES) {
          return _waitForRebuildAndReconnect().then(tryOnce);
        }
        throw err._wsRetryable ? new Error(err.message) : err;
      });
    }
    return tryOnce();
  }

  function _wsGetContents(path) {
    return _wsSend('get_contents', path).then(function (resp) {
      if (resp && typeof resp.contents === 'string') return resp.contents;
      if (typeof resp === 'string') return resp;
      if (resp && resp.contents !== undefined) return String(resp.contents);
      return '';
    });
  }

  function _wsSetContents(path, contents) {
    return _wsSend('set_contents', path, contents);
  }

  function _wsNewFile(path, title) {
    return _getOrCreateBulkWs().then(function (ws) {
      return new Promise(function (resolve, reject) {
        var msg = { action: 'new_file', path: path, title: title || 'Untitled' };
        var settled = false;
        var handler = function (e) {
          try {
            var data = JSON.parse(e.data);
            if (data && data.action === 'new_file') {
              cleanup();
              resolve(data);
            }
          } catch (err) {
            cleanup();
            resolve(e.data);
          }
        };
        var closeHandler = function () {
          cleanup();
          _bulkWs = null;
          reject(new Error('WS closed during new_file ' + path));
        };
        var errorHandler = function () {
          cleanup();
          _bulkWs = null;
          reject(new Error('WS error during new_file ' + path));
        };
        var timer = setTimeout(function () {
          cleanup();
          reject(new Error('WS timeout for new_file ' + path));
        }, 15000);
        function cleanup() {
          if (settled) return;
          settled = true;
          clearTimeout(timer);
          ws.removeEventListener('message', handler);
          ws.removeEventListener('close', closeHandler);
          ws.removeEventListener('error', errorHandler);
        }
        ws.addEventListener('message', handler);
        ws.addEventListener('close', closeHandler);
        ws.addEventListener('error', errorHandler);
        ws.send(JSON.stringify(msg));
      });
    });
  }

  function _wsDeleteFile(path) {
    return _wsSend('delete_file', path);
  }

  // ======================================================================
  // NAV MENU - Livereload guard & rebuild polling
  // ======================================================================
  // Suppresses MkDocs' livereload long-polling XHR to /livereload/ so the
  // page never auto-reloads during batch processing.  Our own rebuild
  // detection uses fetch() which is completely independent of XHR.
  //
  // Two layers:
  // 1. Tracking hook (always active): records every XHR opened to
  //    /livereload/ so we can abort pre-existing in-flight requests.
  // 2. Guard (active only during batch): patches XHR.open/send to
  //    suppress NEW livereload requests.
  //
  // _installReloadGuard  — aborts tracked XHRs + patches open/send
  // _removeReloadGuard   — restores originals; safe to call when inactive
  // _waitForRebuild      — polls /livereload/ via fetch, resolves on reply
  // _waitForRebuildAndReconnect — waitForRebuild + reconnect bulk WebSocket
  // ======================================================================

  var _trackedLivereloadXHRs = [];
  var _xhrTrackingHookOpen = XMLHttpRequest.prototype.open;
  XMLHttpRequest.prototype.open = function (method, url) {
    if (typeof url === 'string' && url.indexOf('/livereload/') !== -1) {
      this._liveWysiwygLivereloadXHR = true;
      _trackedLivereloadXHRs.push(this);
    }
    return _xhrTrackingHookOpen.apply(this, arguments);
  };

  var _reloadGuardActive = false;
  var _origXHROpen = null;
  var _origXHRSend = null;
  var _origLocationReload = null;
  var _origLocationAssign = null;
  var _origLocationReplace = null;
  var _origLocationHrefDesc = null;
  var _reloadGuardBeforeUnloadHandler = null;

  // ======================================================================
  // WebSocket redirect suppression
  // ======================================================================
  // The upstream mkdocs-live-edit-plugin sends { action:'redirect', new_url }
  // over its WebSocket when a page was recently created or renamed.  During
  // batch operations or migration Phase 8, this redirect would navigate away
  // and kill the in-progress operation.  Because Chrome does not allow
  // redefining location properties, we intercept the redirect at the
  // WebSocket message level instead.
  //
  // The wrapper patches WebSocket.prototype.onmessage (setter) so that any
  // handler installed by upstream code is transparently wrapped.  When the
  // suppress flag is active, messages with action:'redirect' are swallowed
  // and the URL is stored for later use.
  // ======================================================================
  var _wsRedirectSuppressActive = false;
  var _suppressedRedirectUrl = null;

  (function _installWsRedirectWrapper() {
    var desc = Object.getOwnPropertyDescriptor(WebSocket.prototype, 'onmessage');
    if (!desc || !desc.set) {
      return;
    }
    Object.defineProperty(WebSocket.prototype, 'onmessage', {
      get: desc.get,
      set: function (fn) {
        if (typeof fn !== 'function') { desc.set.call(this, fn); return; }
        var ws = this;
        desc.set.call(this, function (e) {
          if (_wsRedirectSuppressActive || _reloadGuardActive || _focusModeGuardActive) {
            try {
              var data = JSON.parse(e.data);
              if (data && data.action === 'redirect' && data.new_url) {
                _suppressedRedirectUrl = data.new_url;
                if (_focusModeGuardActive && !_reloadGuardActive && !_userActionInProgress && !_isMigrationChainActive()) {
                  _onExternalRebuild();
                }
                return;
              }
            } catch (err) { /* not JSON — pass through */ }
          }
          return fn.call(ws, e);
        });
      },
      configurable: true,
      enumerable: desc.enumerable
    });
  })();

  // Set suppress flag early if the migration-normalize setting is present.
  // This runs synchronously before the live-edit plugin creates its WebSocket
  // (which happens on DOMContentLoaded), closing the race window.
  function _isMigrationChainActive() {
    return _getSetting('live_wysiwyg_migration_normalize') === '1' ||
      _getSetting('live_wysiwyg_migration_adjust_weight') === '1';
  }

  (function _earlyMigrationSuppressCheck() {
    if (_isMigrationChainActive()) {
      _wsRedirectSuppressActive = true;
    }
  })();

  function _installReloadGuard() {
    if (_reloadGuardActive) { return; }
    _reloadGuardActive = true;

    if (_focusModeGuardActive) return;

    _reloadGuardBeforeUnloadHandler = function (e) {
    };
    window.addEventListener('beforeunload', _reloadGuardBeforeUnloadHandler);

    for (var i = 0; i < _trackedLivereloadXHRs.length; i++) {
      try { _trackedLivereloadXHRs[i].abort(); } catch (e) { /* noop */ }
    }
    _trackedLivereloadXHRs = [];

    if (!_origXHROpen) _origXHROpen = XMLHttpRequest.prototype.open;
    if (!_origXHRSend) _origXHRSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function (method, url) {
      if (_reloadGuardActive && typeof url === 'string' && url.indexOf('/livereload/') !== -1) {
        this._liveWysiwygSuppressed = true;
        return;
      }
      return _origXHROpen.apply(this, arguments);
    };
    XMLHttpRequest.prototype.send = function () {
      if (this._liveWysiwygSuppressed) { return; }
      return _origXHRSend.apply(this, arguments);
    };

    try {
      if (!_origLocationReload) _origLocationReload = location.reload.bind(location);
      Object.defineProperty(location, 'reload', {
        configurable: true,
        value: function () {
          if (_reloadGuardActive) { return; }
          return _origLocationReload();
        }
      });
    } catch (e) { _origLocationReload = null; }
    try {
      if (!_origLocationAssign) _origLocationAssign = location.assign.bind(location);
      Object.defineProperty(location, 'assign', {
        configurable: true,
        value: function (url) {
          if (_reloadGuardActive) { return; }
          return _origLocationAssign(url);
        }
      });
    } catch (e) { _origLocationAssign = null; }
    try {
      if (!_origLocationReplace) _origLocationReplace = location.replace.bind(location);
      Object.defineProperty(location, 'replace', {
        configurable: true,
        value: function (url) {
          if (_reloadGuardActive) { return; }
          return _origLocationReplace(url);
        }
      });
    } catch (e) { _origLocationReplace = null; }
    try {
      if (!_origLocationHrefDesc) _origLocationHrefDesc = Object.getOwnPropertyDescriptor(Location.prototype, 'href') ||
        Object.getOwnPropertyDescriptor(location, 'href');
      if (_origLocationHrefDesc && _origLocationHrefDesc.set) {
        Object.defineProperty(location, 'href', {
          configurable: true,
          get: _origLocationHrefDesc.get ? _origLocationHrefDesc.get.bind(location) : function () { return location.toString(); },
          set: function (v) {
            if (_reloadGuardActive) { return; }
            _origLocationHrefDesc.set.call(location, v);
          }
        });
      }
    } catch (e) { _origLocationHrefDesc = null; }
  }

  function _removeReloadGuard() {
    _reloadGuardActive = false;
    _wsRedirectSuppressActive = false;

    if (_focusModeGuardActive) return;

    if (_reloadGuardBeforeUnloadHandler) {
      window.removeEventListener('beforeunload', _reloadGuardBeforeUnloadHandler);
      _reloadGuardBeforeUnloadHandler = null;
    }
    if (_origXHROpen) XMLHttpRequest.prototype.open = _origXHROpen;
    if (_origXHRSend) XMLHttpRequest.prototype.send = _origXHRSend;
    _origXHROpen = null;
    _origXHRSend = null;

    if (_origLocationReload) {
      try { Object.defineProperty(location, 'reload', { configurable: true, value: _origLocationReload }); } catch (e) { }
      _origLocationReload = null;
    }
    if (_origLocationAssign) {
      try { Object.defineProperty(location, 'assign', { configurable: true, value: _origLocationAssign }); } catch (e) { }
      _origLocationAssign = null;
    }
    if (_origLocationReplace) {
      try { Object.defineProperty(location, 'replace', { configurable: true, value: _origLocationReplace }); } catch (e) { }
      _origLocationReplace = null;
    }
    if (_origLocationHrefDesc) {
      try { Object.defineProperty(location, 'href', _origLocationHrefDesc); } catch (e) { }
      _origLocationHrefDesc = null;
    }
  }

  // ======================================================================
  // Focus-mode persistent reload guard
  // ======================================================================

  function _installFocusModeGuard() {
    if (_focusModeGuardActive) return;
    _focusModeGuardActive = true;

    for (var i = 0; i < _trackedLivereloadXHRs.length; i++) {
      try { _trackedLivereloadXHRs[i].abort(); } catch (e) { /* noop */ }
    }
    _trackedLivereloadXHRs = [];

    _fmgOrigXHROpen = XMLHttpRequest.prototype.open;
    _fmgOrigXHRSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function (method, url) {
      if (_focusModeGuardActive && typeof url === 'string' && url.indexOf('/livereload/') !== -1) {
        this._liveWysiwygSuppressed = true;
        return;
      }
      return _fmgOrigXHROpen.apply(this, arguments);
    };
    XMLHttpRequest.prototype.send = function () {
      if (this._liveWysiwygSuppressed) return;
      return _fmgOrigXHRSend.apply(this, arguments);
    };

    function _fmgLocationIntercept() {
      if (_reloadGuardActive || _userActionInProgress) return;
      _onExternalRebuild();
    }

    try {
      _fmgOrigLocationReload = location.reload.bind(location);
      Object.defineProperty(location, 'reload', {
        configurable: true,
        value: function () {
          if (_focusModeGuardActive) { _fmgLocationIntercept(); return; }
          return _fmgOrigLocationReload();
        }
      });
    } catch (e) { _fmgOrigLocationReload = null; }
    try {
      _fmgOrigLocationAssign = location.assign.bind(location);
      Object.defineProperty(location, 'assign', {
        configurable: true,
        value: function (url) {
          if (_focusModeGuardActive) { _fmgLocationIntercept(); return; }
          return _fmgOrigLocationAssign(url);
        }
      });
    } catch (e) { _fmgOrigLocationAssign = null; }
    try {
      _fmgOrigLocationReplace = location.replace.bind(location);
      Object.defineProperty(location, 'replace', {
        configurable: true,
        value: function (url) {
          if (_focusModeGuardActive) { _fmgLocationIntercept(); return; }
          return _fmgOrigLocationReplace(url);
        }
      });
    } catch (e) { _fmgOrigLocationReplace = null; }
    try {
      _fmgOrigLocationHrefDesc = Object.getOwnPropertyDescriptor(Location.prototype, 'href') ||
        Object.getOwnPropertyDescriptor(location, 'href');
      if (_fmgOrigLocationHrefDesc && _fmgOrigLocationHrefDesc.set) {
        Object.defineProperty(location, 'href', {
          configurable: true,
          get: _fmgOrigLocationHrefDesc.get ? _fmgOrigLocationHrefDesc.get.bind(location) : function () { return location.toString(); },
          set: function (v) {
            if (_focusModeGuardActive) { _fmgLocationIntercept(); return; }
            _fmgOrigLocationHrefDesc.set.call(location, v);
          }
        });
      }
    } catch (e) { _fmgOrigLocationHrefDesc = null; }

    _startFocusModeRebuildPoller();
  }

  function _removeFocusModeGuard() {
    _focusModeGuardActive = false;
    _focusModeRebuildPromptOpen = false;
    _focusModeBuildEpoch = null;

    if (_focusModePollerTimer) {
      clearTimeout(_focusModePollerTimer);
      _focusModePollerTimer = null;
    }

    if (_fmgOrigXHROpen) XMLHttpRequest.prototype.open = _fmgOrigXHROpen;
    if (_fmgOrigXHRSend) XMLHttpRequest.prototype.send = _fmgOrigXHRSend;
    _fmgOrigXHROpen = null;
    _fmgOrigXHRSend = null;

    if (_fmgOrigLocationReload) {
      try { Object.defineProperty(location, 'reload', { configurable: true, value: _fmgOrigLocationReload }); } catch (e) { }
      _fmgOrigLocationReload = null;
    }
    if (_fmgOrigLocationAssign) {
      try { Object.defineProperty(location, 'assign', { configurable: true, value: _fmgOrigLocationAssign }); } catch (e) { }
      _fmgOrigLocationAssign = null;
    }
    if (_fmgOrigLocationReplace) {
      try { Object.defineProperty(location, 'replace', { configurable: true, value: _fmgOrigLocationReplace }); } catch (e) { }
      _fmgOrigLocationReplace = null;
    }
    if (_fmgOrigLocationHrefDesc) {
      try { Object.defineProperty(location, 'href', _fmgOrigLocationHrefDesc); } catch (e) { }
      _fmgOrigLocationHrefDesc = null;
    }
  }

  function _syncBuildEpoch() {
    if (typeof liveWysiwygLinkCheckPort === 'undefined' || !liveWysiwygLinkCheckPort) return;
    var host = window.location.hostname || '127.0.0.1';
    fetch('http://' + host + ':' + liveWysiwygLinkCheckPort + '/build-epoch', { cache: 'no-store' })
      .then(function (resp) { return resp.ok ? resp.json() : null; })
      .then(function (data) { if (data && data.epoch != null) _focusModeBuildEpoch = data.epoch; })
      .catch(function () {});
  }

  function _startFocusModeRebuildPoller() {
    if (!_focusModeGuardActive) return;
    if (typeof liveWysiwygLinkCheckPort === 'undefined' || !liveWysiwygLinkCheckPort) return;
    if (_focusModePollerTimer) { clearTimeout(_focusModePollerTimer); _focusModePollerTimer = null; }

    var host = window.location.hostname || '127.0.0.1';
    var epochUrl = 'http://' + host + ':' + liveWysiwygLinkCheckPort + '/build-epoch';

    function poll() {
      if (!_focusModeGuardActive) return;
      fetch(epochUrl, { cache: 'no-store' }).then(function (resp) {
        if (!resp.ok) throw new Error('HTTP ' + resp.status);
        return resp.json();
      }).then(function (data) {
        if (!_focusModeGuardActive) return;
        var serverEpoch = data.epoch;
        if (_focusModeBuildEpoch === null) {
          _focusModeBuildEpoch = serverEpoch;
          _focusModePollerTimer = setTimeout(poll, 2000);
          return;
        }
        if (serverEpoch === _focusModeBuildEpoch) {
          _focusModePollerTimer = setTimeout(poll, 2000);
          return;
        }
        _focusModeBuildEpoch = serverEpoch;
        if (_userActionInProgress || _reloadGuardActive || _focusModeRebuildPromptOpen || _isMigrationChainActive()) {
          _focusModePollerTimer = setTimeout(poll, 2000);
          return;
        }
        _onExternalRebuild();
      }).catch(function () {
        if (_focusModeGuardActive) _focusModePollerTimer = setTimeout(poll, 2000);
      });
    }
    _focusModePollerTimer = setTimeout(poll, 2000);
  }

  function _focusModeRefreshContent() {
    var currentSrc = _getCurrentSrcPath();
    if (!currentSrc) return Promise.resolve();
    var transitionOv = _showFullScreenTransition('Refreshing...');
    return _wsGetContents(currentSrc).then(function (md) {
      if (wysiwygEditor && wysiwygEditor._loadContent) {
        wysiwygEditor._loadContent(md);
      }
      if (wysiwygEditor && wysiwygEditor._resetPristineContent) {
        var ta = document.querySelector('.live-edit-source');
        if (ta) wysiwygEditor._resetPristineContent(ta.value);
      }
      _refreshFocusToc();
      _fadeOutOverlay(transitionOv);
    }).catch(function () {
      _fadeOutOverlay(transitionOv);
    });
  }

  function _onExternalRebuild() {
    if (_focusModeRebuildPromptOpen) return;
    if (!_focusModeGuardActive) return;
    _focusModeRebuildPromptOpen = true;

    var docDirty = wysiwygEditor && wysiwygEditor._isDocDirty && wysiwygEditor._isDocDirty();
    var navDirty = _navEditMode;
    var hasPendingChanges = docDirty || navDirty;

    if (!hasPendingChanges) {
      _showNavDialog(
        'An external change triggered a site rebuild.',
        [{ text: 'Refresh', value: 'refresh', className: 'live-wysiwyg-nav-dialog-primary' }]
      ).then(function (result) {
        _focusModeRebuildPromptOpen = false;
        if (result === 'refresh') {
          _focusModeRefreshContent().then(function () {
            _startFocusModeRebuildPoller();
          });
        } else {
          _startFocusModeRebuildPoller();
        }
      });
    } else {
      _showNavDialog(
        'An external change triggered a site rebuild. You have unsaved changes.',
        [
          { text: 'Discard and Refresh', value: 'discard' },
          { text: 'Save changes and Refresh', value: 'save', className: 'live-wysiwyg-nav-dialog-primary' }
        ]
      ).then(function (result) {
        _focusModeRebuildPromptOpen = false;
        if (result === 'save') {
          if (_navEditMode) {
            _confirmNavSave();
          } else {
            _doFocusSave().then(function () {
              return _focusModeRefreshContent();
            }).then(function () {
              _startFocusModeRebuildPoller();
            });
          }
        } else if (result === 'discard') {
          if (_navEditMode) _exitNavEditMode(true);
          _focusModeRefreshContent().then(function () {
            _startFocusModeRebuildPoller();
          });
        } else {
          _startFocusModeRebuildPoller();
        }
      });
    }
  }

  function _closeBulkWs() {
    if (_bulkWs) {
      try { _bulkWs.close(); } catch (e) { /* noop */ }
      _bulkWs = null;
    }
  }

  function _waitForRebuild() {
    return new Promise(function (resolve) {
      var resolved = false;
      function done() { if (!resolved) { resolved = true; resolve(); } }

      var attempts = 0;
      var maxAttempts = 60;
      var delay = 1500;

      function poll() {
        attempts++;
        if (attempts > maxAttempts) { done(); return; }
        fetch('/livereload/' + Date.now(), { cache: 'no-store' })
          .then(function () { done(); })
          .catch(function () {
            if (attempts < maxAttempts) setTimeout(poll, delay);
            else done();
          });
      }

      setTimeout(poll, delay);
    });
  }

  function _refreshLinkCheckPort() {
    return fetch(window.location.href, { cache: 'no-store' })
      .then(function (resp) { return resp.text(); })
      .then(function (html) {
        var m = html.match(/liveWysiwygLinkCheckPort\s*=\s*(\d+)/);
        if (m) {
          var newPort = parseInt(m[1], 10);
          if (newPort && newPort !== liveWysiwygLinkCheckPort) {
            console.info('[wysiwyg] Link check port changed: ' + liveWysiwygLinkCheckPort + ' → ' + newPort);
            liveWysiwygLinkCheckPort = newPort;
          }
        }
      })
      .catch(function () { /* page fetch failed, keep current port */ });
  }

  function _waitForRebuildAndReconnect() {
    _closeBulkWs();
    return _waitForRebuild().then(function () {
      return _refreshLinkCheckPort();
    }).then(function () {
      return _getOrCreateBulkWs();
    }).catch(function (err) {
      return _getOrCreateBulkWs();
    });
  }

  // ======================================================================
  // NAV MENU - Link rewriting utilities
  // ======================================================================
  var _RE_FENCED_CODE = /^(`{3,}|~{3,})[^\n]*\n[\s\S]*?\n\1\s*$/gm;
  var _RE_INLINE_CODE = /`[^`]+`/g;
  var _RE_HTML_COMMENT = /<!--[\s\S]*?-->/g;

  function _findExclusionZones(content) {
    var zones = [];
    var m;
    var patterns = [_RE_FENCED_CODE, _RE_INLINE_CODE, _RE_HTML_COMMENT];
    for (var p = 0; p < patterns.length; p++) {
      patterns[p].lastIndex = 0;
      while ((m = patterns[p].exec(content)) !== null) {
        zones.push([m.index, m.index + m[0].length]);
      }
    }
    zones.sort(function (a, b) { return a[0] - b[0]; });
    return zones;
  }

  function _isInExclusionZone(offset, zones) {
    for (var i = 0; i < zones.length; i++) {
      if (offset >= zones[i][0] && offset < zones[i][1]) return true;
      if (zones[i][0] > offset) break;
    }
    return false;
  }

  function _resolvePath(fromDir, relativePath) {
    var parts = fromDir.replace(/\/$/, '').split('/').filter(Boolean);
    var relParts = relativePath.split('/');
    for (var i = 0; i < relParts.length; i++) {
      if (relParts[i] === '..') {
        if (parts.length) parts.pop();
        else return null;
      }
      else if (relParts[i] !== '.' && relParts[i] !== '') parts.push(relParts[i]);
    }
    return parts.join('/');
  }

  function _computeRelativePath(fromDir, toPath) {
    var fromParts = fromDir.replace(/\/$/, '').split('/').filter(Boolean);
    var toParts = toPath.split('/');
    var common = 0;
    while (common < fromParts.length && common < toParts.length && fromParts[common] === toParts[common]) common++;
    var ups = fromParts.length - common;
    var rel = [];
    for (var i = 0; i < ups; i++) rel.push('..');
    for (var j = common; j < toParts.length; j++) rel.push(toParts[j]);
    return rel.join('/') || '.';
  }

  function _getDir(srcPath) {
    var idx = srcPath.lastIndexOf('/');
    return idx >= 0 ? srcPath.substring(0, idx) : '';
  }

  function _makeRelativePath(fromPath, toPath) {
    return _computeRelativePath(_getDir(fromPath), toPath);
  }

  function _rewriteOutboundLinks(content, oldDir, newDir) {
    if (oldDir === newDir) return content;
    var oldPath = oldDir ? oldDir + '/_.md' : '_.md';
    var newPath = newDir ? newDir + '/_.md' : '_.md';
    return _rewriteLinksInContent(content, oldPath, newPath);
  }

  function _looksLikePageRef(pathStr) {
    var lastSlash = pathStr.lastIndexOf('/');
    var filename = lastSlash >= 0 ? pathStr.substring(lastSlash + 1) : pathStr;
    var dotIdx = filename.lastIndexOf('.');
    if (dotIdx <= 0) return true;
    return filename.substring(dotIdx + 1).toLowerCase() === 'md';
  }

  function _rewriteLinksInContent(content, oldSrcPath, newSrcPath) {
    var oldDir = _getDir(oldSrcPath);
    var newDir = _getDir(newSrcPath);
    if (oldDir === newDir) return content;
    var allPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
    var knownPaths = {};
    for (var k = 0; k < allPaths.length; k++) knownPaths[allPaths[k]] = true;
    var zones = _findExclusionZones(content);
    var patterns = [
      { re: /(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, group: 2, prefix: '[', mid: '](', suffix: ')' },
      { re: /!\[([^\]]*)\]\(([^)]+)\)/g, group: 2, prefix: '![', mid: '](', suffix: ')' },
      { re: /<img([^>]+)src=["']([^"']+)["']/g, group: 2, isTag: true },
      { re: /^\[([^\]]+)\]:\s+(\S+)/gm, group: 2, isRefDef: true }
    ];
    var replacements = [];
    var excludedCount = 0;
    for (var p = 0; p < patterns.length; p++) {
      var pat = patterns[p];
      pat.re.lastIndex = 0;
      var m;
      while ((m = pat.re.exec(content)) !== null) {
        if (_isInExclusionZone(m.index, zones)) { excludedCount++; continue; }
        var fullTarget = m[pat.group];
        if (!fullTarget || fullTarget.startsWith('http://') || fullTarget.startsWith('https://') ||
            fullTarget.startsWith('#') || fullTarget.startsWith('mailto:') || fullTarget.startsWith('data:')) continue;
        var anchorIdx = fullTarget.indexOf('#');
        var queryIdx = fullTarget.indexOf('?');
        var splitIdx = -1;
        if (anchorIdx !== -1 && queryIdx !== -1) splitIdx = Math.min(anchorIdx, queryIdx);
        else if (anchorIdx !== -1) splitIdx = anchorIdx;
        else if (queryIdx !== -1) splitIdx = queryIdx;
        var pathPart = splitIdx >= 0 ? fullTarget.substring(0, splitIdx) : fullTarget;
        var suffix = splitIdx >= 0 ? fullTarget.substring(splitIdx) : '';
        if (!pathPart) continue;
        var decoded = decodeURIComponent(pathPart);
        var absTarget = _resolvePath(oldDir, decoded);
        if (absTarget === null) continue;
        if (_looksLikePageRef(decoded) &&
            !knownPaths[absTarget] && !knownPaths[absTarget + '.md'] && !knownPaths[absTarget + '/index.md']) continue;
        var newRelative = _computeRelativePath(newDir, absTarget);
        var needsEncode = pathPart !== decoded;
        if (needsEncode) newRelative = encodeURIComponent(newRelative).replace(/%2F/g, '/');
        var newTarget = newRelative + suffix;
        if (newTarget !== fullTarget) {
          var targetStart = m.index + m[0].lastIndexOf(fullTarget);
          replacements.push({ start: targetStart, end: targetStart + fullTarget.length, replacement: newTarget });
        }
      }
    }
    if (!replacements.length) return content;
    replacements.sort(function (a, b) { return b.start - a.start; });
    var result = content;
    for (var i = 0; i < replacements.length; i++) {
      var r = replacements[i];
      result = result.substring(0, r.start) + r.replacement + result.substring(r.end);
    }
    return result;
  }

  function _rewriteInboundLinksInPage(pageContent, oldTargetSrcPath, newTargetSrcPath, pageSrcPath) {
    var pageDir = _getDir(pageSrcPath);
    var oldRelative = _computeRelativePath(pageDir, oldTargetSrcPath);
    var newRelative = _computeRelativePath(pageDir, newTargetSrcPath);
    if (oldRelative === newRelative) {
      return pageContent;
    }
    var zones = _findExclusionZones(pageContent);

    var searchPatterns = [oldRelative];
    var isIndex = oldTargetSrcPath.endsWith('/index.md') || oldTargetSrcPath === 'index.md';
    if (isIndex) {
      var oldDir = _getDir(oldTargetSrcPath);
      var dirRelative = _computeRelativePath(pageDir, oldDir ? oldDir + '/' : '');
      if (dirRelative !== oldRelative) searchPatterns.push(dirRelative);
      var dirRelativeNoSlash = dirRelative.replace(/\/$/, '');
      if (dirRelativeNoSlash && dirRelativeNoSlash !== oldRelative && dirRelativeNoSlash !== dirRelative) {
        searchPatterns.push(dirRelativeNoSlash);
      }
    }

    var replacements = [];
    for (var p = 0; p < searchPatterns.length; p++) {
      var pattern = searchPatterns[p];
      var escapedOld = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      var reStr = '(\\]\\(|src=["\']|^\\[[^\\]]+\\]:\\s+)(' + escapedOld + ')(?:(?:#[^)\\s"\']*|\\?[^)\\s"\']*)*(?=[)\\s"\']))';
      var re = new RegExp(reStr, 'gm');
      var m;
      while ((m = re.exec(pageContent)) !== null) {
        if (_isInExclusionZone(m.index, zones)) continue;
        var start = m.index + m[1].length;
        var end = start + m[2].length;
        replacements.push({ start: start, end: end, replacement: newRelative });
      }
    }
    if (!replacements.length) return pageContent;
    replacements.sort(function (a, b) { return b.start - a.start; });
    var seen = {};
    var result = pageContent;
    for (var i = 0; i < replacements.length; i++) {
      var r = replacements[i];
      var key = r.start + ':' + r.end;
      if (seen[key]) continue;
      seen[key] = true;
      result = result.substring(0, r.start) + r.replacement + result.substring(r.end);
    }
    return result;
  }

  function _doubleRenderCheck(markdownContent, srcPath) {
    if (!markdownContent || typeof markdownContent !== 'string') return true;
    var editor = wysiwygEditor;
    if (!editor || !editor._markdownToHtml || !editor._htmlToMarkdown) {
      return true;
    }
    var prev = _inMemoryRenderMode;
    _inMemoryRenderMode = true;
    try {
      var html1 = editor._markdownToHtml(markdownContent);
      var md = editor._htmlToMarkdown(html1);
      var html2 = editor._markdownToHtml(md);
      var norm = function (s) { return (s || '').replace(/\s+/g, ' ').replace(/\u200B/g, '').replace(/\u200C/g, '').replace(/\u200D/g, '').replace(/\uFEFF/g, '').trim(); };
      var n1 = norm(html1);
      var n2 = norm(html2);
      return n1 === n2;
    } catch (e) {
      return false;
    } finally {
      _inMemoryRenderMode = prev;
    }
  }

  // --- Unified Content Undo DAG ---

  var _historyNodes = {};
  var _historyCurrentId = null;
  var _historyRootMd = null;
  var _historyNextId = 0;
  var _historyTimer = null;
  var _historyLastMd = null;
  var _historyMaxNodes = 200;

  function _historyReset(markdown) {
    _historyNodes = {};
    _historyNextId = 0;
    _historyTimer = null;
    _historyRootMd = markdown;
    _historyLastMd = markdown;
    var rootId = _historyNextId++;
    _historyNodes[rootId] = {
      id: rootId,
      parentId: null,
      children: [],
      activeChildId: null,
      diff: null,
      cursor: null,
      timestamp: Date.now(),
      summary: null
    };
    _historyCurrentId = rootId;
  }

  function _computeLineDiff(oldLines, newLines) {
    var ops = [];
    var oLen = oldLines.length;
    var nLen = newLines.length;
    var o = 0, n = 0;
    while (o < oLen && n < nLen) {
      if (oldLines[o] === newLines[n]) {
        o++; n++;
        continue;
      }
      var oEnd = o, nEnd = n;
      while (oEnd < oLen && (nEnd >= nLen || oldLines[oEnd] !== newLines[nEnd])) {
        oEnd++;
        if (oEnd < oLen) {
          var sync = nEnd;
          while (sync < nLen && newLines[sync] !== oldLines[oEnd]) sync++;
          if (sync < nLen) break;
        }
      }
      while (nEnd < nLen && (oEnd >= oLen || newLines[nEnd] !== oldLines[oEnd])) {
        nEnd++;
        if (nEnd < nLen && oEnd < oLen && newLines[nEnd] === oldLines[oEnd]) break;
      }
      var delCount = oEnd - o;
      var insLines = newLines.slice(n, nEnd);
      if (delCount > 0 && insLines.length > 0) {
        ops.push({ type: 'replace', line: o, count: delCount, old: oldLines.slice(o, oEnd), new: insLines });
      } else if (delCount > 0) {
        ops.push({ type: 'delete', line: o, count: delCount, old: oldLines.slice(o, oEnd) });
      } else if (insLines.length > 0) {
        ops.push({ type: 'insert', afterLine: o, lines: insLines });
      }
      o = oEnd;
      n = nEnd;
    }
    if (o < oLen) {
      ops.push({ type: 'delete', line: o, count: oLen - o, old: oldLines.slice(o) });
    }
    if (n < nLen) {
      ops.push({ type: 'insert', afterLine: o, lines: newLines.slice(n) });
    }
    return ops.length > 0 ? { ops: ops } : null;
  }

  function _applyDiff(lines, diff) {
    if (!diff || !diff.ops) return lines;
    var result = lines.slice();
    var offset = 0;
    for (var i = 0; i < diff.ops.length; i++) {
      var op = diff.ops[i];
      if (op.type === 'replace') {
        var args = [op.line + offset, op.count].concat(op.new);
        Array.prototype.splice.apply(result, args);
        offset += op.new.length - op.count;
      } else if (op.type === 'insert') {
        var args2 = [op.afterLine + offset, 0].concat(op.lines);
        Array.prototype.splice.apply(result, args2);
        offset += op.lines.length;
      } else if (op.type === 'delete') {
        result.splice(op.line + offset, op.count);
        offset -= op.count;
      }
    }
    return result;
  }

  function _reverseDiff(diff) {
    if (!diff || !diff.ops) return null;
    var rOps = [];
    for (var i = diff.ops.length - 1; i >= 0; i--) {
      var op = diff.ops[i];
      if (op.type === 'replace') {
        rOps.push({ type: 'replace', line: op.line, count: op.new.length, old: op.new, new: op.old });
      } else if (op.type === 'insert') {
        rOps.push({ type: 'delete', line: op.afterLine, count: op.lines.length, old: op.lines });
      } else if (op.type === 'delete') {
        rOps.push({ type: 'insert', afterLine: op.line, lines: op.old });
      }
    }
    return { ops: rOps };
  }

  function _reconstructContentAtNode(nodeId) {
    var path = [];
    var id = nodeId;
    while (id !== null && _historyNodes[id]) {
      path.unshift(id);
      id = _historyNodes[id].parentId;
    }
    if (path.length === 0 || _historyRootMd === null) return null;
    var lines = _historyRootMd.split('\n');
    for (var i = 1; i < path.length; i++) {
      var node = _historyNodes[path[i]];
      if (node && node.diff) {
        lines = _applyDiff(lines, node.diff);
      }
    }
    return lines.join('\n');
  }

  function _generateSummary(diff) {
    if (!diff || !diff.ops || diff.ops.length === 0) return null;
    var totalOld = 0, totalNew = 0;
    for (var i = 0; i < diff.ops.length; i++) {
      var op = diff.ops[i];
      if (op.type === 'replace') { totalOld += op.count; totalNew += op.new.length; }
      else if (op.type === 'insert') { totalNew += op.lines.length; }
      else if (op.type === 'delete') { totalOld += op.count; }
    }
    if (diff.ops.length === 1) {
      var singleOp = diff.ops[0];
      var newLines = singleOp.type === 'replace' ? singleOp.new : (singleOp.type === 'insert' ? singleOp.lines : []);
      var oldLines = singleOp.old || [];
      if (newLines.length > 0) {
        var first = newLines[0];
        if (/^```/.test(first) && newLines.length > 1) return 'inserted code block';
        if (/^#{1,6}\s/.test(first)) return 'changed heading';
        if (/^(!{3}|\?{3}\+?)\s/.test(first)) return 'inserted admonition';
        if (/^>\s/.test(first) && newLines.length > 1) return 'inserted blockquote';
        if (/^(\s*[-*+]|\s*\d+\.)\s/.test(first) && newLines.length > 1) return 'added list items';
        if (/^(---|___|\*\*\*)\s*$/.test(first)) return 'inserted horizontal rule';
      }
      if (singleOp.type === 'delete') {
        if (oldLines.length > 0 && /^```/.test(oldLines[0]) && oldLines.length > 1) return 'removed code block';
        if (oldLines.length > 0 && /^#{1,6}\s/.test(oldLines[0])) return 'removed heading';
      }
      if (singleOp.type === 'replace' && singleOp.count === 1 && newLines.length === 1) {
        return 'edited line ' + (singleOp.line + 1);
      }
    }
    var total = totalOld + totalNew;
    return 'edited ' + total + ' line' + (total !== 1 ? 's' : '');
  }

  function _groupMarkdownConstructs(diff, newLines) {
    if (!diff || !diff.ops || diff.ops.length === 0) return diff;
    var grouped = [];
    for (var i = 0; i < diff.ops.length; i++) {
      var op = diff.ops[i];
      if (op.type === 'insert' && op.lines.length > 1) {
        var first = op.lines[0];
        var last = op.lines[op.lines.length - 1];
        if (/^```/.test(first) && /^```\s*$/.test(last)) {
          grouped.push(op);
          continue;
        }
        if (/^(!{3}|\?{3}\+?)\s/.test(first)) {
          grouped.push(op);
          continue;
        }
      }
      grouped.push(op);
    }
    return { ops: grouped };
  }

  function _createHistoryNode(markdown, cursor) {
    if (_historyLastMd === null || _historyCurrentId === null) return;
    if (markdown === _historyLastMd) return;

    if (!_doubleRenderCheck(markdown)) {
      console.log('[UNDO] history capture skipped: double-render corruption detected');
      return;
    }

    var oldLines = _historyLastMd.split('\n');
    var newLines = markdown.split('\n');
    var diff = _computeLineDiff(oldLines, newLines);
    if (!diff) return;

    diff = _groupMarkdownConstructs(diff, newLines);
    var summary = _generateSummary(diff);

    var nodeId = _historyNextId++;
    var node = {
      id: nodeId,
      parentId: _historyCurrentId,
      children: [],
      activeChildId: null,
      diff: diff,
      cursor: cursor || null,
      timestamp: Date.now(),
      summary: summary
    };
    _historyNodes[nodeId] = node;

    var parent = _historyNodes[_historyCurrentId];
    if (parent) {
      parent.children.push(nodeId);
      parent.activeChildId = nodeId;
    }

    _historyCurrentId = nodeId;
    _historyLastMd = markdown;

    _historyPrune();
  }

  function _historyPrune() {
    var ids = Object.keys(_historyNodes);
    if (ids.length <= _historyMaxNodes) return;

    var onPath = {};
    var id = _historyCurrentId;
    while (id !== null && _historyNodes[id]) {
      onPath[id] = true;
      id = _historyNodes[id].parentId;
    }

    var leaves = [];
    for (var i = 0; i < ids.length; i++) {
      var nid = parseInt(ids[i], 10);
      var n = _historyNodes[nid];
      if (n.children.length === 0 && !onPath[nid]) {
        leaves.push(nid);
      }
    }
    leaves.sort(function (a, b) { return a - b; });

    var toRemove = ids.length - _historyMaxNodes;
    for (var j = 0; j < leaves.length && toRemove > 0; j++) {
      var leafId = leaves[j];
      var leafNode = _historyNodes[leafId];
      if (leafNode && leafNode.parentId !== null) {
        var p = _historyNodes[leafNode.parentId];
        if (p) {
          var ci = p.children.indexOf(leafId);
          if (ci !== -1) p.children.splice(ci, 1);
          if (p.activeChildId === leafId) {
            p.activeChildId = p.children.length > 0 ? p.children[p.children.length - 1] : null;
          }
        }
      }
      delete _historyNodes[leafId];
      toRemove--;
    }
  }

  function _getHistoryBranchPoints() {
    var points = [];
    var ids = Object.keys(_historyNodes);
    for (var i = 0; i < ids.length; i++) {
      var n = _historyNodes[ids[i]];
      if (n.children.length > 1) points.push(n);
    }
    return points;
  }

  function _getHistoryBranches(nodeId) {
    var node = _historyNodes[nodeId];
    if (!node) return [];
    var branches = [];
    for (var i = 0; i < node.children.length; i++) {
      var childId = node.children[i];
      var child = _historyNodes[childId];
      if (!child) continue;
      var depth = 0;
      var queue = [childId];
      while (queue.length > 0) {
        var cid = queue.shift();
        depth++;
        var cn = _historyNodes[cid];
        if (cn) {
          for (var j = 0; j < cn.children.length; j++) queue.push(cn.children[j]);
        }
      }
      branches.push({
        childId: childId,
        summary: child.summary,
        timestamp: child.timestamp,
        depth: depth
      });
    }
    return branches;
  }

  function _switchHistoryBranch(nodeId, childId) {
    var node = _historyNodes[nodeId];
    if (!node) return false;
    if (node.children.indexOf(childId) === -1) return false;
    node.activeChildId = childId;
    return true;
  }

  function _estimateMdOffsetFromWysiwyg(ea) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0 || !ea) return 0;
    var range = sel.getRangeAt(0);
    if (!ea.contains(range.startContainer)) return 0;
    var preRange = document.createRange();
    preRange.setStart(ea, 0);
    preRange.setEnd(range.startContainer, range.startOffset);
    var textBefore = preRange.toString();
    preRange.detach();
    return textBefore.length;
  }

  function _captureHistoryCursor() {
    if (!wysiwygEditor) return null;
    if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
      return {
        mode: 'markdown',
        start: wysiwygEditor.markdownArea.selectionStart,
        end: wysiwygEditor.markdownArea.selectionEnd,
        semantic: null
      };
    }
    if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
      var mdOffset = _estimateMdOffsetFromWysiwyg(wysiwygEditor.editableArea);
      return {
        mode: 'wysiwyg',
        start: mdOffset,
        end: mdOffset,
        semantic: captureSemanticSelection(wysiwygEditor.editableArea)
      };
    }
    return null;
  }

  function _diffToMdOffset(diff, mdContent, isRedo) {
    if (!diff || !diff.ops || diff.ops.length === 0 || !mdContent) return mdContent ? mdContent.length : 0;
    var lines = mdContent.split('\n');
    var endLine = 0;
    if (isRedo) {
      var shift = 0;
      for (var i = 0; i < diff.ops.length; i++) {
        var op = diff.ops[i];
        if (op.type === 'replace') {
          endLine = op.line + shift + op.new.length - 1;
          shift += op.new.length - op.count;
        } else if (op.type === 'insert') {
          endLine = op.afterLine + shift + op.lines.length - 1;
          shift += op.lines.length;
        } else if (op.type === 'delete') {
          endLine = Math.max(0, op.line + shift - 1);
          shift -= op.count;
        }
      }
    } else {
      var lastOp = diff.ops[diff.ops.length - 1];
      if (lastOp.type === 'replace') {
        endLine = lastOp.line + lastOp.count - 1;
      } else if (lastOp.type === 'insert') {
        endLine = Math.max(0, lastOp.afterLine - 1);
      } else if (lastOp.type === 'delete') {
        endLine = lastOp.line + lastOp.count - 1;
      }
    }
    endLine = Math.max(0, Math.min(endLine, lines.length - 1));
    var offset = 0;
    for (var j = 0; j < endLine; j++) {
      offset += lines[j].length + 1;
    }
    offset += lines[endLine].length;
    return Math.min(offset, mdContent.length);
  }

  function _placeCursorAtMdOffset(mdOffset, mdContent) {
    if (!wysiwygEditor) return;
    if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
      var ma = wysiwygEditor.markdownArea;
      var pos = Math.min(mdOffset, ma.value.length);
      ma.focus();
      ma.setSelectionRange(pos, pos);
    } else if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
      var ea = wysiwygEditor.editableArea;
      ea.focus();
      var walker = document.createTreeWalker(ea, NodeFilter.SHOW_TEXT, null, false);
      var n, pos2 = 0, lastNode = null, lastLen = 0;
      while ((n = walker.nextNode())) {
        lastNode = n;
        lastLen = n.textContent.length;
        if (pos2 + lastLen >= mdOffset) {
          var off = Math.min(mdOffset - pos2, lastLen);
          var range = document.createRange();
          range.setStart(n, off);
          range.collapse(true);
          var sel = window.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
          return;
        }
        pos2 += lastLen;
      }
      if (lastNode) {
        var range2 = document.createRange();
        range2.setStart(lastNode, lastLen);
        range2.collapse(true);
        var sel2 = window.getSelection();
        sel2.removeAllRanges();
        sel2.addRange(range2);
      }
    }
  }

  function _restoreHistoryCursor(cursor, diff, mdContent, isRedo) {
    if (!wysiwygEditor) return;
    if (diff && mdContent) {
      var offset = _diffToMdOffset(diff, mdContent, isRedo);
      _placeCursorAtMdOffset(offset, mdContent);
      return;
    }
    var sameMode = cursor && cursor.mode === wysiwygEditor.currentMode;
    if (sameMode && cursor.mode === 'markdown' && wysiwygEditor.markdownArea) {
      var ma = wysiwygEditor.markdownArea;
      var s = Math.min(cursor.start, ma.value.length);
      var e = Math.min(cursor.end, ma.value.length);
      ma.focus();
      ma.setSelectionRange(s, e);
      return;
    }
    if (sameMode && cursor.mode === 'wysiwyg' && wysiwygEditor.editableArea) {
      if (cursor.semantic) {
        wysiwygEditor.editableArea.focus();
        if (restoreSelectionFromSemantic(wysiwygEditor.editableArea, cursor.semantic)) return;
      }
    }
    if (cursor && cursor.start !== undefined && mdContent) {
      _placeCursorAtMdOffset(cursor.start, mdContent);
      return;
    }
    if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
      wysiwygEditor.markdownArea.focus();
      wysiwygEditor.markdownArea.setSelectionRange(0, 0);
    } else if (wysiwygEditor.editableArea) {
      wysiwygEditor.editableArea.focus();
    }
  }

  function _flushHistoryCapture() {
    if (_historyTimer !== null) {
      clearTimeout(_historyTimer);
      _historyTimer = null;
    }
    if (!wysiwygEditor) return;
    var md = wysiwygEditor.getValue();
    if (md && md !== _historyLastMd) {
      _createHistoryNode(md, _captureHistoryCursor());
    }
  }

  function _scheduleHistoryCapture(immediate) {
    if (_historyTimer !== null) {
      clearTimeout(_historyTimer);
      _historyTimer = null;
    }
    if (immediate) {
      _flushHistoryCapture();
      return;
    }
    _historyTimer = setTimeout(function () {
      _historyTimer = null;
      _flushHistoryCapture();
    }, 500);
  }

  function _contentUndo() {
    if (_historyCurrentId === null) return;
    var current = _historyNodes[_historyCurrentId];
    if (!current || current.parentId === null) return;

    _flushHistoryCapture();

    current = _historyNodes[_historyCurrentId];
    if (!current || current.parentId === null) return;

    var undoDiff = current.diff;
    var parentMd = _reconstructContentAtNode(current.parentId);
    if (parentMd === null) return;

    var parent = _historyNodes[current.parentId];
    _historyCurrentId = current.parentId;
    _historyLastMd = parentMd;

    _historySetContent(parentMd);
    _restoreHistoryCursor(parent ? parent.cursor : null, undoDiff, parentMd, false);
  }

  function _contentRedo() {
    if (_historyCurrentId === null) return;
    var current = _historyNodes[_historyCurrentId];
    if (!current || !current.activeChildId) return;

    var child = _historyNodes[current.activeChildId];
    if (!child) return;

    var childMd = _reconstructContentAtNode(child.id);
    if (childMd === null) return;

    _historyCurrentId = child.id;
    _historyLastMd = childMd;

    _historySetContent(childMd);
    _restoreHistoryCursor(child.cursor, child.diff, childMd, true);
  }

  function _historySetContent(markdown) {
    if (!wysiwygEditor || !wysiwygEditor._historyApplyContent) return;
    wysiwygEditor._historyApplyContent(markdown);
  }

  // --- End Unified Content Undo DAG ---

  function _fetchLinkIndex() {
    if (typeof liveWysiwygLinkCheckPort === 'undefined' || !liveWysiwygLinkCheckPort) {
      var fallback = typeof liveWysiwygLinkIndex !== 'undefined' ? liveWysiwygLinkIndex : {};
      return Promise.resolve(fallback);
    }
    var host = window.location.hostname || '127.0.0.1';
    var url = 'http://' + host + ':' + liveWysiwygLinkCheckPort + '/link-index';
    return fetch(url).then(function (resp) {
      if (!resp.ok) throw new Error('HTTP ' + resp.status);
      return resp.json();
    }).then(function (idx) {
      return idx;
    }).catch(function (err) {
      return typeof liveWysiwygLinkIndex !== 'undefined' ? liveWysiwygLinkIndex : {};
    });
  }

  function _updateLinkIndexForMove(oldPath, newPath) {
    var idx = _batchLinkIndex;
    if (!idx || typeof idx !== 'object') return;

    var oldRefs = idx[oldPath];
    var newRefs = [];
    if (Array.isArray(oldRefs)) {
      var oldDir = _getDir(oldPath);
      var newDir = _getDir(newPath);
      for (var r = 0; r < oldRefs.length; r++) {
        var oRef = oldRefs[r];
        if (!oRef || !oRef.target) continue;
        var absTarget = _resolvePath(oldDir, oRef.target);
        if (absTarget === null) { newRefs.push({ target: oRef.target }); continue; }
        newRefs.push({ target: _computeRelativePath(newDir, absTarget) });
      }
    }

    delete idx[oldPath];
    idx[newPath] = newRefs;

    var oldPathBase = oldPath.replace(/\.md$/, '');
    var isIndex = oldPath.endsWith('/index.md') || oldPath === 'index.md';
    var oldDirForm = isIndex ? _getDir(oldPath) : null;
    for (var srcPath in idx) {
      if (!Object.prototype.hasOwnProperty.call(idx, srcPath)) continue;
      if (srcPath === newPath) continue;
      var refs = idx[srcPath];
      if (!Array.isArray(refs)) continue;
      var pageDir = _getDir(srcPath);
      var newRelative = _computeRelativePath(pageDir, newPath);
      for (var i = 0; i < refs.length; i++) {
        var ref = refs[i];
        var target = ref && ref.target;
        if (!target) continue;
        var absRef = _resolvePath(pageDir, target);
        if (absRef === null) continue;
        var absRefBase = absRef.replace(/\.md$/, '');
        if (absRefBase === oldPathBase || absRef === oldPath || absRef === oldPathBase || absRefBase === oldPath.replace(/\.md$/, '')) {
          ref.target = newRelative;
        } else if (oldDirForm && (absRef === oldDirForm || absRef === oldDirForm + '/')) {
          ref.target = newRelative;
        }
      }
    }
  }

  function _rewriteInboundLinks(oldPath, newPath, linkIndex) {
    if (!linkIndex || typeof linkIndex !== 'object') {
      return Promise.resolve();
    }
    var oldPathBase = oldPath.replace(/\.md$/, '');
    var isIndex = oldPath.endsWith('/index.md') || oldPath === 'index.md';
    var oldDirForm = isIndex ? _getDir(oldPath) : null;
    var pagesToUpdate = [];
    for (var srcPath in linkIndex) {
      if (!Object.prototype.hasOwnProperty.call(linkIndex, srcPath)) continue;
      var refs = linkIndex[srcPath];
      if (!Array.isArray(refs)) continue;
      var pageDir = _getDir(srcPath);
      for (var i = 0; i < refs.length; i++) {
        var ref = refs[i];
        var target = ref && ref.target;
        if (!target) continue;
        var absTarget = _resolvePath(pageDir, target);
        if (absTarget === null) continue;
        var absTargetBase = absTarget.replace(/\.md$/, '');
        if (absTargetBase === oldPathBase || absTarget === oldPath || absTarget === oldPathBase || absTargetBase === oldPath.replace(/\.md$/, '')) {
          pagesToUpdate.push(srcPath);
          break;
        }
        if (oldDirForm && (absTarget === oldDirForm || absTarget === oldDirForm + '/')) {
          pagesToUpdate.push(srcPath);
          break;
        }
      }
    }
    var chain = Promise.resolve();
    pagesToUpdate.forEach(function (pagePath) {
      chain = chain.then(function () {
        var actualPagePath = _resolveChainedRename(pagePath);
        if (_batchDeletedPaths[actualPagePath]) {
          return;
        }
        return _wsGetContents(actualPagePath).then(function (content) {
          var updated = _rewriteInboundLinksInPage(content, oldPath, newPath, actualPagePath);
          return _wsSetContents(actualPagePath, updated);
        }).catch(function (err) {
          console.error('[rewrite-inbound] FAILED for', pagePath, ':', err);
          _addCautionPage(pagePath, 'Failed to rewrite inbound links after a referenced document was moved');
        });
      });
    });
    return chain;
  }

  // ======================================================================
  // NAV MENU - Status overlay / progress helpers
  // ======================================================================
  function _showNavStatus(container, text, options) {
    options = options || {};
    var el = container.querySelector('.live-wysiwyg-nav-status');
    if (!el) {
      el = document.createElement('div');
      el.className = 'live-wysiwyg-nav-status';
      if (!container.style.position || container.style.position === 'static') {
        container.style.position = 'relative';
      }
      container.appendChild(el);
    }
    el.innerHTML = '';
    if (!options.hideSpinner) {
      var spinner = document.createElement('div');
      spinner.className = 'live-wysiwyg-nav-status-icon';
      el.appendChild(spinner);
    }
    var textEl = document.createElement('div');
    textEl.className = 'live-wysiwyg-nav-status-text';
    textEl.textContent = text;
    el.appendChild(textEl);
    if (options.showProgress) {
      var bar = document.createElement('div');
      bar.className = 'live-wysiwyg-nav-progress-bar' + (options.indeterminate ? ' live-wysiwyg-nav-progress-indeterminate' : '');
      var fill = document.createElement('div');
      fill.className = 'live-wysiwyg-nav-progress-fill';
      if (options.percent !== undefined) fill.style.width = options.percent + '%';
      bar.appendChild(fill);
      el.appendChild(bar);
    }
    if (options.detail) {
      var detail = document.createElement('div');
      detail.className = 'live-wysiwyg-nav-status-detail';
      detail.textContent = options.detail;
      el.appendChild(detail);
    }
    if (options.showCheckBtn) {
      var checkBtn = document.createElement('button');
      checkBtn.className = 'live-wysiwyg-nav-check-btn';
      checkBtn.textContent = 'Check now';
      checkBtn.disabled = true;
      setTimeout(function () { checkBtn.disabled = false; }, 10000);
      checkBtn.addEventListener('click', function () {
        if (options.onCheck) options.onCheck();
      });
      el.appendChild(checkBtn);
    }
    return el;
  }

  function _removeNavStatus(container) {
    var el = container ? container.querySelector('.live-wysiwyg-nav-status') : null;
    if (el && el.parentNode) el.parentNode.removeChild(el);
  }

  function _updateNavProgress(container, percent, detail) {
    var fill = container.querySelector('.live-wysiwyg-nav-progress-fill');
    if (fill) fill.style.width = percent + '%';
    var detailEl = container.querySelector('.live-wysiwyg-nav-status-detail');
    if (detailEl && detail) detailEl.textContent = detail;
  }

  // ======================================================================
  // NAV MENU - Confirmation dialog
  // ======================================================================
  function _showNavDialog(message, buttons, extraEls) {
    return new Promise(function (resolve) {
      var resolved = false;
      function finish(val) { if (resolved) return; resolved = true; overlay.parentNode.removeChild(overlay); resolve(val); }
      var overlay = document.createElement('div');
      overlay.className = 'live-wysiwyg-nav-dialog';
      var content = document.createElement('div');
      content.className = 'live-wysiwyg-nav-dialog-content';
      var p = document.createElement('p');
      p.textContent = message;
      content.appendChild(p);
      if (extraEls) {
        for (var ei = 0; ei < extraEls.length; ei++) {
          content.appendChild(extraEls[ei]);
        }
      }
      var actions = document.createElement('div');
      actions.className = 'live-wysiwyg-nav-dialog-actions';
      var primaryValue = null;
      var dangerValue = null;
      var primaryBtn = null;
      var dangerBtn = null;
      var tabIdx = 1;
      buttons.forEach(function (btn) {
        var b = document.createElement('button');
        b.textContent = btn.text;
        b.tabIndex = tabIdx++;
        if (btn.className) b.className += ' ' + btn.className;
        if (btn.className && btn.className.indexOf('live-wysiwyg-nav-dialog-primary') >= 0) {
          primaryValue = btn.value; primaryBtn = b;
        }
        if (btn.className && btn.className.indexOf('live-wysiwyg-nav-dialog-danger') >= 0) {
          dangerValue = btn.value; dangerBtn = b;
        }
        b.addEventListener('click', function () { finish(btn.value); });
        actions.appendChild(b);
      });
      content.appendChild(actions);
      overlay.appendChild(content);
      var confirmValue = primaryValue || dangerValue || (buttons.length ? buttons[0].value : null);
      var focusBtn = primaryBtn || dangerBtn || actions.firstChild;
      _attachDialogKeyboard(overlay, {
        category: 'confirmation',
        onDismiss: function () { finish(null); },
        onConfirm: confirmValue != null ? function () { finish(confirmValue); } : null,
        autoFocus: focusBtn
      });
      document.body.appendChild(overlay);
    });
  }

  function _showNavDialogHtml(htmlContent, buttons) {
    return new Promise(function (resolve) {
      var resolved = false;
      function finish(val) { if (resolved) return; resolved = true; overlay.parentNode.removeChild(overlay); resolve(val); }
      var overlay = document.createElement('div');
      overlay.className = 'live-wysiwyg-nav-dialog';
      var content = document.createElement('div');
      content.className = 'live-wysiwyg-nav-dialog-content';
      content.style.maxWidth = '520px';
      var body = document.createElement('div');
      body.innerHTML = htmlContent;
      body.style.maxHeight = '50vh';
      body.style.overflowY = 'auto';
      body.style.fontSize = '.85rem';
      body.style.lineHeight = '1.5';
      body.style.marginBottom = '16px';
      content.appendChild(body);
      var actions = document.createElement('div');
      actions.className = 'live-wysiwyg-nav-dialog-actions';
      var primaryValue = null;
      var dangerValue = null;
      var primaryBtn = null;
      var dangerBtn = null;
      var tabIdx = 1;
      buttons.forEach(function (btn) {
        var b = document.createElement('button');
        b.textContent = btn.text;
        b.tabIndex = tabIdx++;
        if (btn.className) b.className += ' ' + btn.className;
        if (btn.className && btn.className.indexOf('live-wysiwyg-nav-dialog-primary') >= 0) {
          primaryValue = btn.value; primaryBtn = b;
        }
        if (btn.className && btn.className.indexOf('live-wysiwyg-nav-dialog-danger') >= 0) {
          dangerValue = btn.value; dangerBtn = b;
        }
        b.addEventListener('click', function () { finish(btn.value); });
        actions.appendChild(b);
      });
      content.appendChild(actions);
      overlay.appendChild(content);
      var confirmValue = primaryValue || dangerValue || (buttons.length ? buttons[0].value : null);
      var focusBtn = primaryBtn || dangerBtn || actions.firstChild;
      _attachDialogKeyboard(overlay, {
        category: 'confirmation',
        onDismiss: function () { finish(null); },
        onConfirm: confirmValue != null ? function () { finish(confirmValue); } : null,
        autoFocus: focusBtn
      });
      document.body.appendChild(overlay);
    });
  }

  // ======================================================================
  // NAV MENU - Toast notification
  // ======================================================================
  function _showToast(message, duration) {
    duration = duration || 5000;
    var toast = document.createElement('div');
    toast.className = 'live-wysiwyg-toast';
    var text = document.createElement('span');
    text.textContent = message;
    toast.appendChild(text);
    var closeBtn = document.createElement('button');
    closeBtn.className = 'live-wysiwyg-toast-close';
    closeBtn.textContent = '\u00D7';
    closeBtn.addEventListener('click', function () { dismiss(); });
    toast.appendChild(closeBtn);
    document.body.appendChild(toast);
    requestAnimationFrame(function () {
      requestAnimationFrame(function () { toast.classList.add('live-wysiwyg-toast--visible'); });
    });
    var timer = setTimeout(dismiss, duration);
    function dismiss() {
      clearTimeout(timer);
      toast.classList.remove('live-wysiwyg-toast--visible');
      setTimeout(function () { if (toast.parentNode) toast.parentNode.removeChild(toast); }, 300);
    }
  }

  // ======================================================================
  // NAV MENU - Build nav tree in sidebar
  // ======================================================================
  function _isMaterialThemeDetected() {
    var cs = getComputedStyle(document.documentElement);
    return !!cs.getPropertyValue('--md-primary-fg-color').trim() || !!document.querySelector('.md-header');
  }

  function _buildNavMenu(sidebarEl) {
    if (!sidebarEl) return;
    if (typeof liveWysiwygNavData === 'undefined' || !liveWysiwygNavData.length) return;
    _isMaterialTheme = _isMaterialThemeDetected();
    if (!_isMaterialTheme) return;

    sidebarEl.innerHTML = '';
    _navSidebarEl = sidebarEl;

    var nav = document.createElement('nav');
    nav.className = 'md-nav md-nav--primary';
    nav.setAttribute('aria-label', 'Navigation');

    var navTitle = document.createElement('label');
    navTitle.className = 'md-nav__title';

    var hiddenCb = document.createElement('input');
    hiddenCb.type = 'checkbox';
    hiddenCb.className = 'live-wysiwyg-nav-hidden-cb';
    hiddenCb.title = 'Show hidden files';
    hiddenCb.checked = _getSetting('live_wysiwyg_show_hidden') === '1';
    hiddenCb.addEventListener('change', function () {
      _setSetting('live_wysiwyg_show_hidden', this.checked ? '1' : '0');
      _renderNavFromSnapshot();
    });
    navTitle.appendChild(hiddenCb);

    var siteTitle = document.title ? document.title.split(' - ').pop().trim() : 'Navigation';
    navTitle.appendChild(document.createTextNode(siteTitle));
    nav.appendChild(navTitle);

    var ul = document.createElement('ul');
    ul.className = 'md-nav__list';
    _navMaxWeight = 0;
    _buildNavItems(ul, liveWysiwygNavData, 0);
    nav.appendChild(ul);

    var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
    if (nwCfg.enabled && _navMaxWeight > 0 && !_navMigrationPending) {
      var defWeight = nwCfg.default_page_weight !== undefined ? nwCfg.default_page_weight : 1000;
      if (_navMaxWeight > defWeight) {
        var suggested = Math.ceil((_navMaxWeight + 500) / 1000) * 1000;
        if (!_hasNavTopWarning('weight-exceeds-default')) {
          _navTopWarnings.push({
            id: 'weight-exceeds-default',
            text: 'Page weights in content are higher than default page weight. Increase default_page_weight to ' + suggested + '?',
            icon: 'caution',
            title: 'Page weights exceed default',
            actionId: 'apply-default-weight',
            actionText: 'Apply to mkdocs.yml',
            _suggestedWeight: suggested
          });
          _ensureNavUncollapsed();
        }
      } else {
        _removeNavTopWarning('weight-exceeds-default');
      }
    } else {
      _removeNavTopWarning('weight-exceeds-default');
    }

    for (var tw = 0; tw < _navTopWarnings.length; tw++) {
      (function (warn) {
        var warnIcon = document.createElement('span');
        warnIcon.className = 'live-wysiwyg-nav-' + (warn.icon || 'caution');
        warnIcon.textContent = '\u26A0';
        warnIcon.title = warn.title || '';
        warnIcon.addEventListener('click', function (e) {
          e.preventDefault();
          e.stopPropagation();
          var actions = [];
          if (warn.actionId && _navTopWarningActions[warn.actionId]) {
            actions.push({
              text: warn.actionText || 'Apply',
              primary: true,
              action: function () { _navTopWarningActions[warn.actionId](warn); }
            });
          }
          _showNavPopup(warnIcon, warn.text, actions);
        });
        navTitle.appendChild(warnIcon);
      })(_navTopWarnings[tw]);
    }

    var scrollWrap = document.createElement('div');
    scrollWrap.className = 'live-wysiwyg-nav-scroll-wrap';
    scrollWrap.appendChild(nav);
    sidebarEl.appendChild(scrollWrap);
    _navScrollWrap = scrollWrap;

    if (_hasAnyNavSelected()) {
      sidebarEl.classList.add('live-wysiwyg-nav-group-active');
    } else {
      sidebarEl.classList.remove('live-wysiwyg-nav-group-active');
    }

    requestAnimationFrame(function () { _alignAllNavControls(); });

    sidebarEl.addEventListener('mouseleave', function () {});

  }

  // ======================================================================
  // NAV MENU - Detect hidden index pages (removed from nav by plugins)
  // ======================================================================

  function _collectSectionsNeedingIndexCheck(items, out) {
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.type !== 'section') continue;
      if (!item.src_path && !item.index_meta) {
        var hasIndexChild = item.children && item.children.some(function (c) {
          return c.type === 'page' && c.isIndex;
        });
        if (!hasIndexChild) {
          var dir = _getSectionFolderDir(item) || '';
          if (dir) out.push({ item: item, indexPath: dir + '/index.md' });
        }
      }
      if (item.children) _collectSectionsNeedingIndexCheck(item.children, out);
    }
  }

  // ======================================================================
  // NAV MENU - Hidden (headless) page detection & insertion
  // ======================================================================

  function _collectNavTreePaths(items, out) {
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if ((item.type === 'page' || item.type === 'asset') && item.src_path) out[item.src_path] = true;
      if (item.type === 'section') {
        if (item.src_path) out[item.src_path] = true;
        if (item.children) _collectNavTreePaths(item.children, out);
      }
    }
  }

  function _buildFileLayoutFromNav(deletedDirs) {
    var layout = {};
    var excluded = {};
    var navData = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item._deleted) {
          if (item.src_path) excluded[item.src_path] = true;
          continue;
        }
        if (item.src_path) layout[item.src_path] = true;
        if (item.type === 'section' && item.children) {
          var dir = _getDir(item.src_path || '');
          if (dir) layout[dir] = true;
          walk(item.children);
        }
      }
    })(navData);
    if (deletedDirs) {
      for (var d = 0; d < deletedDirs.length; d++) {
        var prefix = deletedDirs[d] + '/';
        excluded['__dir__' + deletedDirs[d]] = prefix;
      }
    }
    var allPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
    for (var i = 0; i < allPaths.length; i++) {
      var p = allPaths[i];
      if (excluded[p]) continue;
      var skip = false;
      for (var key in excluded) {
        if (key.indexOf('__dir__') === 0 && p.indexOf(excluded[key]) === 0) { skip = true; break; }
      }
      if (!skip) layout[p] = true;
    }
    return Object.keys(layout);
  }

  function _titleFromSrcPath(srcPath) {
    var name = srcPath.split('/').pop().replace(/\.md$/, '');
    if (name === 'index') {
      var parts = srcPath.split('/');
      name = parts.length > 1 ? parts[parts.length - 2] : 'Index';
    }
    return name.replace(/[-_]/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
  }

  function _precomputeHiddenPages() {
    return new Promise(function (resolve) {
      if (_navHiddenPagesPrecomputed) { resolve(); return; }
      if (typeof liveWysiwygLinkCheckPort === 'undefined' || !liveWysiwygLinkCheckPort) { _navHiddenPagesPrecomputed = true; resolve(); return; }
      if (typeof liveWysiwygAllMdSrcPaths === 'undefined') { _navHiddenPagesPrecomputed = true; resolve(); return; }
      if (typeof liveWysiwygNavData === 'undefined' || !liveWysiwygNavData.length) { _navHiddenPagesPrecomputed = true; resolve(); return; }

      var inNav = {};
      _collectNavTreePaths(liveWysiwygNavData, inNav);
      var hiddenPaths = [];
      for (var i = 0; i < liveWysiwygAllMdSrcPaths.length; i++) {
        var p = liveWysiwygAllMdSrcPaths[i];
        if (!inNav[p]) hiddenPaths.push(p);
      }

      var sectionIndexNeeds = [];
      _collectSectionsNeedingIndexCheck(liveWysiwygNavData, sectionIndexNeeds);
      var sectionIndexPaths = sectionIndexNeeds.map(function (n) { return n.indexPath; });

      var sectionIndexSet = {};
      for (var si2 = 0; si2 < sectionIndexPaths.length; si2++) {
        sectionIndexSet[sectionIndexPaths[si2]] = true;
      }
      hiddenPaths = hiddenPaths.filter(function (hp) { return !sectionIndexSet[hp]; });

      var allPaths = hiddenPaths.concat(sectionIndexPaths);
      if (!allPaths.length) {
        _navHiddenPagesPrecomputed = true;
        resolve();
        return;
      }

      var host = window.location.hostname || '127.0.0.1';
      var url = 'http://' + host + ':' + liveWysiwygLinkCheckPort + '/file-exists';
      fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ paths: allPaths })
      }).then(function (resp) {
        if (!resp.ok) throw new Error('HTTP ' + resp.status);
        return resp.json();
      }).then(function (data) {
        var results = data.results || {};

        for (var si = 0; si < sectionIndexNeeds.length; si++) {
          var entry = sectionIndexNeeds[si];
          var info = results[entry.indexPath];
          if (!info || !info.exists) continue;
          var meta = info.meta || {};
          entry.item.src_path = entry.indexPath;
          entry.item.index_meta = {
            weight: meta.weight != null ? meta.weight : null,
            headless: meta.headless || null,
            retitled: meta.retitled || null,
            empty: meta.empty || null
          };
        }

        for (var h = 0; h < hiddenPaths.length; h++) {
          var srcPath = hiddenPaths[h];
          var hInfo = results[srcPath];
          if (!hInfo || !hInfo.exists) continue;
          var hMeta = hInfo.meta || {};
          var isIndex = srcPath.endsWith('index.md');
          var title = hMeta.title || _titleFromSrcPath(srcPath);
          var dir = _getDir(srcPath);

          var syntheticItem = {
            type: 'page',
            title: title,
            src_path: srcPath,
            url: isIndex ? (dir ? dir + '/' : '') : srcPath.replace(/\.md$/, '/'),
            isIndex: isIndex,
            weight: hMeta.weight != null ? hMeta.weight : null,
            headless: true,
            retitled: hMeta.retitled || null,
            empty: hMeta.empty || null,
            _fm: Object.assign({}, hMeta)
          };

          var targetItems = _ensureSectionForDir(dir);
          if (isIndex && targetItems.length) {
            targetItems.splice(0, 0, syntheticItem);
          } else {
            targetItems.push(syntheticItem);
          }
        }

        _navHiddenPagesPrecomputed = true;
        resolve();
      }).catch(function () {
        _navHiddenPagesPrecomputed = true;
        resolve();
      });
    });
  }

  var _navAssetFilesPrecomputed = false;

  function _ensureSectionForDir(dir) {
    if (!dir) return liveWysiwygNavData;
    var existing = _findSectionByDir(liveWysiwygNavData, dir);
    if (existing) return existing.children;

    var parts = dir.split('/');
    var parentItems = liveWysiwygNavData;
    var builtDir = '';
    for (var p = 0; p < parts.length; p++) {
      builtDir = builtDir ? builtDir + '/' + parts[p] : parts[p];
      var found = _findSectionByDir(liveWysiwygNavData, builtDir);
      if (found) {
        parentItems = found.children;
      } else {
        var folderName = parts[p];
        var syntheticSection = {
          type: 'section',
          title: folderName.replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); }),
          children: [],
          _assetOnlySection: true
        };
        parentItems.push(syntheticSection);
        parentItems = syntheticSection.children;
      }
    }
    return parentItems;
  }

  function _precomputeAssetFiles() {
    if (_navAssetFilesPrecomputed) return Promise.resolve();
    _navAssetFilesPrecomputed = true;
    if (typeof liveWysiwygNavData === 'undefined' || !liveWysiwygNavData.length) return Promise.resolve();

    return _apiPost('/list-items', { folder: '', all: true }).then(function (result) {
      var items = (result && result.items) || [];
      var dirsWithMd = {};
      var dirsWithFiles = {};
      for (var i = 0; i < items.length; i++) {
        var entry = items[i];
        if (entry.type !== 'file') continue;
        var entryDir = _getDir(entry.path) || '';
        dirsWithFiles[entryDir] = true;
        if (entry.path.endsWith('.md')) dirsWithMd[entryDir] = true;
      }

      for (var i = 0; i < items.length; i++) {
        var entry = items[i];
        if (entry.type !== 'file' || entry.path.endsWith('.md')) continue;
        var srcPath = entry.path;
        var filename = srcPath.split('/').pop();
        var dir = _getDir(srcPath);
        var dotIdx = filename.lastIndexOf('.');
        var ext = dotIdx > 0 ? filename.substring(dotIdx) : '';

        var assetItem = {
          type: 'asset',
          title: filename,
          src_path: srcPath,
          extension: ext
        };

        var targetItems = _ensureSectionForDir(dir);
        targetItems.push(assetItem);
      }
    }).catch(function (err) {
      console.warn('[precomputeAssetFiles] Failed to fetch file list:', err);
    });
  }

  function _preComputationContentScan() {
    if (typeof liveWysiwygNavData === 'undefined' || !liveWysiwygNavData.length) return Promise.resolve();
    var indexItems = [];
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.type === 'section' && item.children) {
          for (var c = 0; c < item.children.length; c++) {
            var child = item.children[c];
            if (child.type === 'page' && child.isIndex && child.src_path) {
              if (!(child.retitled && child.empty)) {
                indexItems.push(child);
              }
            }
          }
          walk(item.children);
        }
      }
    })(liveWysiwygNavData);
    if (!indexItems.length) return Promise.resolve();
    var promises = indexItems.map(function (item) {
      return _wsGetContents(item.src_path).then(function (content) {
        if (content) item._indexContent = content;
      }).catch(function () {});
    });
    return Promise.all(promises);
  }

  function _findSectionByDir(items, dir) {
    for (var i = 0; i < items.length; i++) {
      if (items[i].type === 'section') {
        var fd = _getSectionFolderDir(items[i]);
        if (fd === dir) return items[i];
        if (items[i].children) {
          var found = _findSectionByDir(items[i].children, dir);
          if (found) return found;
        }
      }
    }
    return null;
  }

  function _findSectionChildren(tree, dir) {
    if (!dir) return tree;
    var sec = _findSectionByDir(tree, dir);
    return sec ? sec.children : null;
  }

  function _ensureSectionForDirIn(tree, dir) {
    if (!dir) return tree;
    var existing = _findSectionByDir(tree, dir);
    if (existing) return existing.children;
    var parts = dir.split('/');
    var parentItems = tree;
    var builtDir = '';
    for (var p = 0; p < parts.length; p++) {
      builtDir = builtDir ? builtDir + '/' + parts[p] : parts[p];
      var found = _findSectionByDir(tree, builtDir);
      if (found) {
        parentItems = found.children;
      } else {
        var folderName = parts[p];
        var syntheticSection = {
          type: 'section',
          title: folderName.replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); }),
          children: [],
          _assetOnlySection: true
        };
        parentItems.push(syntheticSection);
        parentItems = syntheticSection.children;
      }
    }
    return parentItems;
  }

  function _markSubtreeDeleted(item) {
    item._deleted = true;
    if (item.children) {
      for (var i = 0; i < item.children.length; i++) {
        _markSubtreeDeleted(item.children[i]);
      }
    }
  }

  function _isAssetOnlySection(section) {
    if (!section || section.type !== 'section' || !section.children) return false;
    var hasFile = false;
    var hasMd = false;
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        var c = items[i];
        if (c._deleted) continue;
        if (c.type === 'page') { hasMd = true; return; }
        if (c.type === 'asset') hasFile = true;
        if (c.type === 'section' && c.children) walk(c.children);
        if (hasMd) return;
      }
    })(section.children);
    return hasFile && !hasMd;
  }

  function _hasVisibleMdContent(items) {
    for (var i = 0; i < items.length; i++) {
      var c = items[i];
      if (c._deleted) continue;
      if (c.type === 'page' && !c.headless && !c.empty && !c.isIndex) return true;
      if (c.type === 'section' && c.children && _hasVisibleMdContent(c.children)) return true;
    }
    return false;
  }

  function _isSectionAllHidden(section) {
    if (!section || section.type !== 'section' || !section.children) return false;
    var sectionHasIndex = (
      (section.src_path != null && section.src_path !== '') ||
      (section.index_meta != null) ||
      section.children.some(function (c) { return c.type === 'page' && c.isIndex; })
    );
    if (sectionHasIndex) return false;
    return !_hasVisibleMdContent(section.children);
  }

  function _isMovableWithoutNormalization(item, itemType) {
    if (itemType === 'asset') return true;
    if (item.headless || item.empty) return true;
    if (itemType === 'section') return true;
    return false;
  }

  function _buildNavItems(parentUl, items, depth) {
    var currentSrcPath = _getCurrentSrcPath();
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item._deleted) continue;
      var isHiddenPage = item.type === 'page' && (item.headless || item.empty);
      var isHiddenSection = item.type === 'section' && _isSectionAllHidden(item);
      var li = document.createElement('li');
      li.className = 'md-nav__item';
      if (item._uid) li.setAttribute('data-nav-uid', item._uid);

      if (item._renamed) li.classList.add('live-wysiwyg-nav-item--renamed');
      if (item._new) li.classList.add('live-wysiwyg-nav-item--new');
      if (item._focused) li.classList.add('live-wysiwyg-nav-item--focused');
      if (item._selected) li.classList.add('live-wysiwyg-nav-item--selected');
      if (isHiddenPage) {
        li.classList.add('live-wysiwyg-nav-hidden-page');
        var showHidden = _getSetting('live_wysiwyg_show_hidden') === '1';
        var isCurrentPage = item.src_path === _getCurrentSrcPath();
        if (isCurrentPage) {
          li.classList.add('live-wysiwyg-nav-hidden-page--current');
        } else if (!showHidden) {
          li.style.display = 'none';
        }
      }
      if (isHiddenSection) {
        li.classList.add('live-wysiwyg-nav-hidden-page');
        var showHiddenForSection = _getSetting('live_wysiwyg_show_hidden') === '1';
        if (!showHiddenForSection) {
          li.style.display = 'none';
        }
      }

      (function (liEl) {
        liEl.addEventListener('mouseenter', function (e) {
          e.stopPropagation();
        });
      })(li);

      if (item.type === 'section') {
        li.classList.add('md-nav__item--nested');

        var hasCurrentPage = false;
        if (item.children && item.children.length) {
          hasCurrentPage = item.children.some(function findCurrent(c) {
            if (c.type === 'page' && c.src_path === currentSrcPath) return true;
            if (c.children) return c.children.some(findCurrent);
            return false;
          });
          var indexChild = item.children.find(function (c) { return c.type === 'page' && c.isIndex; });
          if (indexChild && indexChild.src_path) {
            li.setAttribute('data-nav-index-path', indexChild.src_path);
            if (!item.src_path) item.src_path = indexChild.src_path;
            if (!item.index_meta) {
              item.index_meta = { weight: indexChild.weight, headless: indexChild.headless, retitled: indexChild.retitled, empty: indexChild.empty };
            }
          }
        }

        var sectionLabel = document.createElement('label');
        sectionLabel.className = 'md-nav__link';
        sectionLabel.tabIndex = 0;
        var sectionEllipsis = document.createElement('span');
        sectionEllipsis.className = 'md-ellipsis';
        sectionEllipsis.textContent = item.title;
        sectionLabel.appendChild(sectionEllipsis);
        var expandIcon = document.createElement('span');
        expandIcon.className = 'md-nav__icon md-icon';
        sectionLabel.appendChild(expandIcon);
        var folderDir = _getSectionFolderDir(item) || (item.src_path ? _getDir(item.src_path) : '');
        if (folderDir) li.setAttribute('data-nav-folder-dir', folderDir);
        if (_isSectionEmpty(item)) {
          if (folderDir) {
            var emptyCaution = document.createElement('span');
            emptyCaution.className = 'live-wysiwyg-nav-empty-folder-caution';
            emptyCaution.textContent = '\u26A0';
            emptyCaution.title = 'Empty folder';
            emptyCaution.addEventListener('click', function (e) {
              e.preventDefault();
              e.stopPropagation();
              _showEmptyFolderPopup(emptyCaution, item, folderDir);
            });
            sectionLabel.appendChild(emptyCaution);
          }
        }
        (function (navItem) {
          sectionLabel.addEventListener('click', function (e) {
            if (e.metaKey || e.ctrlKey) {
              e.preventDefault();
              e.stopPropagation();
              if (!_navEditMode) _enterNavEditMode();
              _toggleNavGroupItem(navItem, true);
              return;
            }
            if (_navEditMode && _hasAnyNavSelected()) {
              e.preventDefault();
              e.stopPropagation();
              if (navItem._selected && navItem._focused && _countNavSelected() === 1) {
                _clearNavGroup();
              } else {
                _clearAllNavSelected();
                _setNavItemFocused(navItem);
              }
              _commitNavSnapshot();
              return;
            }
            if (_navEditMode && _hasAnyNavFocused()) {
              e.preventDefault();
              e.stopPropagation();
              navItem._expanded = !navItem._expanded;
              _setNavItemFocused(navItem);
              _commitNavSnapshot();
              return;
            }
            var childNavEl = this.parentNode.querySelector(':scope > .md-nav');
            if (!childNavEl) return;
            var expanded = childNavEl.getAttribute('aria-expanded') !== 'false';
            childNavEl.setAttribute('aria-expanded', expanded ? 'false' : 'true');
            this.parentNode.classList.toggle('md-nav__item--active', !expanded);
            navItem._expanded = !expanded;
            var sectionLi = this.parentNode;
            requestAnimationFrame(function () { _alignNavControls(sectionLi); });
          });
        })(item);

        (function (sLi, sLabel) {
          sLabel.addEventListener('mouseenter', function () { _showNavItemControls(sLi); });
          sLabel.addEventListener('mouseleave', function () { _scheduleNavItemHide(sLi); });
        })(li, sectionLabel);

        var sectionCautionItem = item;
        if (!sectionCautionItem._warnings || !sectionCautionItem._warnings.length) {
          if (item.children) {
            var idxChild = item.children.find(function (c) { return c.type === 'page' && c.isIndex; });
            if (idxChild && idxChild._warnings && idxChild._warnings.length) sectionCautionItem = idxChild;
          }
        }
        if (sectionCautionItem._warnings && sectionCautionItem._warnings.length) {
          (function (cItem, cLabel, cLi) {
            var cIcon = document.createElement('span');
            cIcon.className = 'live-wysiwyg-nav-caution';
            cIcon.textContent = '\u26A0';
            cIcon.title = 'Review - issues found';
            cIcon.addEventListener('click', function (e) {
              e.preventDefault();
              e.stopPropagation();
              _showCautionPopup(cIcon, cItem);
            });
            cLabel.appendChild(cIcon);
            cLi.classList.add('live-wysiwyg-nav-caution-item');
          })(sectionCautionItem, sectionLabel, li);
        }
        li.appendChild(sectionLabel);

        if ((_navEditMode || isHiddenSection || (typeof liveWysiwygNavWeightConfig !== 'undefined' && liveWysiwygNavWeightConfig.enabled)) &&
            !_ymlHasNavKey(_virtualMkdocsYml)) {
          var sectionCtrl = _createNavWeightControls(item, 'section', depth);
          var sectionWrapper = document.createElement('div');
          sectionWrapper.className = 'live-wysiwyg-nav-controls-wrapper live-wysiwyg-nav-controls-section';
          sectionWrapper.appendChild(sectionCtrl.arrows);
          sectionWrapper.appendChild(sectionCtrl.gear);
          sectionWrapper.addEventListener('mouseenter', function () { _showNavItemControls(this.parentNode); });
          sectionWrapper.addEventListener('mouseleave', function () { _scheduleNavItemHide(this.parentNode); });
          li.insertBefore(sectionWrapper, sectionLabel);
        }

        if (item.children && item.children.length) {
          var childNav = document.createElement('nav');
          childNav.className = 'md-nav';
          childNav.setAttribute('data-md-level', String(depth + 1));
          var childTitle = document.createElement('label');
          childTitle.className = 'md-nav__title';
          var childTitleIcon = document.createElement('span');
          childTitleIcon.className = 'md-nav__icon md-icon';
          childTitle.appendChild(childTitleIcon);
          childTitle.appendChild(document.createTextNode(' ' + item.title));
          childNav.appendChild(childTitle);
          var childUl = document.createElement('ul');
          childUl.className = 'md-nav__list';
          _buildNavItems(childUl, item.children, depth + 1);
          childNav.appendChild(childUl);
          li.appendChild(childNav);

          var hasWarnings = item.children.some(function findWarning(c) {
            if (c._warnings && c._warnings.length) return true;
            if (c.children) return c.children.some(findWarning);
            return false;
          });
          if (hasWarnings) {
            var collapsedCaution = document.createElement('span');
            collapsedCaution.className = 'live-wysiwyg-nav-collapsed-caution';
            collapsedCaution.textContent = '\u26A0';
            collapsedCaution.title = 'This folder contains issues.';
            sectionLabel.appendChild(collapsedCaution);
          }
          var shouldExpand = item._expanded !== undefined
            ? item._expanded
            : (hasCurrentPage || item._renamed || hasWarnings);
          if (shouldExpand) {
            li.classList.add('md-nav__item--active');
            childNav.setAttribute('aria-expanded', 'true');
          } else {
            childNav.setAttribute('aria-expanded', 'false');
          }
        }
      } else if (item.type === 'page') {
        var isActive = item.src_path === currentSrcPath;

        if ((_navEditMode || (typeof liveWysiwygNavWeightConfig !== 'undefined' && liveWysiwygNavWeightConfig.enabled)) &&
            !_ymlHasNavKey(_virtualMkdocsYml)) {
          var pageCtrl = _createNavWeightControls(item, 'page', depth);
          var pageWrapper = document.createElement('div');
          pageWrapper.className = 'live-wysiwyg-nav-controls-wrapper';
          pageWrapper.appendChild(pageCtrl.arrows);
          pageWrapper.appendChild(pageCtrl.gear);
          pageWrapper.addEventListener('mouseenter', function () { _showNavItemControls(this.parentNode); });
          pageWrapper.addEventListener('mouseleave', function () { _scheduleNavItemHide(this.parentNode); });
          li.appendChild(pageWrapper);
        }

        var a = document.createElement('a');
        a.className = 'md-nav__link';
        a.href = '/' + (item.url || '');
        a.setAttribute('data-src-path', item.src_path || '');
        (function (pLi, pLink) {
          pLink.addEventListener('mouseenter', function () { _showNavItemControls(pLi); });
          pLink.addEventListener('mouseleave', function () { _scheduleNavItemHide(pLi); });
        })(li, a);
        if (isActive) {
          a.classList.add('md-nav__link--active');
          li.classList.add('md-nav__item--active');
        }
        var pageEllipsis = document.createElement('span');
        pageEllipsis.className = 'md-ellipsis';
        pageEllipsis.textContent = item.title;
        a.appendChild(pageEllipsis);

        var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
        if (!_isRootIndex(item)) {
          if (nwCfg.enabled && item.weight != null) {
            if (item.weight > _navMaxWeight) _navMaxWeight = item.weight;
            var defWeight = (nwCfg.default_page_weight !== undefined ? nwCfg.default_page_weight : 1000);
            if (!item.isIndex && item.weight > defWeight) {
              var weightIcon = document.createElement('span');
              weightIcon.className = 'live-wysiwyg-nav-caution';
              weightIcon.textContent = '\u26A0';
              weightIcon.title = 'Weight exceeds default page weight';
              weightIcon.setAttribute('data-weight-caution', '1');
              (function (wIcon, wItem, wDef) {
                wIcon.addEventListener('click', function (ev) {
                  ev.preventDefault();
                  ev.stopPropagation();
                  _showNavPopup(wIcon,
                    'Weight ' + wItem.weight + ' exceeds default page weight ' + wDef + '. See caution at top of nav menu to resolve.',
                    []);
                });
              })(weightIcon, item, defWeight);
              a.appendChild(weightIcon);
            }
          }
          if (item.weight == null && typeof liveWysiwygNavWeightConfig !== 'undefined' && liveWysiwygNavWeightConfig.enabled) {
            var infoIcon = document.createElement('span');
            infoIcon.className = 'live-wysiwyg-nav-info';
            infoIcon.textContent = '\u2139';
            infoIcon.title = 'No nav weight defined';
            infoIcon.addEventListener('click', function (ev) {
              ev.preventDefault();
              ev.stopPropagation();
              _showUnweightedPopup(ev.target);
            });
            a.appendChild(infoIcon);
          }
        }
        if (item._warnings && item._warnings.length) {
          (function (cautionItem, cautionLink, cautionLi) {
            var cautionIcon = document.createElement('span');
            cautionIcon.className = 'live-wysiwyg-nav-caution';
            cautionIcon.textContent = '\u26A0';
            cautionIcon.title = 'Review this page - issues found';
            cautionIcon.addEventListener('click', function (e) {
              e.preventDefault();
              e.stopPropagation();
              _showCautionPopup(cautionIcon, cautionItem);
            });
            cautionLink.appendChild(cautionIcon);
            cautionLi.classList.add('live-wysiwyg-nav-caution-item');
          })(item, a, li);
        }
        if (item.headless) {
          var hiddenIcon = document.createElement('span');
          hiddenIcon.className = 'live-wysiwyg-nav-hidden-icon';
          hiddenIcon.textContent = '\uD83D\uDC41';
          hiddenIcon.title = 'Hidden page (headless)';
          a.appendChild(hiddenIcon);
        }
        li.appendChild(a);
        li.setAttribute('data-nav-src-path', item.src_path || '');

        (function (navItem, aEl) {
          aEl.addEventListener('click', function (e) {
            e.preventDefault();
            if (e.metaKey || e.ctrlKey) {
              e.stopPropagation();
              if (!_navEditMode) _enterNavEditMode();
              _toggleNavGroupItem(navItem, false);
              return;
            }
            if (_navEditMode && _hasAnyNavSelected()) {
              e.stopPropagation();
              if (navItem._selected && navItem._focused && _countNavSelected() === 1) {
                _clearNavGroup();
              } else {
                _clearAllNavSelected();
                _setNavItemFocused(navItem);
              }
              _commitNavSnapshot();
              return;
            }
            var targetPath = aEl.getAttribute('data-src-path');
            if (_navEditMode && _hasAnyNavFocused()) {
              e.stopPropagation();
              if (navItem._focused) {
                _clearNavItemFocused();
              } else {
                _setNavFocusTarget(targetPath);
                _setNavItemFocused(navItem);
              }
              _commitNavSnapshot();
              return;
            }
            _navigateToPage(aEl.href, aEl.textContent, targetPath);
          });
        })(item, a);
      } else if (item.type === 'asset') {
        li.classList.add('live-wysiwyg-nav-asset-item');
        var showHiddenForAsset = _getSetting('live_wysiwyg_show_hidden') === '1';
        if (!showHiddenForAsset) {
          li.style.display = 'none';
        }

        if ((_navEditMode || (typeof liveWysiwygNavWeightConfig !== 'undefined' && liveWysiwygNavWeightConfig.enabled)) &&
            !_ymlHasNavKey(_virtualMkdocsYml)) {
          var assetCtrl = _createNavWeightControls(item, 'asset', depth);
          var assetWrapper = document.createElement('div');
          assetWrapper.className = 'live-wysiwyg-nav-controls-wrapper';
          assetWrapper.appendChild(assetCtrl.arrows);
          assetWrapper.appendChild(assetCtrl.gear);
          assetWrapper.addEventListener('mouseenter', function () { _showNavItemControls(this.parentNode); });
          assetWrapper.addEventListener('mouseleave', function () { _scheduleNavItemHide(this.parentNode); });
          li.appendChild(assetWrapper);
        }

        var assetSpan = document.createElement('span');
        assetSpan.className = 'md-nav__link live-wysiwyg-nav-asset-link';
        assetSpan.setAttribute('data-src-path', item.src_path || '');
        (function (aLi, aLink, navItem) {
          aLink.addEventListener('mouseenter', function () { _showNavItemControls(aLi); });
          aLink.addEventListener('mouseleave', function () { _scheduleNavItemHide(aLi); });
          aLink.addEventListener('click', function (e) {
            if (e.metaKey || e.ctrlKey) {
              e.preventDefault();
              e.stopPropagation();
              if (!_navEditMode) _enterNavEditMode();
              _toggleNavGroupItem(navItem, false);
              return;
            }
            if (_navEditMode && _hasAnyNavSelected()) {
              e.preventDefault();
              e.stopPropagation();
              if (navItem._selected && navItem._focused && _countNavSelected() === 1) {
                _clearNavGroup();
              } else {
                _clearAllNavSelected();
                _setNavItemFocused(navItem);
              }
              _commitNavSnapshot();
              return;
            }
            if (_navEditMode && _hasAnyNavFocused()) {
              e.preventDefault();
              e.stopPropagation();
              if (navItem._focused) {
                _clearNavItemFocused();
              } else {
                _setNavItemFocused(navItem);
              }
              _commitNavSnapshot();
              return;
            }
          });
        })(li, assetSpan, item);

        var assetIcon = document.createElement('span');
        assetIcon.className = 'live-wysiwyg-nav-asset-icon';
        assetIcon.textContent = '\uD83D\uDCC4';
        assetIcon.title = 'Asset file';
        assetSpan.appendChild(assetIcon);

        var assetEllipsis = document.createElement('span');
        assetEllipsis.className = 'md-ellipsis';
        assetEllipsis.textContent = item.title;
        assetSpan.appendChild(assetEllipsis);

        if (item.extension) {
          var extBadge = document.createElement('span');
          extBadge.className = 'live-wysiwyg-nav-asset-ext';
          extBadge.textContent = item.extension;
          assetSpan.appendChild(extBadge);
        }

        if (item._warnings && item._warnings.length) {
          (function (cautionItem, cautionLink, cautionLi) {
            var cautionIcon = document.createElement('span');
            cautionIcon.className = 'live-wysiwyg-nav-caution';
            cautionIcon.textContent = '\u26A0';
            cautionIcon.title = 'Unreferenced asset';
            cautionIcon.addEventListener('click', function (e) {
              e.preventDefault();
              e.stopPropagation();
              _showCautionPopup(cautionIcon, cautionItem);
            });
            cautionLink.appendChild(cautionIcon);
            cautionLi.classList.add('live-wysiwyg-nav-caution-item');
          })(item, assetSpan, li);
        }

        li.appendChild(assetSpan);
        li.setAttribute('data-nav-src-path', item.src_path || '');
      }
      parentUl.appendChild(li);
    }
  }

  function _createNavWeightControls(item, itemType, depth) {
    var controls = document.createElement('div');
    controls.className = 'live-wysiwyg-nav-weight-controls';

    var upBtn = document.createElement('button');
    upBtn.type = 'button';
    upBtn.textContent = '\u25B2';
    upBtn.title = 'Move up';
    upBtn.className = 'live-wysiwyg-nav-arrow live-wysiwyg-nav-arrow-up';

    var leftBtn = document.createElement('button');
    leftBtn.type = 'button';
    leftBtn.textContent = '\u25C0';
    leftBtn.title = 'Move left (outdent)';
    leftBtn.className = 'live-wysiwyg-nav-arrow live-wysiwyg-nav-arrow-left';

    var rightBtn = document.createElement('button');
    rightBtn.type = 'button';
    rightBtn.textContent = '\u25B6';
    rightBtn.title = 'Move right (indent)';
    rightBtn.className = 'live-wysiwyg-nav-arrow live-wysiwyg-nav-arrow-right';

    var downBtn = document.createElement('button');
    downBtn.type = 'button';
    downBtn.textContent = '\u25BC';
    downBtn.title = 'Move down';
    downBtn.className = 'live-wysiwyg-nav-arrow live-wysiwyg-nav-arrow-down';

    var gearBtn = document.createElement('button');
    gearBtn.type = 'button';
    gearBtn.textContent = '\u2699';
    gearBtn.title = 'Settings';
    gearBtn.className = 'live-wysiwyg-nav-settings-gear';

    var nwEnabled = typeof liveWysiwygNavWeightConfig !== 'undefined' && liveWysiwygNavWeightConfig.enabled;
    if (!nwEnabled && !_isMovableWithoutNormalization(item, itemType)) {
      leftBtn.disabled = rightBtn.disabled = upBtn.disabled = downBtn.disabled = true;
    }

    if (_isRootIndex(item)) {
      upBtn.style.display = 'none';
      downBtn.style.display = 'none';
      leftBtn.style.display = 'none';
      rightBtn.style.display = 'none';
    } else if (depth === 0) {
      leftBtn.style.visibility = 'hidden';
    }

    [leftBtn, upBtn, downBtn, rightBtn].forEach(function (btn) {
      btn.addEventListener('click', function (e) {
        e.stopPropagation();
        _handleArrowClick(item, itemType, btn.className, e.shiftKey);
      });
    });

    gearBtn.addEventListener('click', function (e) {
      e.stopPropagation();
      _showSettingsGear(item, itemType, gearBtn);
    });

    var targetBtn = document.createElement('button');
    targetBtn.type = 'button';
    targetBtn.textContent = '\u25CF';
    targetBtn.title = 'Set as focus target after save';
    targetBtn.className = 'live-wysiwyg-nav-target-dot';
    targetBtn.addEventListener('click', function (e) {
      e.stopPropagation();
      var targetPath = _getItemSrcPath(item);
      if (targetPath) _setNavFocusTarget(targetPath);
    });
    if (itemType === 'asset') targetBtn.style.display = 'none';

    controls.appendChild(upBtn);
    controls.appendChild(leftBtn);
    controls.appendChild(targetBtn);
    controls.appendChild(rightBtn);
    controls.appendChild(downBtn);

    var result = { arrows: controls, gear: gearBtn };
    return result;
  }

  // ======================================================================
  // NAV MENU - Arrow click handler (enters nav edit mode)
  // ======================================================================
  function _isRootIndex(item) {
    return item && item.type === 'page' && item.isIndex && item.src_path === 'index.md';
  }

  function _getItemSrcPath(item) {
    if (!item) return '';
    return item.src_path || '';
  }

  function _getItemWeight(navItem) {
    if (navItem.type === 'page') return navItem.weight;
    if (navItem.type === 'section' && navItem.index_meta) return navItem.index_meta.weight;
    return undefined;
  }

  

  function _findNavSiblings(item) {
    var result = [];
    var itemPath = _getItemSrcPath(item);
    function isSameItem(navItem) {
      if (itemPath && itemPath === _getItemSrcPath(navItem)) return true;
      if (item.type === 'section' && navItem.type === 'section' && item.title === navItem.title) return true;
      return false;
    }
    function collectAll(items) {
      items.forEach(function (c) { result.push(c); });
    }
    function walk(items) {
      for (var i = 0; i < items.length; i++) {
        if (isSameItem(items[i])) {
          collectAll(items);
          return true;
        }
        if (items[i].type === 'section' && items[i].children) {
          if (walk(items[i].children)) return true;
        }
      }
      return false;
    }
    if (typeof liveWysiwygNavData !== 'undefined') {
      walk(liveWysiwygNavData);
    }
    return result;
  }

  function _dismissActiveNavHover(exceptLi) {
    if (_navActiveHoverLi && _navActiveHoverLi !== exceptLi) {
      clearTimeout(_navActiveHoverLi.__navHoverTimer);
      _navActiveHoverLi.classList.remove('live-wysiwyg-nav-hover');
      _navActiveHoverLi = null;
    }
  }

  function _showNavItemControls(li) {
    _dismissActiveNavHover(li);
    clearTimeout(li.__navHoverTimer);
    li.classList.add('live-wysiwyg-nav-hover');
    _navActiveHoverLi = li;
  }

  function _scheduleNavItemHide(li) {
    li.__navHoverTimer = setTimeout(function () {
      li.classList.remove('live-wysiwyg-nav-hover');
      if (_navActiveHoverLi === li) _navActiveHoverLi = null;
    }, 500);
  }

  function _alignNavControls(li) {
    if (!li) return;
    var wrapper = li.querySelector(':scope > .live-wysiwyg-nav-controls-wrapper');
    var label = li.querySelector(':scope > .md-nav__link');
    if (!wrapper || !label) return;
    wrapper.style.top = label.offsetTop + 'px';
    wrapper.style.height = label.offsetHeight + 'px';
  }

  function _alignAllNavControls() {
    if (!_navSidebarEl) return;
    var items = _navSidebarEl.querySelectorAll('.md-nav__item');
    for (var i = 0; i < items.length; i++) {
      if (items[i].querySelector(':scope > .live-wysiwyg-nav-controls-wrapper')) {
        _alignNavControls(items[i]);
      }
    }
  }

  // ======================================================================
  // NAV MENU - navData state helpers (no direct DOM manipulation)
  // All visual state lives on navData items; the renderer reads it.
  // ======================================================================

  function _setNavItemFocused(item) {
    _walkNavData(function (it) { delete it._focused; });
    if (item) item._focused = true;
    _navKeyboardActiveItem = item || null;
  }

  function _clearNavItemFocused() {
    _walkNavData(function (it) { delete it._focused; });
    _navKeyboardActiveItem = null;
  }

  function _clearAllNavSelected() {
    _walkNavData(function (it) { delete it._selected; delete it._groupMode; });
  }

  function _hasAnyNavSelected() {
    var found = false;
    _walkNavData(function (it) { if (it._selected) found = true; });
    return found;
  }

  function _hasAnyNavFocused() {
    var found = false;
    _walkNavData(function (it) { if (it._focused) found = true; });
    return found;
  }

  function _countNavSelected() {
    var c = 0;
    _walkNavData(function (it) { if (it._selected) c++; });
    return c;
  }

  function _clearNavFocus() {
    _clearNavItemFocused();
  }

  function _clearNavGroup() {
    _clearAllNavSelected();
    _clearNavItemFocused();
  }

  function _isItemSelectedInNavData(item) {
    if (item._selected) return true;
    var nd = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    var found = false;
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        if (found) return;
        if (items[i]._selected && items[i]._groupMode === 'section' && items[i].children) {
          for (var j = 0; j < items[i].children.length; j++) {
            if (items[i].children[j]._uid === item._uid) { found = true; return; }
          }
        }
        if (items[i].children) walk(items[i].children);
      }
    })(nd);
    return found;
  }

  function _checkAutoPromotion(item) {
    var parent = _findParentSection(item._uid);
    if (!parent || !parent.children) return;
    var nonIndexChildren = [];
    for (var i = 0; i < parent.children.length; i++) {
      var ch = parent.children[i];
      if (ch.isIndex) continue;
      nonIndexChildren.push(ch);
    }
    if (nonIndexChildren.length === 0) return;
    var allSelected = true;
    for (var j = 0; j < nonIndexChildren.length; j++) {
      if (!_isItemSelectedInNavData(nonIndexChildren[j])) { allSelected = false; break; }
    }
    if (!allSelected) return;
    for (var ci2 = 0; ci2 < nonIndexChildren.length; ci2++) {
      delete nonIndexChildren[ci2]._selected;
      delete nonIndexChildren[ci2]._groupMode;
    }
    parent._selected = true;
    parent._groupMode = 'section';
    parent._expanded = false;
  }

  function _toggleNavGroupItem(item, isSection) {
    if (!_navEditMode) return;

    if (isSection && item.type === 'section') {
      if (item._selected && item._groupMode === 'section') {
        delete item._selected;
        delete item._groupMode;
        if (!_hasAnyNavSelected()) {
          var wasFocused = !!item._focused;
          _clearNavGroup();
          if (!wasFocused) _setNavItemFocused(item);
          _commitNavSnapshot();
          return;
        }
      } else {
        item._selected = true;
        item._groupMode = 'section';
        item._expanded = false;
      }
    } else {
      if (item._selected) {
        delete item._selected;
        delete item._groupMode;
        if (!_hasAnyNavSelected()) {
          var wasFocused = !!item._focused;
          _clearNavGroup();
          if (!wasFocused) _setNavItemFocused(item);
          _commitNavSnapshot();
          return;
        }
      } else {
        var parentSection = null;
        var nd = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
        (function findParentSec(items) {
          for (var i = 0; i < items.length; i++) {
            if (parentSection) return;
            if (items[i]._selected && items[i]._groupMode === 'section' && items[i].children) {
              for (var j = 0; j < items[i].children.length; j++) {
                if (items[i].children[j]._uid === item._uid) {
                  parentSection = items[i]; return;
                }
              }
            }
            if (items[i].children) findParentSec(items[i].children);
          }
        })(nd);
        if (parentSection) {
          delete parentSection._selected;
          delete parentSection._groupMode;
          if (parentSection.children) {
            for (var ri = 0; ri < parentSection.children.length; ri++) {
              var remainChild = parentSection.children[ri];
              if (remainChild._uid === item._uid) continue;
              if (remainChild.isIndex) continue;
              remainChild._selected = true;
              remainChild._groupMode = 'individual';
            }
          }
        } else {
          item._selected = true;
          item._groupMode = 'individual';
          _checkAutoPromotion(item);
        }
      }
    }

    _setNavItemFocused(item);
    _commitNavSnapshot();
  }

  function _getNavItemDepth(uid, items, depth) {
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    depth = depth || 0;
    for (var i = 0; i < items.length; i++) {
      if (items[i]._uid === uid) return depth;
      if (items[i].children) {
        var found = _getNavItemDepth(uid, items[i].children, depth + 1);
        if (found >= 0) return found;
      }
    }
    return -1;
  }

  function _promoteGroupFocal() {
    var selectedItems = [];
    _walkNavData(function (it) { if (it._selected) selectedItems.push(it); });
    if (selectedItems.length === 0) return null;
    var minDepth = Infinity;
    var bestItem = null;
    for (var i = 0; i < selectedItems.length; i++) {
      var d = _getNavItemDepth(selectedItems[i]._uid);
      if (d < 0) continue;
      if (d < minDepth || (d === minDepth && !bestItem)) {
        minDepth = d;
        bestItem = selectedItems[i];
      }
    }
    if (bestItem) {
      _navKeyboardActiveItem = bestItem;
    }
    return bestItem;
  }

  function _collectGroupEffectiveItems() {
    var result = [];
    var seen = {};
    _walkNavData(function (it) {
      if (!it._selected) return;
      if (seen[it._uid]) return;
      seen[it._uid] = true;
      result.push(it);
    });
    return result;
  }

  function _computeRelativeParentChains(effectiveItems, focalDepth) {
    var result = [];
    for (var i = 0; i < effectiveItems.length; i++) {
      var item = effectiveItems[i];
      var d = _getNavItemDepth(item._uid);
      if (d < 0) d = focalDepth;
      if (d <= focalDepth) {
        result.push({ item: item, parentChain: [] });
      } else {
        var chain = [];
        var cur = item;
        for (var level = d; level > focalDepth; level--) {
          var p = _findParentSection(cur._uid);
          if (p) {
            chain.unshift(p);
            cur = p;
          } else {
            break;
          }
        }
        result.push({ item: item, parentChain: chain });
      }
    }
    return result;
  }

  function _createIndexlessSectionSilent(folderName, parentDir) {
    var folderTitle = folderName.replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
    var indexPath = (parentDir ? parentDir + '/' : '') + folderName + '/index.md';
    var syntheticSection = {
      type: 'section',
      title: folderTitle,
      src_path: indexPath,
      children: [],
      _new: true,
      _uid: _generateUid(),
      _expanded: true
    };
    _navBatchQueue.push({
      type: 'create-folder',
      item: null,
      folderName: folderName,
      folderTitle: folderTitle,
      skipIndex: true,
      syntheticSection: syntheticSection
    });
    return syntheticSection;
  }

  function _findSectionByFolderName(siblings, folderName) {
    for (var i = 0; i < siblings.length; i++) {
      if (siblings[i].type !== 'section') continue;
      var dir = _getSectionFolderDir(siblings[i]);
      var name = dir ? dir.split('/').pop() : '';
      if (!name && siblings[i].title) {
        name = siblings[i].title.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
      }
      if (name === folderName) return siblings[i];
    }
    return null;
  }

  function _doGroupLateralMove(direction, focal, effectiveItems) {
    var isLeft = direction.indexOf('left') !== -1;
    var focalDepth = _getNavItemDepth(focal._uid);
    if (focalDepth < 0) return;

    var chains = _computeRelativeParentChains(effectiveItems, focalDepth);

    var others = [];
    for (var i = 0; i < effectiveItems.length; i++) {
      if (effectiveItems[i] !== focal) others.push(effectiveItems[i]);
    }
    for (var k = others.length - 1; k >= 0; k--) {
      var eLoc = _findNavItemInTree(others[k]._uid);
      if (eLoc) eLoc.parent.splice(eLoc.index, 1);
    }

    var oldParent = _findParentSection(focal._uid);

    if (isLeft) {
      _moveNavItemLeft(focal);
    } else {
      _moveNavItemRight(focal, false);
    }

    var focalLoc = _findNavItemInTree(focal._uid);
    if (!focalLoc) return;

    var destParent = _findParentSection(focal._uid);
    var destDir = destParent ? _getSectionFolderDir(destParent) : '';

    var uniqueChains = [];
    var chainKeys = {};
    for (var ci = 0; ci < chains.length; ci++) {
      var entry = chains[ci];
      if (entry.parentChain.length === 0) continue;
      var key = '';
      for (var pi = 0; pi < entry.parentChain.length; pi++) {
        var sec = entry.parentChain[pi];
        var secDir = _getSectionFolderDir(sec);
        var secName = secDir ? secDir.split('/').pop() : '';
        if (!secName && sec.title) {
          secName = sec.title.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
        }
        key += (key ? '/' : '') + secName;
      }
      if (!chainKeys[key]) {
        chainKeys[key] = { chain: entry.parentChain, key: key };
        uniqueChains.push(chainKeys[key]);
      }
    }
    uniqueChains.sort(function (a, b) {
      return a.key.split('/').length - b.key.split('/').length;
    });

    var resolvedSections = {};
    var createdSections = {};
    for (var ui = 0; ui < uniqueChains.length; ui++) {
      var chainInfo = uniqueChains[ui];
      var parts = chainInfo.key.split('/');
      var currentParentArr = focalLoc.parent;
      var currentParentDir = destDir;
      var builtKey = '';
      for (var pi = 0; pi < parts.length; pi++) {
        var folderName = parts[pi];
        builtKey += (builtKey ? '/' : '') + folderName;
        if (resolvedSections[builtKey]) {
          var resolved = resolvedSections[builtKey];
          resolved.section.children = resolved.section.children || [];
          currentParentArr = resolved.section.children;
          currentParentDir = _getSectionFolderDir(resolved.section) || currentParentDir + '/' + folderName;
          continue;
        }
        var existing = _findSectionByFolderName(currentParentArr, folderName);
        if (existing) {
          existing.children = existing.children || [];
          resolvedSections[builtKey] = { section: existing, isNew: false };
          currentParentArr = existing.children;
          currentParentDir = _getSectionFolderDir(existing) || currentParentDir + '/' + folderName;
        } else {
          var newSec = _createIndexlessSectionSilent(folderName, currentParentDir);
          currentParentArr.push(newSec);
          resolvedSections[builtKey] = { section: newSec, isNew: true };
          createdSections[builtKey] = newSec;
          currentParentArr = newSec.children;
          currentParentDir = _getSectionFolderDir(newSec) || currentParentDir + '/' + folderName;
        }
      }
    }

    var insertIdx = focalLoc.index + 1;
    for (var oi = 0; oi < others.length; oi++) {
      var otherItem = others[oi];
      var otherChain = null;
      for (var ci2 = 0; ci2 < chains.length; ci2++) {
        if (chains[ci2].item === otherItem) { otherChain = chains[ci2]; break; }
      }
      if (!otherChain || otherChain.parentChain.length === 0) {
        focalLoc.parent.splice(insertIdx, 0, otherItem);
        insertIdx++;
      } else {
        var targetKey = '';
        for (var pi2 = 0; pi2 < otherChain.parentChain.length; pi2++) {
          var sec2 = otherChain.parentChain[pi2];
          var secDir2 = _getSectionFolderDir(sec2);
          var secName2 = secDir2 ? secDir2.split('/').pop() : '';
          if (!secName2 && sec2.title) {
            secName2 = sec2.title.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
          }
          targetKey += (targetKey ? '/' : '') + secName2;
        }
        var targetResolved = resolvedSections[targetKey];
        if (targetResolved) {
          targetResolved.section.children.push(otherItem);
        } else {
          focalLoc.parent.splice(insertIdx, 0, otherItem);
          insertIdx++;
        }
      }
    }

    _clearAllNavSelected();
    for (var sk in createdSections) {
      if (createdSections.hasOwnProperty(sk)) {
        var createdSec = createdSections[sk];
        createdSec._selected = true;
        createdSec._groupMode = 'section';
      }
    }
    for (var ri = 0; ri < chains.length; ri++) {
      var rEntry = chains[ri];
      if (rEntry.parentChain.length === 0) {
        rEntry.item._selected = true;
        rEntry.item._groupMode = rEntry.item._groupMode || 'individual';
      } else {
        var rKey = '';
        for (var rp = 0; rp < rEntry.parentChain.length; rp++) {
          var rs = rEntry.parentChain[rp];
          var rsDir = _getSectionFolderDir(rs);
          var rsName = rsDir ? rsDir.split('/').pop() : '';
          if (!rsName && rs.title) {
            rsName = rs.title.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
          }
          rKey += (rKey ? '/' : '') + rsName;
        }
        if (createdSections[rKey]) continue;
        var topKey = '';
        var topSec2 = rEntry.parentChain[0];
        var topDir2 = _getSectionFolderDir(topSec2);
        topKey = topDir2 ? topDir2.split('/').pop() : '';
        if (!topKey && topSec2.title) {
          topKey = topSec2.title.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
        }
        if (createdSections[topKey]) continue;
        rEntry.item._selected = true;
        rEntry.item._groupMode = 'individual';
      }
    }

    var newParent = _findParentSection(focal._uid);
    if (newParent !== oldParent) {
      var sec3 = newParent;
      while (sec3) {
        sec3._expanded = true;
        sec3 = sec3._uid ? _findParentSection(sec3._uid) : null;
      }
      if (oldParent) oldParent._expanded = false;
    }
  }

  function _doGroupArrowMove(direction, shiftKey) {
    var focal = _promoteGroupFocal();
    if (!focal) return;

    var isLeft = direction.indexOf('left') !== -1;
    var isRight = direction.indexOf('right') !== -1;
    var isUp = direction.indexOf('up') !== -1;
    var isDown = direction.indexOf('down') !== -1;

    if (isRight && shiftKey) {
      var allGroupItems = _collectGroupEffectiveItems();
      if (allGroupItems.length === 0) allGroupItems = [focal];
      _promptNewFolder(focal, allGroupItems);
      return;
    }

    var effectiveItems = _collectGroupEffectiveItems();
    if (effectiveItems.length === 0) return;

    if (isLeft || isRight) {
      _doGroupLateralMove(direction, focal, effectiveItems);
    } else {
      var others = [];
      for (var i = 0; i < effectiveItems.length; i++) {
        if (effectiveItems[i] !== focal) others.push(effectiveItems[i]);
      }

      for (var k = others.length - 1; k >= 0; k--) {
        var eLoc = _findNavItemInTree(others[k]._uid);
        if (eLoc) eLoc.parent.splice(eLoc.index, 1);
      }

      var oldParent = _findParentSection(focal._uid);

      if (isUp) {
        _moveNavItemUp(focal, shiftKey);
      } else if (isDown) {
        _moveNavItemDown(focal, shiftKey);
      }

      var focalLoc = _findNavItemInTree(focal._uid);
      if (focalLoc) {
        var insertIdx = focalLoc.index + 1;
        for (var m = 0; m < others.length; m++) {
          focalLoc.parent.splice(insertIdx, 0, others[m]);
          insertIdx++;
        }
      }

      var newParent = _findParentSection(focal._uid);
      if (newParent !== oldParent) {
        var sec = newParent;
        while (sec) {
          sec._expanded = true;
          sec = sec._uid ? _findParentSection(sec._uid) : null;
        }
        if (oldParent) oldParent._expanded = false;
      }
    }

    _setNavItemFocused(focal);

    if (!_navBadges.some(function (b) { return b.text === 'Reorder files'; })) {
      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge',
        text: 'Reorder files'
      });
    }
    _commitNavSnapshot();
  }

  function _handleArrowClick(item, itemType, direction, shiftKey) {
    if (_hasAnyNavSelected()) {
      if (!_navEditMode) _enterNavEditMode();
      _doGroupArrowMove(direction, shiftKey);
      return;
    }

    var isLeft = direction.indexOf('left') !== -1;
    var isRight = direction.indexOf('right') !== -1;
    var isUp = direction.indexOf('up') !== -1;
    var isDown = direction.indexOf('down') !== -1;

    var srcPath = _getItemSrcPath(item);
    var currentSrc = _getCurrentSrcPath();
    var isCurrentPage = srcPath === currentSrc ||
      (item.type === 'section' && item.children && item.children.some(function (c) {
        return c.type === 'page' && c.src_path === currentSrc;
      }));
    var isSimpleVertical = (isUp || isDown) && !shiftKey && isCurrentPage;

    function _doArrowMove() {
    _navKeyboardActiveItem = item;

    var oldParent = _findParentSection(item._uid);

    if (isUp) {
      if (isSimpleVertical) {
        _moveNavItemUpDirect(item);
      } else {
        _moveNavItemUp(item, shiftKey);
      }
    } else if (isDown) {
      if (isSimpleVertical) {
        _moveNavItemDownDirect(item);
      } else {
        _moveNavItemDown(item, shiftKey);
      }
    } else if (isLeft) {
      _moveNavItemLeft(item);
    } else if (isRight) {
      _moveNavItemRight(item, shiftKey);
      if (shiftKey) return;
    }

    var newParent = _findParentSection(item._uid);
    if (newParent !== oldParent) {
      var sec = newParent;
      while (sec) {
        sec._expanded = true;
        sec = sec._uid ? _findParentSection(sec._uid) : null;
      }
      if (oldParent) oldParent._expanded = false;
    }

    var moveDir = isUp ? 'up' : isDown ? 'down' : isLeft ? 'up' : 'down';
    var loc = item._uid ? _findNavItemInTree(item._uid) : null;
    if (loc) {
      var parentSection = _findParentSection(item._uid);
      var needsFullNormalize = parentSection && (parentSection._new || parentSection._renamed);
      if (!needsFullNormalize) {
        var siblingsNeedNormalize = loc.parent.some(function (sib) {
          if (sib._deleted) return false;
          if (sib.type === 'page' && sib.isIndex) return false;
          if (sib.type === 'page' && sib.headless) return false;
          if (sib.type === 'section' && sib.children && !_hasVisibleMdContent(sib.children)) return false;
          return _getItemWeight(sib) == null;
        });
        if (siblingsNeedNormalize) needsFullNormalize = true;
      }
      if (needsFullNormalize) {
        _normalizeLevelWeights(parentSection || null);
      } else {
        _updateInMemoryWeightFromDom(item, moveDir);
      }
    }

    _setNavItemFocused(item);

    if (!_navBadges.some(function (b) { return b.text === 'Reorder files'; })) {
      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge',
        text: 'Reorder files'
      });
    }
    _commitNavSnapshot();
    }

    if (!_navEditMode) _enterNavEditMode();
    _doArrowMove();
  }

  function _moveNavItemUpDirect(item) {
    if (!item || !item._uid) return;
    var loc = _findNavItemInTree(item._uid);
    if (!loc || loc.index <= 0) return;
    var prev = loc.parent[loc.index - 1];
    if (_getItemSrcPath(prev) === 'index.md') return;
    loc.parent.splice(loc.index, 1);
    loc.parent.splice(loc.index - 1, 0, item);
  }

  function _moveNavItemDownDirect(item) {
    if (!item || !item._uid) return;
    var loc = _findNavItemInTree(item._uid);
    if (!loc || loc.index >= loc.parent.length - 1) return;
    loc.parent.splice(loc.index, 1);
    loc.parent.splice(loc.index + 1, 0, item);
  }

  function _updateInMemoryWeightFromDom(item, direction) {
    if (!item || !item._uid || typeof liveWysiwygNavData === 'undefined') return;
    var srcPath = _getItemSrcPath(item);
    if (!srcPath) return;
    var loc = _findNavItemInTree(item._uid);
    if (!loc) return;
    var siblings = loc.parent;
    var targetIdx = loc.index;
    var prevW = targetIdx > 0 ? (_getItemWeight(siblings[targetIdx - 1]) || 0) : null;
    var nextW = targetIdx < siblings.length - 1 ? (_getItemWeight(siblings[targetIdx + 1]) || 0) : null;
    var rounder = direction === 'up' ? Math.floor : Math.ceil;
    var newWeight;
    if (prevW != null && nextW != null) {
      newWeight = rounder((prevW + nextW) / 2);
      if (newWeight === prevW || newWeight === nextW) newWeight = prevW + 1;
    } else if (prevW != null) {
      newWeight = prevW + 100;
    } else if (nextW != null) {
      newWeight = rounder(nextW / 2);
    } else {
      newWeight = (targetIdx + 1) * 100;
    }
    _setItemWeight(item, newWeight);
    _syncCurrentPageWeight(srcPath, newWeight);
  }

  function _setItemWeight(navItem, weight) {
    if (navItem.type === 'page') {
      navItem.weight = weight;
    } else if (navItem.type === 'section') {
      if (navItem.index_meta) navItem.index_meta.weight = weight;
      if (navItem.children) {
        for (var i = 0; i < navItem.children.length; i++) {
          if (navItem.children[i].type === 'page' && navItem.children[i].isIndex) {
            navItem.children[i].weight = weight;
            break;
          }
        }
      }
    }
  }

  function _syncCurrentPageWeight(srcPath, weight) {
    if (srcPath !== _getCurrentSrcPath()) return;
    if (typeof wysiwygEditor === 'undefined' || !wysiwygEditor) return;

    var isIndex = srcPath.endsWith('index.md');
    var fmStr = wysiwygEditor._liveWysiwygFrontmatter || '';
    var withBody = fmStr ? (fmStr + '\n') : '';
    var updatedFull = _updateFrontmatter(withBody, { weight: weight }, isIndex);
    var parsed = parseFrontmatter(updatedFull);
    wysiwygEditor._liveWysiwygFrontmatter = parsed.frontmatter;

    if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
      var ma = wysiwygEditor.markdownArea;
      var content = ma.value;
      var updatedContent = _updateFrontmatter(content, { weight: weight }, isIndex);
      if (updatedContent !== content) {
        var start = ma.selectionStart;
        var end = ma.selectionEnd;
        ma.value = updatedContent;
        var delta = updatedContent.length - content.length;
        ma.selectionStart = Math.max(0, start + delta);
        ma.selectionEnd = Math.max(0, end + delta);
      }
    }

    if (wysiwygEditor._finalizeUpdate) {
      wysiwygEditor._finalizeUpdate();
    }
  }

  function _findSectionByFolderDir(items, folderDir) {
    if (!items || !folderDir) return null;
    for (var i = 0; i < items.length; i++) {
      var it = items[i];
      if (it.type === 'section') {
        var fd = _getSectionFolderDir(it);
        if (fd === folderDir) return it;
        if (it.children) {
          var found = _findSectionByFolderDir(it.children, folderDir);
          if (found) return found;
        }
      }
    }
    return null;
  }

  function _findSectionByIndexPath(items, indexPath) {
    if (!items || !indexPath) return null;
    for (var i = 0; i < items.length; i++) {
      var it = items[i];
      if (it.type === 'section') {
        if (it.src_path === indexPath) return it;
        if (it.children) {
          var found = _findSectionByIndexPath(it.children, indexPath);
          if (found) return found;
        }
      }
    }
    return null;
  }

  function _moveNavItemUp(item, shiftKey) {
    if (!item || !item._uid) return;
    var loc = _findNavItemInTree(item._uid);
    if (!loc) return;
    var idx = loc.index;
    var siblings = loc.parent;
    if (shiftKey && idx > 0 && siblings[idx - 1].type === 'section') {
      var target = siblings[idx - 1];
      var deepest = target;
      while (deepest.children) {
        var lastSection = null;
        for (var di = deepest.children.length - 1; di >= 0; di--) {
          if (deepest.children[di].type === 'section') { lastSection = deepest.children[di]; break; }
        }
        if (lastSection) deepest = lastSection;
        else break;
      }
      siblings.splice(idx, 1);
      if (deepest.children) {
        deepest.children.push(item);
      } else {
        target.children = target.children || [];
        target.children.push(item);
      }
      _navBatchQueue.push({ type: 'move-into-section', item: item, targetSection: target, position: 'end' });
      return;
    }
    if (idx <= 0) return;
    if (_getItemSrcPath(siblings[idx - 1]) === 'index.md' && !_findParentSection(item._uid)) return;
    siblings.splice(idx, 1);
    siblings.splice(idx - 1, 0, item);
    _navBatchQueue.push({ type: 'move-up', item: item });
  }

  function _getSectionLiFromUl(ul) {
    if (!ul || !ul.parentNode) return null;
    var nav = ul.parentNode;
    if (!nav.classList || !nav.classList.contains('md-nav')) return null;
    var sectionLi = nav.parentNode;
    return sectionLi && sectionLi.classList && sectionLi.classList.contains('md-nav__item--nested') ? sectionLi : null;
  }

  function _moveNavItemDown(item, shiftKey) {
    if (!item || !item._uid) return;
    var loc = _findNavItemInTree(item._uid);
    if (!loc) return;
    var idx = loc.index;
    var siblings = loc.parent;
    if (shiftKey && idx < siblings.length - 1 && siblings[idx + 1].type === 'section') {
      var target = siblings[idx + 1];
      target.children = target.children || [];
      siblings.splice(idx, 1);
      target.children.splice(0, 0, item);
      _navBatchQueue.push({ type: 'move-into-section', item: item, targetSection: target, position: 'start' });
      return;
    }
    if (idx >= siblings.length - 1) return;
    siblings.splice(idx, 1);
    siblings.splice(idx + 1, 0, item);
    _navBatchQueue.push({ type: 'move-down', item: item });
  }

  function _expandSection(sectionLi) {
    if (!sectionLi) return;
    var childNav = sectionLi.querySelector(':scope > .md-nav');
    if (!childNav) return;
    childNav.setAttribute('aria-expanded', 'true');
    sectionLi.classList.add('md-nav__item--active');
    requestAnimationFrame(function () { _alignNavControls(sectionLi); });
  }

  function _collapseIfEmpty(sectionLi) {
    if (!sectionLi || !sectionLi.classList.contains('md-nav__item--nested')) return;
    var childNav = sectionLi.querySelector(':scope > .md-nav');
    if (!childNav) return;
    var ul = childNav.querySelector('.md-nav__list');
    if (!ul) return;
    var visiblePages = 0;
    for (var i = 0; i < ul.children.length; i++) {
      var c = ul.children[i];
      if (c.classList.contains('md-nav__item') && !c.classList.contains('md-nav__item--nested')) visiblePages++;
    }
    if (visiblePages === 0 || (visiblePages === 1 && ul.children.length === 1 && ul.children[0].getAttribute('data-nav-src-path') && ul.children[0].getAttribute('data-nav-src-path').endsWith('index.md'))) {
      childNav.setAttribute('aria-expanded', 'false');
      sectionLi.classList.remove('md-nav__item--active');
    }
  }

  function _moveNavItemLeft(item) {
    if (!item || !item._uid) return;
    var parentSection = _findParentSection(item._uid);
    if (!parentSection) return;
    var loc = _findNavItemInTree(item._uid);
    if (!loc) return;
    loc.parent.splice(loc.index, 1);
    if (parentSection._renamed || parentSection._new) {
      delete item._renamed;
    }
    var parentLoc = parentSection._uid ? _findNavItemInTree(parentSection._uid) : null;
    if (parentLoc) {
      parentLoc.parent.splice(parentLoc.index + 1, 0, item);
    } else {
      var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
      navItems.push(item);
    }
    _navBatchQueue.push({ type: 'move-left', item: item });
  }

  function _moveNavItemRight(item, shiftKey) {
    if (!item || !item._uid) return;

    if (shiftKey) {
      _promptNewFolder(item);
      return;
    }

    var loc = _findNavItemInTree(item._uid);
    if (!loc) return;
    var idx = loc.index;
    var siblings = loc.parent;
    var belowSection = null;
    var aboveSection = null;
    for (var i = idx + 1; i < siblings.length; i++) {
      if (siblings[i].type === 'section') { belowSection = siblings[i]; break; }
    }
    for (var j = idx - 1; j >= 0; j--) {
      if (siblings[j].type === 'section') { aboveSection = siblings[j]; break; }
    }

    if (belowSection) {
      belowSection.children = belowSection.children || [];
      siblings.splice(idx, 1);
      belowSection.children.splice(0, 0, item);
      _navBatchQueue.push({ type: 'move-right', item: item, targetSection: belowSection, position: 'start' });
    } else if (aboveSection) {
      aboveSection.children = aboveSection.children || [];
      siblings.splice(idx, 1);
      aboveSection.children.push(item);
      _navBatchQueue.push({ type: 'move-right', item: item, targetSection: aboveSection, position: 'end' });
    } else {
      _promptNewFolder(item);
    }
  }

  /**
   * Unified auto-expand for any container with text/number inputs.
   * Uses a captured base width to prevent compounding expansion on repeated focus.
   *
   * @param {HTMLElement} container  - Element whose width grows (dropdown or dialog content)
   * @param {Object}      [opts]
   * @param {string}      [opts.prop='minWidth']    - CSS property to expand ('minWidth' or 'maxWidth')
   * @param {string}      [opts.selector]           - Input selector (default: 'input[type="text"], input[type="number"]')
   * @param {Function}    [opts.onResize]            - Called after expansion (e.g. reposition dropdown)
   * @param {HTMLElement[]} [opts.inputs]            - Explicit input list (overrides selector)
   */
  function _attachContainerExpandBehavior(container, opts) {
    opts = opts || {};
    var prop = opts.prop || 'minWidth';
    var cssProp = prop.replace(/[A-Z]/g, function (c) { return '-' + c.toLowerCase(); });
    var onResize = opts.onResize || null;
    var inputs = opts.inputs;
    if (!inputs) {
      var sel = opts.selector || 'input[type="text"], input[type="number"]';
      inputs = container.querySelectorAll(sel);
    }
    var animId = null;
    var animStart = 0;
    var animFrom = 0;
    var animTo = 0;
    var ANIM_MS = 300;
    var cssReady = false;
    var lastTarget = 0;

    function easeInOut(t) {
      return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    }

    function animTick(now) {
      var elapsed = now - animStart;
      var t = Math.min(elapsed / ANIM_MS, 1);
      var val = animFrom + (animTo - animFrom) * easeInOut(t);
      container.style[prop] = val + 'px';
      if (onResize) onResize();
      if (t < 1) {
        animId = requestAnimationFrame(animTick);
      } else {
        animId = null;
        container.style.transition = cssProp + ' .3s ease-in-out';
        cssReady = true;
      }
    }

    // Contraction intentionally skipped for UI stability — avoids
    // distracting shrink animations when the user switches between inputs.
    var OVERFLOW_THRESHOLD = 3;
    function measure() {
      if (animId) return;
      var maxOverflow = 0;
      for (var i = 0; i < inputs.length; i++) {
        var ov = inputs[i].scrollWidth - inputs[i].clientWidth;
        if (ov > OVERFLOW_THRESHOLD && ov > maxOverflow) maxOverflow = ov;
      }
      if (maxOverflow <= 0) return;

      var cur = container.offsetWidth;
      var needed = cur + maxOverflow + 4;

      var rect = container.getBoundingClientRect();
      var maxWidth = window.innerWidth - rect.left - 8;
      if (needed > maxWidth) needed = maxWidth;
      if (needed <= cur || needed <= lastTarget) return;

      lastTarget = needed;
      if (!cssReady) {
        animFrom = cur;
        animTo = needed;
        animStart = performance.now();
        animId = requestAnimationFrame(animTick);
      } else {
        container.style[prop] = needed + 'px';
        if (onResize) onResize();
      }
    }

    for (var i = 0; i < inputs.length; i++) {
      (function (inp) {
        inp.addEventListener('focus', function () {
          requestAnimationFrame(function () { measure(); });
        });
        inp.addEventListener('click', function () {
          requestAnimationFrame(function () { measure(); });
        });
        inp.addEventListener('input', function () { measure(); });
      })(inputs[i]);
    }
    return measure;
  }

  /**
   * Attach unified keyboard handling to a dialog/popup/dropdown container.
   * Mirrors the DRY pattern of _attachContainerExpandBehavior: one function,
   * called from every dialog, with opts controlling category-specific behavior.
   *
   * @param {HTMLElement} container  - The dialog overlay, dropdown, popup, or panel element
   * @param {Object}      opts
   * @param {string}      opts.category    - 'form' | 'confirmation' | 'settings' | 'informational'
   * @param {Function}    opts.onDismiss   - Called on ESC, or Enter-when-clean (form), or Enter (settings)
   * @param {Function}   [opts.onConfirm]  - Called on Enter-when-dirty (form) or Enter (confirmation/informational)
   * @param {boolean}    [opts.trackDirty] - Auto-attach input/change listeners for dirty tracking
   * @param {Function}   [opts.isDirty]    - Custom dirty predicate; overrides auto-tracking when provided
   * @param {Function}   [opts.enterGuard] - If provided and returns false, Enter is not intercepted
   * @param {HTMLElement|Function} [opts.autoFocus] - Element to focus (or function to call) via requestAnimationFrame
   * @returns {Object}   { markDirty: Function } - API for programmatic dirty marking (smart defaults)
   */
  function _attachDialogKeyboard(container, opts) {
    var dirty = false;
    if (opts.trackDirty) {
      container.addEventListener('input', function () { dirty = true; });
      container.addEventListener('change', function () { dirty = true; });
    }

    container.addEventListener('keydown', function (ev) {
      if (ev.key === 'Escape') {
        ev.preventDefault(); ev.stopPropagation();
        opts.onDismiss();
        return;
      }
      if (ev.key === 'Enter') {
        if (opts.enterGuard && !opts.enterGuard()) return;
        var focused = document.activeElement;
        if (focused && focused.tagName === 'BUTTON' && container.contains(focused)) return;
        ev.preventDefault(); ev.stopPropagation();
        var cat = opts.category;
        if (cat === 'form') {
          var isDirty = opts.isDirty ? opts.isDirty() : dirty;
          if (isDirty && opts.onConfirm) { opts.onConfirm(); } else { opts.onDismiss(); }
        } else if (cat === 'confirmation') {
          if (opts.onConfirm) opts.onConfirm();
        } else if (cat === 'settings') {
          opts.onDismiss();
        } else if (cat === 'informational') {
          if (opts.onConfirm) { opts.onConfirm(); } else { opts.onDismiss(); }
        }
      }
    });

    if (opts.autoFocus) {
      var af = opts.autoFocus;
      requestAnimationFrame(function () {
        if (typeof af === 'function') af(); else if (af.focus) af.focus();
      });
    }

    return { markDirty: function () { dirty = true; } };
  }

  function _promptNewFolder(item, extraItems) {
    var isAsset = item && item.type === 'asset';
    var dialogOverlay = document.createElement('div');
    dialogOverlay.className = 'live-wysiwyg-nav-dialog';
    var content = document.createElement('div');
    content.className = 'live-wysiwyg-nav-dialog-content';
    content.innerHTML = '<p>Create a new folder for this ' + (isAsset ? 'file' : 'page') + ':</p>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline"><span>Folder name</span>' +
      '<input type="text" class="live-wysiwyg-nav-folder-name" placeholder="new-section"></div>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline live-wysiwyg-nav-title-row"><span>Display name</span>' +
      '<input type="text" class="live-wysiwyg-nav-folder-title" placeholder="New Section"></div>' +
      '<div class="live-wysiwyg-nav-settings-row"><label>' +
      '<input type="checkbox" class="live-wysiwyg-nav-skip-index"> Only create folder</label></div>';
    var actions = document.createElement('div');
    actions.className = 'live-wysiwyg-nav-dialog-actions';
    var createBtn = document.createElement('button');
    createBtn.className = 'live-wysiwyg-nav-dialog-primary';
    createBtn.textContent = 'Create';
    var cancelBtn = document.createElement('button');
    cancelBtn.textContent = 'Cancel';
    actions.appendChild(cancelBtn);
    actions.appendChild(createBtn);
    content.appendChild(actions);
    dialogOverlay.appendChild(content);
    document.body.appendChild(dialogOverlay);
    _attachContainerExpandBehavior(content, { prop: 'maxWidth' });

    var nameInput = content.querySelector('.live-wysiwyg-nav-folder-name');
    var titleInput = content.querySelector('.live-wysiwyg-nav-folder-title');
    var skipIndexCheckbox = content.querySelector('.live-wysiwyg-nav-skip-index');

    nameInput.tabIndex = 1;
    titleInput.tabIndex = 2;
    skipIndexCheckbox.tabIndex = 3;
    createBtn.tabIndex = 4;
    cancelBtn.tabIndex = 5;

    var titleRow = content.querySelector('.live-wysiwyg-nav-title-row');

    var dirty = false;
    function markDirty() { dirty = true; }

    function syncTitleRowVisibility() {
      if (skipIndexCheckbox.checked) {
        titleRow.style.display = 'none';
      } else {
        titleRow.style.display = '';
      }
    }

    var defaultName = '';
    var defaultTitle = '';
    if (isAsset) {
      skipIndexCheckbox.checked = true;
      var srcPath = item.src_path || '';
      var fname = srcPath.split('/').pop() || '';
      var dot = fname.lastIndexOf('.');
      var base = dot > 0 ? fname.substring(0, dot) : fname;
      defaultName = base.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
      defaultTitle = base.charAt(0).toUpperCase() + base.slice(1);
    } else if (item && item.title) {
      defaultName = item.title.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
      defaultTitle = item.title;
    }
    if (defaultName) { nameInput.value = defaultName; dirty = true; }
    if (defaultTitle) { titleInput.value = defaultTitle; dirty = true; }
    syncTitleRowVisibility();

    nameInput.addEventListener('input', function () {
      nameInput.value = nameInput.value.replace(/[^a-z0-9-]/g, '');
      markDirty();
    });
    titleInput.addEventListener('input', markDirty);
    skipIndexCheckbox.addEventListener('change', function () {
      syncTitleRowVisibility();
      markDirty();
    });

    _attachDialogKeyboard(dialogOverlay, {
      category: 'form',
      isDirty: function () { return dirty; },
      onConfirm: function () { createBtn.click(); },
      onDismiss: function () { if (dialogOverlay.parentNode) dialogOverlay.parentNode.removeChild(dialogOverlay); },
      autoFocus: function () { nameInput.focus(); nameInput.select(); }
    });

    cancelBtn.addEventListener('click', function () { dialogOverlay.parentNode.removeChild(dialogOverlay); });
    createBtn.addEventListener('click', function () {
      var folderName = nameInput.value.trim();
      var skipIndex = skipIndexCheckbox && skipIndexCheckbox.checked;
      var folderTitle = skipIndex ? folderName : (titleInput.value.trim() || folderName);
      if (!folderName) { nameInput.focus(); return; }
      dialogOverlay.parentNode.removeChild(dialogOverlay);

      var parentDir = item && item.src_path ? _getDir(item.src_path) : '';
      var indexPath = (parentDir ? parentDir + '/' : '') + folderName + '/index.md';

      var allItems = [item];
      if (extraItems && extraItems.length) {
        for (var xi = 0; xi < extraItems.length; xi++) {
          if (extraItems[xi] !== item) allItems.push(extraItems[xi]);
        }
      }

      var syntheticSection = {
        type: 'section',
        title: folderTitle,
        src_path: indexPath,
        children: allItems,
        _new: true,
        _uid: _generateUid()
      };
      if (!skipIndex) {
        syntheticSection.index_meta = { weight: _getItemWeight(item) || 100, headless: false, retitled: true, empty: true };
      }
      syntheticSection._expanded = true;

      if (!skipIndex && _batchClaimedPaths) _batchClaimedPaths.add(indexPath);
      _navBatchQueue.push({
        type: 'create-folder',
        item: item,
        folderName: folderName,
        folderTitle: folderTitle,
        skipIndex: !!skipIndex,
        syntheticSection: syntheticSection
      });
      var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
      var itemSrcPath = _getItemSrcPath(item);

      for (var ei = allItems.length - 1; ei >= 0; ei--) {
        if (allItems[ei] === item) continue;
        var eLoc = _findNavItemInTree(allItems[ei]._uid);
        if (eLoc) eLoc.parent.splice(eLoc.index, 1);
      }

      var itemLoc = _findNavItemInTree(item._uid);
      if (itemLoc) {
        itemLoc.parent.splice(itemLoc.index, 1, syntheticSection);
      } else {
        navItems.push(syntheticSection);
      }

      _setItemWeight(item, 100);
      _syncCurrentPageWeight(itemSrcPath, 100);
      _setNavItemFocused(item);

      if (!_navBadges.some(function (b) { return b.text === 'Review changes'; })) {
        _addNavBadge({
          className: 'live-wysiwyg-nav-normalize-badge',
          text: 'Review changes'
        });
      }
      _commitNavSnapshot();
    });
  }

  function _normalizeLevelWeights(sectionItem) {
    var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
    var indexWeight = (nwCfg.frontmatter_defaults && nwCfg.frontmatter_defaults.index_weight !== undefined)
      ? nwCfg.frontmatter_defaults.index_weight
      : (nwCfg.index_weight !== undefined ? nwCfg.index_weight : -10);

    var levelItems, parentDir;
    if (sectionItem && sectionItem.children) {
      levelItems = sectionItem.children;
      parentDir = _getSectionFolderDir(sectionItem) || '';
    } else {
      levelItems = (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
      parentDir = '';
    }
    if (!levelItems.length) return;

    var orderedItems = [];
    for (var i = 0; i < levelItems.length; i++) {
      var item = levelItems[i];
      if (item._deleted) continue;
      if (item.type === 'page') {
        if (item.isIndex) {
          item.weight = null;
          if (item._fm) item._fm.weight = null;
          continue;
        }
        if (item.headless) continue;
        orderedItems.push(item);
      } else if (item.type === 'section' && item.children) {
        if (!_hasVisibleMdContent(item.children)) continue;
        var folderDir = _getSectionFolderDir(item);

        var indexChild = item.children.find(function (c) { return c.type === 'page' && c.isIndex; });
        if (indexChild && !(indexChild.retitled && indexChild.empty)) {
          var title = indexChild.title || item.title;
          var baseName = _generateFilename(title);
          var claimedPaths = [];
          for (var ci = 0; ci < item.children.length; ci++) {
            if (item.children[ci].src_path) claimedPaths.push(item.children[ci].src_path);
          }
          var existingPaths = (typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [])
            .filter(function (p) { return p.indexOf((folderDir || parentDir) + '/') === 0 && p !== indexChild.src_path; });
          var newFilename = _resolveFilenameConflict(baseName, existingPaths, claimedPaths);
          var fd = folderDir || parentDir;
          var renamedPath = fd ? fd + '/' + newFilename : newFilename;

          indexChild._renamed = true;
          indexChild._originalPath = indexChild.src_path;
          indexChild.src_path = renamedPath;
          indexChild.isIndex = false;

          var newIndexPath = fd ? fd + '/index.md' : 'index.md';
          var thinIndex = {
            type: 'page', src_path: newIndexPath, title: title, isIndex: true,
            retitled: true, empty: true, weight: indexWeight,
            _fm: { title: title, retitled: true, empty: true, weight: indexWeight },
            _new: true, _uid: _generateUid()
          };
          item.children.splice(0, 0, thinIndex);
          if (item.src_path === indexChild._originalPath) {
            item.src_path = newIndexPath;
          }

          orderedItems.push({ _proxy: true, _target: thinIndex, isIndex: true });
          orderedItems.push({ _proxy: true, _target: indexChild });
        } else if (indexChild) {
          orderedItems.push({ _proxy: true, _target: indexChild, isIndex: true, _section: item });
        } else if (item.src_path && item.index_meta) {
          orderedItems.push({ _proxy: true, _target: item, isIndex: true, useIndexMeta: true });
        } else {
          var fd = folderDir || parentDir;
          if (fd) {
            var newIndexPath = fd + '/index.md';
            var sectionTitle = item.title || fd.split('/').pop().replace(/-/g, ' ').replace(/\b\w/g, function (ch) { return ch.toUpperCase(); });
            var thinIndex = {
              type: 'page', src_path: newIndexPath, title: sectionTitle, isIndex: true,
              retitled: true, empty: true, weight: indexWeight,
              _fm: { title: sectionTitle, retitled: true, empty: true, weight: indexWeight },
              _new: true, _uid: _generateUid()
            };
            item.children.splice(0, 0, thinIndex);
            item.src_path = newIndexPath;
            orderedItems.push({ _proxy: true, _target: thinIndex, isIndex: true });
          }
        }
      }
    }
    for (var j = 0; j < orderedItems.length; j++) {
      var w = (j + 1) * 100;
      var entry = orderedItems[j];
      if (entry._proxy) {
        var tgt = entry._target;
        if (entry.useIndexMeta && tgt.index_meta) {
          tgt.index_meta.weight = w;
        } else if (entry.isIndex && tgt.type === 'page') {
          tgt.weight = w;
          if (tgt._fm) tgt._fm.weight = w;
        } else {
          tgt.weight = w;
          if (tgt._fm) tgt._fm.weight = w;
        }
        if (entry._section && entry._section.index_meta) {
          entry._section.index_meta.weight = w;
        }
        var sp = tgt.src_path || '';
        if (sp) _syncCurrentPageWeight(sp, w);
      } else {
        entry.weight = w;
        if (entry._fm) entry._fm.weight = w;
        var sp = _getItemSrcPath(entry);
        if (sp) _syncCurrentPageWeight(sp, w);
      }
    }
  }

  function _findParentSection(uid, items) {
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      if (items[i].children) {
        for (var j = 0; j < items[i].children.length; j++) {
          if (items[i].children[j]._uid === uid) return items[i];
        }
        var found = _findParentSection(uid, items[i].children);
        if (found) return found;
      }
    }
    return null;
  }

  // ======================================================================
  // NAV MENU - Nav edit mode management
  // ======================================================================
  function _enterNavEditModeAsync() {
    if (_navEditMode) return Promise.resolve(true);
    _enterNavEditMode();
    return Promise.resolve(true);
  }

  function _deepCloneNavData(items) {
    if (!items) return items;
    var clone = [];
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      var copy = {};
      for (var k in item) {
        if (item.hasOwnProperty(k)) {
          if (k === 'children') {
            copy.children = _deepCloneNavData(item.children);
          } else if (k === 'index_meta' && item[k] && typeof item[k] === 'object') {
            var metaCopy = {};
            for (var mk in item[k]) {
              if (item[k].hasOwnProperty(mk)) metaCopy[mk] = item[k][mk];
            }
            copy[k] = metaCopy;
          } else if (k === '_fm' && item[k] && typeof item[k] === 'object') {
            var fmCopy = {};
            for (var fk in item[k]) {
              if (item[k].hasOwnProperty(fk)) fmCopy[fk] = item[k][fk];
            }
            copy[k] = fmCopy;
          } else if (k === '_warnings' && Array.isArray(item[k])) {
            copy[k] = item[k].map(function (w) {
              return { reason: w.reason, renames: w.renames || 0 };
            });
          } else if (k === '_deadLinks' && item[k] && typeof item[k] === 'object') {
            copy[k] = {
              internal: item[k].internal ? item[k].internal.map(function (l) { return { text: l.text, target: l.target }; }) : [],
              external: item[k].external ? item[k].external.map(function (l) { return { text: l.text, target: l.target, status: l.status, error: l.error }; }) : []
            };
          } else {
            copy[k] = item[k];
          }
        }
      }
      clone.push(copy);
    }
    return clone;
  }

  function _enterNavEditMode() {
    if (_navEditMode) return;
    _flushHistoryCapture();
    _navEditMode = true;
    if (_batchClaimedPaths) _batchClaimedPaths.clear();

    var cursor = _captureEditorSelection();
    if (cursor) {
      try { _setSetting('live_wysiwyg_nav_edit_cursor', JSON.stringify(cursor)); }
      catch (e) { /* serialization failure */ }
    }

    if (_navSidebarEl) {
      _navSidebarEl.classList.add('live-wysiwyg-nav-edit-mode');
      _addNavEditActions(_navSidebarEl);
    }
    var currentSrcPath = _getCurrentSrcPath();
    if (currentSrcPath && !_navFocusTarget) _navFocusTarget = currentSrcPath;

    _rebuildNavMenuForEditMode();
  }

  

  function _exitNavEditMode(restoreCursor) {
    if (!_navEditMode) return;
    var hasSaveable = _snapshotHasSaveableChanges();
    _navEditMode = false;

    if (_navEditActionsEl && _navEditActionsEl.parentNode) {
      _navEditActionsEl.parentNode.removeChild(_navEditActionsEl);
    }
    _navEditActionsEl = null;

    _clearNavFocus();
    _clearNavGroup();

    if (hasSaveable) {
      _navBatchQueue = [];
      if (_batchClaimedPaths) _batchClaimedPaths.clear();
      _batchRenamedPaths = {};
      _batchDeletedPaths = {};
      _navBadges = [];
      _navMigrationPending = false;
      _navFocusTarget = null;
      _navTopWarnings = [];
      _navTopInfo = [];

      if (restoreCursor && _navSnapshots.length > 0) {
        var initial = _navSnapshots[0];
        _applySnapshotToGlobals(initial);
      }

      var initialSnap = (_navSnapshots.length > 0) ? _navSnapshots[0] : null;
      _navSnapshots = initialSnap ? [initialSnap] : [];
      _navSnapshotIndex = initialSnap ? 0 : -1;
    }

    if (_navSidebarEl) {
      _navSidebarEl.classList.remove('live-wysiwyg-nav-edit-mode');
      _buildNavMenu(_navSidebarEl);
    }

    if (restoreCursor) {
      var raw = _getSetting('live_wysiwyg_nav_edit_cursor');
      if (raw) {
        try {
          var saved = JSON.parse(raw);
          _restoreEditorSelection(saved, document.querySelector('.live-wysiwyg-focus-main'));
        } catch (e) { /* parse error */ }
        _deleteSetting('live_wysiwyg_nav_edit_cursor');
      }
    }
  }

  function _rebuildNavMenuForEditMode() {
    if (!_navSidebarEl) return;
  }

  function _addNavEditActions(sidebarEl) {
    if (_navEditActionsEl) return;
    _navEditActionsEl = document.createElement('div');
    _navEditActionsEl.className = 'live-wysiwyg-nav-edit-actions';

    var saveBtn = document.createElement('button');
    saveBtn.className = 'live-wysiwyg-nav-save-btn';
    saveBtn.textContent = 'Save';
    saveBtn.addEventListener('click', function () { _confirmNavSave(); });

    var discardBtn = document.createElement('button');
    discardBtn.className = 'live-wysiwyg-nav-discard-btn';
    discardBtn.textContent = 'Discard';
    discardBtn.addEventListener('click', function () { _confirmNavDiscard(); });

    var undoBtn = document.createElement('button');
    undoBtn.className = 'live-wysiwyg-nav-undo-btn';
    undoBtn.textContent = '\u21A9 Undo';
    undoBtn.disabled = true;
    undoBtn.addEventListener('click', function () { _navUndo(); });

    var redoBtn = document.createElement('button');
    redoBtn.className = 'live-wysiwyg-nav-redo-btn';
    redoBtn.textContent = 'Redo \u21AA';
    redoBtn.disabled = true;
    redoBtn.addEventListener('click', function () { _navRedo(); });

    var reviewBtn = document.createElement('button');
    reviewBtn.className = 'live-wysiwyg-nav-review-btn';
    reviewBtn.textContent = 'Review Changes';
    reviewBtn.addEventListener('click', function () { _showReviewChangesPopup(reviewBtn); });

    _navEditActionsEl.appendChild(saveBtn);
    _navEditActionsEl.appendChild(discardBtn);
    _navEditActionsEl.appendChild(undoBtn);
    _navEditActionsEl.appendChild(redoBtn);
    _navEditActionsEl.appendChild(reviewBtn);

    sidebarEl.appendChild(_navEditActionsEl);
  }

  function _collectDeletedItems(items, out) {
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item._deleted && item.type === 'section') {
        var fd = _getSectionFolderDir(item);
        out.push({ label: 'Deleting folder ' + (item.title || fd), path: fd + '/' });
      } else if (item._deleted && item.type === 'page') {
        out.push({ label: 'Deleting ' + (item.title || item.src_path), path: item.src_path || '' });
      }
      if (item.children && !item._deleted) {
        _collectDeletedItems(item.children, out);
      }
    }
  }

  function _addNavBadge(descriptor) {
    _navBadges.push(descriptor);
  }

  function _dismissReviewPopup(popup) {
    if (!popup || !popup.parentNode) return;
    popup.classList.remove('live-wysiwyg-nav-review-popup-open');
    var onEnd = function () {
      popup.removeEventListener('transitionend', onEnd);
      if (popup.parentNode) popup.parentNode.removeChild(popup);
    };
    popup.addEventListener('transitionend', onEnd);
    setTimeout(onEnd, 350);
  }

  function _showReviewChangesPopup(anchorBtn) {
    var existing = document.querySelector('.live-wysiwyg-nav-review-popup');
    if (existing) {
      _dismissReviewPopup(existing);
      return;
    }

    var popup = document.createElement('div');
    popup.className = 'live-wysiwyg-nav-review-popup';

    if (_navBadges.length) {
      for (var bi = 0; bi < _navBadges.length; bi++) {
        var bd = _navBadges[bi];
        var badge = document.createElement('span');
        badge.className = bd.className;
        badge.textContent = bd.text;
        if (bd.style) badge.style.cssText = bd.style;
        popup.appendChild(badge);
      }
    }

    var deletedItems = [];
    _collectDeletedItems(typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [], deletedItems);
    if (deletedItems.length) {
      var delHeader = document.createElement('span');
      delHeader.className = 'live-wysiwyg-nav-pending-deletes-header';
      delHeader.textContent = '\u26A0 Saving will delete:';
      popup.appendChild(delHeader);
      for (var di = 0; di < deletedItems.length; di++) {
        var delItem = document.createElement('span');
        delItem.className = 'live-wysiwyg-nav-pending-delete-item';
        delItem.textContent = deletedItems[di].label;
        delItem.title = deletedItems[di].path;
        popup.appendChild(delItem);
      }
    }

    if (!_navBadges.length && !deletedItems.length) {
      var empty = document.createElement('span');
      empty.className = 'live-wysiwyg-nav-review-empty';
      empty.textContent = 'No pending changes to review.';
      popup.appendChild(empty);
    }

    popup.tabIndex = -1;

    var btnRect = anchorBtn.getBoundingClientRect();
    popup.style.left = btnRect.left + 'px';
    popup.style.bottom = (window.innerHeight - btnRect.top + 6) + 'px';
    popup.style.maxWidth = '320px';
    document.body.appendChild(popup);
    requestAnimationFrame(function () {
      popup.classList.add('live-wysiwyg-nav-review-popup-open');
      popup.focus();
    });

    var cleanupListeners = function () {
      document.removeEventListener('click', dismiss, true);
      _reviewPopupDismiss = null;
    };
    var dismiss = function (e) {
      if (!popup.parentNode) { cleanupListeners(); return; }
      if (popup.contains(e.target) || e.target === anchorBtn) return;
      _dismissReviewPopup(popup);
      cleanupListeners();
    };
    _reviewPopupDismiss = function () {
      if (popup.parentNode) {
        _dismissReviewPopup(popup);
        cleanupListeners();
      }
    };
    setTimeout(function () {
      document.addEventListener('click', dismiss, true);
    }, 0);
  }

  // ======================================================================
  // NAV MENU - Undo / Redo
  // ======================================================================
  // NAV MENU - Snapshot-based undo / redo
  // ======================================================================

  function _generateUid() { return '__nav_' + (++_uidCounter); }

  function _assignUids(items) {
    if (!items) return;
    for (var i = 0; i < items.length; i++) {
      if (!items[i]._uid) items[i]._uid = _generateUid();
      if (items[i].children) _assignUids(items[i].children);
    }
  }

  function _attachFrontmatterToNavData(items) {
    var fmMap = typeof liveWysiwygFrontmatterMap !== 'undefined' ? liveWysiwygFrontmatterMap : {};
    (function walk(list) {
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (item.type === 'page' && item.src_path && !item._fm) {
          var source = fmMap[item.src_path];
          item._fm = source ? Object.assign({}, source) : {};
        }
        if (item.children) walk(item.children);
      }
    })(items);
  }

  function _syncFmFields(items) {
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.type === 'page' && item.src_path) {
        if (!item._fm) item._fm = {};
        if (item.title != null && (item._fm.hasOwnProperty('title') || item._new)) {
          item._fm.title = item.title;
        }
        if (item.weight != null) item._fm.weight = item.weight;
        else delete item._fm.weight;
        if (item.headless === true) item._fm.headless = true;
        else delete item._fm.headless;
        if (item.retitled === true) item._fm.retitled = true;
        else delete item._fm.retitled;
        if (item.empty === true) item._fm.empty = true;
        else delete item._fm.empty;
      }
      if (item.children) _syncFmFields(item.children);
    }
  }

  function _djb2Hash(str) {
    var h = 5381;
    for (var i = 0; i < str.length; i++) {
      h = ((h << 5) + h) + str.charCodeAt(i);
      h = h & h;
    }
    return h.toString(36);
  }

  var _navContentHashReplacer = function (key, value) {
    if (key === '_warnings' || key === '_deadLinks' || key === '_expanded' ||
        key === '_focused' || key === '_selected' || key === '_groupMode') return undefined;
    return value;
  };

  function _computeNavContentHash(snap) {
    var parts = [
      JSON.stringify(snap.navData, _navContentHashReplacer),
      JSON.stringify(snap.batchQueue),
      snap.mkdocsYml || '',
      snap.originalMkdocsYml || '',
      snap.migrationPending ? '1' : '0',
      snap.pendingFolderDelete ? JSON.stringify(snap.pendingFolderDelete) : ''
    ];
    return _djb2Hash(parts.join('\x00'));
  }

  function _snapshotHasSaveableChanges() {
    if (_navSnapshotIndex <= 0 || _navSnapshots.length < 2) return false;
    return _navSnapshots[0].contentHash !== _navSnapshots[_navSnapshotIndex].contentHash;
  }

  function _takeNavSnapshot() {
    var nd = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    _syncFmFields(nd);
    var cfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
    var snap = {
      navData: _deepCloneNavData(nd),
      contentHash: null,
      batchQueue: _navBatchQueue.map(function (op) {
        var copy = {};
        for (var k in op) { if (op.hasOwnProperty(k)) copy[k] = op[k]; }
        return copy;
      }),
      badges: _navBadges.slice(),
      migrationPending: _navMigrationPending,
      focusTarget: _navFocusTarget,
      topWarnings: _navTopWarnings.slice(),
      topInfo: _navTopInfo.slice(),
      mkdocsYml: _virtualMkdocsYml,
      originalMkdocsYml: _virtualOriginalMkdocsYml,
      hasNavKey: _ymlHasNavKey(_virtualMkdocsYml),
      navWeightConfig: { installed: !!cfg.installed, enabled: !!cfg.enabled, default_page_weight: cfg.default_page_weight || 1000, frontmatter_defaults: cfg.frontmatter_defaults || null }
    };
    snap.contentHash = _computeNavContentHash(snap);
    return snap;
  }

  function _applySnapshotToGlobals(snapshot) {
    if (typeof liveWysiwygNavData !== 'undefined') {
      liveWysiwygNavData.length = 0;
      var cloned = _deepCloneNavData(snapshot.navData);
      for (var i = 0; i < cloned.length; i++) {
        liveWysiwygNavData.push(cloned[i]);
      }
    }
    _navBatchQueue = snapshot.batchQueue.slice();
    _navBadges = snapshot.badges.slice();
    _navMigrationPending = snapshot.migrationPending;
    _navFocusTarget = snapshot.focusTarget;
    _navTopWarnings = snapshot.topWarnings ? snapshot.topWarnings.slice() : [];
    _navTopInfo = snapshot.topInfo ? snapshot.topInfo.slice() : [];
    _virtualMkdocsYml = snapshot.mkdocsYml != null ? snapshot.mkdocsYml : null;
    _virtualOriginalMkdocsYml = snapshot.originalMkdocsYml != null ? snapshot.originalMkdocsYml : null;
    if (snapshot.navWeightConfig) {
      if (typeof liveWysiwygNavWeightConfig !== 'undefined') {
        liveWysiwygNavWeightConfig.installed = snapshot.navWeightConfig.installed;
        liveWysiwygNavWeightConfig.enabled = snapshot.navWeightConfig.enabled;
        liveWysiwygNavWeightConfig.default_page_weight = snapshot.navWeightConfig.default_page_weight;
        if (snapshot.navWeightConfig.frontmatter_defaults) {
          liveWysiwygNavWeightConfig.frontmatter_defaults = snapshot.navWeightConfig.frontmatter_defaults;
        }
      }
    }
  }

  function _commitNavSnapshot() {
    if (_navSnapshotIndex >= 0 && _navSnapshotIndex < _navSnapshots.length - 1) {
      _navSnapshots.splice(_navSnapshotIndex + 1);
    }
    _navSnapshots.push(_takeNavSnapshot());
    _navSnapshotIndex = _navSnapshots.length - 1;
    _renderNavFromSnapshot();
    _navAutoExitCheck();
  }

  function _captureExpandedFromNavData(items, result) {
    result = result || {};
    if (!items) return result;
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.type === 'section' && item._expanded !== undefined) {
        var dir = _getSectionFolderDir(item) || (item.src_path ? _getDir(item.src_path) : '');
        if (dir) result[dir] = item._expanded;
      }
      if (item.children) _captureExpandedFromNavData(item.children, result);
    }
    return result;
  }

  function _applyExpandedToNavData(items, expandedDirs) {
    if (!items || !expandedDirs) return;
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.type === 'section') {
        var dir = _getSectionFolderDir(item) || (item.src_path ? _getDir(item.src_path) : '');
        if (dir && expandedDirs.hasOwnProperty(dir)) {
          item._expanded = expandedDirs[dir];
        }
      }
      if (item.children) _applyExpandedToNavData(item.children, expandedDirs);
    }
  }

  function _renderNavFromSnapshot() {
    var nd = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    var expandedDirs = _captureExpandedFromNavData(nd);
    var snapshot = (_navSnapshotIndex >= 0 && _navSnapshotIndex < _navSnapshots.length)
      ? _navSnapshots[_navSnapshotIndex] : null;
    if (snapshot) {
      _applySnapshotToGlobals(snapshot);
    }
    nd = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    _applyExpandedToNavData(nd, expandedDirs);
    var scrollTop = _navScrollWrap ? _navScrollWrap.scrollTop : 0;
    _navEditActionsEl = null;
    if (_navSidebarEl) {
      _buildNavMenu(_navSidebarEl);
      var focusedLi = _navSidebarEl.querySelector('.live-wysiwyg-nav-item--focused');
      if (focusedLi && _navScrollWrap) {
        requestAnimationFrame(function () {
          var wrapRect = _navScrollWrap.getBoundingClientRect();
          var liRect = focusedLi.getBoundingClientRect();
          var offsetInWrap = liRect.top - wrapRect.top + _navScrollWrap.scrollTop;
          _navScrollWrap.scrollTop = offsetInWrap - (wrapRect.height / 2) + (liRect.height / 2);
        });
      } else if (_navScrollWrap) {
        _navScrollWrap.scrollTop = scrollTop;
      }
      if (_navSnapshots.length >= 2) {
        _addNavEditActions(_navSidebarEl);
        _updateUndoRedoBtns();
      }
    }
    _persistWarningsFromSnapshot();
  }

  function _snapshotHasNavEditState(snapshot) {
    if (!snapshot || !snapshot.navData) return false;
    var found = false;
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        if (found) return;
        if (items[i]._selected || items[i]._focused) { found = true; return; }
        if (items[i].children) walk(items[i].children);
      }
    })(snapshot.navData);
    return found;
  }

  function _ensureNavEditModeForSnapshot() {
    var snap = (_navSnapshotIndex >= 0 && _navSnapshotIndex < _navSnapshots.length)
      ? _navSnapshots[_navSnapshotIndex] : null;
    if (!_navEditMode && snap && _snapshotHasNavEditState(snap)) {
      _navEditMode = true;
      if (_navSidebarEl) _navSidebarEl.classList.add('live-wysiwyg-nav-edit-mode');
    }
  }

  function _navAutoExitCheck() {
    if (_navEditMode && !_navKeyboardActiveItem && !_hasAnyNavSelected() && !_snapshotHasSaveableChanges()) {
      _exitNavEditMode(true);
    }
  }

  function _navUndo() {
    if (_navSnapshotIndex <= 0) return;
    _navSnapshotIndex--;
    _ensureNavEditModeForSnapshot();
    _renderNavFromSnapshot();
    _navAutoExitCheck();
  }

  function _navRedo() {
    if (_navSnapshotIndex >= _navSnapshots.length - 1) return;
    _navSnapshotIndex++;
    _ensureNavEditModeForSnapshot();
    _renderNavFromSnapshot();
    _navAutoExitCheck();
  }

  function _findNavLi(item) {
    if (!_navSidebarEl || !item) return null;
    if (item._uid) {
      var byUid = _navSidebarEl.querySelector('[data-nav-uid="' + item._uid + '"]');
      if (byUid) return byUid;
    }
    var p = _getItemSrcPath(item);
    if (!p) return null;
    if (item.type === 'section') {
      var sectionEl = _navSidebarEl.querySelector('[data-nav-index-path="' + p + '"]');
      if (sectionEl) return sectionEl;
    }
    return _findNavLiByPath(p);
  }

  function _findNavLiByPath(path) {
    if (!_navSidebarEl || !path) return null;
    var el = _navSidebarEl.querySelector('[data-nav-src-path="' + path + '"]');
    if (!el && path.endsWith('/index.md')) {
      el = _navSidebarEl.querySelector('[data-nav-index-path="' + path + '"]');
    }
    return el;
  }

  function _updateUndoRedoBtns() {
    if (!_navEditActionsEl) return;
    var undoBtn = _navEditActionsEl.querySelector('.live-wysiwyg-nav-undo-btn');
    var redoBtn = _navEditActionsEl.querySelector('.live-wysiwyg-nav-redo-btn');
    if (undoBtn) undoBtn.disabled = _navSnapshotIndex <= 0;
    if (redoBtn) redoBtn.disabled = _navSnapshotIndex >= _navSnapshots.length - 1;
    var hasSaveable = _snapshotHasSaveableChanges();
    var vis = hasSaveable ? '' : 'hidden';
    var saveBtn = _navEditActionsEl.querySelector('.live-wysiwyg-nav-save-btn');
    var discardBtn = _navEditActionsEl.querySelector('.live-wysiwyg-nav-discard-btn');
    if (saveBtn) saveBtn.style.visibility = vis;
    if (discardBtn) discardBtn.style.visibility = vis;
    var reviewBtn = _navEditActionsEl.querySelector('.live-wysiwyg-nav-review-btn');
    if (reviewBtn) reviewBtn.style.visibility = vis;
    var targetDots = _navSidebarEl ? _navSidebarEl.querySelectorAll('.live-wysiwyg-nav-target-dot') : [];
    for (var i = 0; i < targetDots.length; i++) {
      targetDots[i].style.visibility = vis;
    }
  }

  function _findNavItemInTree(uid, items) {
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      if (items[i]._uid === uid) return { parent: items, index: i };
      if (items[i].children) {
        var found = _findNavItemInTree(uid, items[i].children);
        if (found) return found;
      }
    }
    return null;
  }

  function _findNavItemByPath(srcPath, items) {
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      if (items[i].src_path === srcPath) return items[i];
      if (items[i].children) {
        var found = _findNavItemByPath(srcPath, items[i].children);
        if (found) return found;
      }
    }
    return null;
  }

  function _collectNavWarnings(items) {
    var result = [];
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      var srcPath = item.src_path || '';
      if (item._warnings && item._warnings.length) {
        result.push({ path: srcPath, reasons: item._warnings.map(function (w) { return w.reason; }), renames: item._warnings[0].renames || 0 });
      }
      if (item.children) {
        result = result.concat(_collectNavWarnings(item.children));
      }
    }
    return result;
  }

  function _collectNavDeadLinks(items) {
    var result = [];
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item._deadLinks && (item._deadLinks.internal.length || item._deadLinks.external.length)) {
        result.push({ path: item.src_path || '', internal: item._deadLinks.internal, external: item._deadLinks.external });
      }
      if (item.children) {
        result = result.concat(_collectNavDeadLinks(item.children));
      }
    }
    return result;
  }

  function _applyStoredWarningsToNavData() {
    var cautionPages = _getCautionPages();
    var deadLinkPages = _getDeadLinkPages();
    for (var i = 0; i < cautionPages.length; i++) {
      var cp = cautionPages[i];
      var item = _findNavItemByPath(cp.path);
      if (!item) continue;
      if (!item._warnings) item._warnings = [];
      for (var r = 0; r < cp.reasons.length; r++) {
        var alreadyPresent = false;
        for (var w = 0; w < item._warnings.length; w++) {
          if (item._warnings[w].reason === cp.reasons[r]) { alreadyPresent = true; break; }
        }
        if (!alreadyPresent) item._warnings.push({ reason: cp.reasons[r], renames: cp.renames || 0 });
      }
    }
    for (var d = 0; d < deadLinkPages.length; d++) {
      var dp = deadLinkPages[d];
      var dlItem = _findNavItemByPath(dp.path);
      if (!dlItem) continue;
      dlItem._deadLinks = {
        internal: dp.internal || [],
        external: dp.external || []
      };
    }
  }

  function _removeNavWarningReason(item, reason) {
    if (!item || !item._warnings) return;
    for (var i = item._warnings.length - 1; i >= 0; i--) {
      if (item._warnings[i].reason === reason) {
        item._warnings.splice(i, 1);
      }
    }
    if (!item._warnings.length) delete item._warnings;
  }

  function _clearAllNavWarnings(items) {
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      delete items[i]._warnings;
      delete items[i]._deadLinks;
      if (items[i].children) _clearAllNavWarnings(items[i].children);
    }
  }

  function _clearAllNavDeadLinks(items) {
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      delete items[i]._deadLinks;
      _removeNavWarningReason(items[i], 'Internal dead links found');
      _removeNavWarningReason(items[i], 'External dead links found');
      if (items[i].children) _clearAllNavDeadLinks(items[i].children);
    }
  }

  function _persistWarningsFromSnapshot() {
    var items = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    _setCautionPages(_collectNavWarnings(items));
    _setDeadLinkPages(_collectNavDeadLinks(items));
  }

  function _flattenNavTree(items, parentUid, parentDir, result) {
    result = result || {};
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item._deleted) continue;
      var srcPath = _getItemSrcPath(item);
      var folderDir = item.type === 'section' ? _getSectionFolderDir(item) : null;
      result[item._uid] = {
        item: item, parentUid: parentUid || null, index: i,
        srcPath: srcPath, folderDir: folderDir,
        itemType: item.type || 'page',
        weight: item.weight != null ? item.weight : (item.index_meta && item.index_meta.weight != null ? item.index_meta.weight : null),
        title: item.title,
        headless: item.headless || (item.index_meta && item.index_meta.headless) || false,
        parentDir: parentDir || ''
      };
      if (item.children) {
        _flattenNavTree(item.children, item._uid, folderDir || parentDir, result);
      }
    }
    return result;
  }

  function _findSectionByPath(items, path) {
    for (var i = 0; i < items.length; i++) {
      if (items[i].type === 'section') {
        var sp = _getItemSrcPath(items[i]);
        var fd = _getSectionFolderDir(items[i]);
        if (sp === path || fd === path) return items[i];
        if (items[i].children) {
          var found = _findSectionByPath(items[i].children, path);
          if (found) return found;
        }
      }
    }
    return null;
  }

  function _countAffectedDocsFromSnapshots() {
    if (_navSnapshots.length < 2 || _navSnapshotIndex < 1) return 0;
    var origFlat = _flattenNavTree(_navSnapshots[0].navData, null, '');
    var currFlat = _flattenNavTree(_navSnapshots[_navSnapshotIndex].navData, null, '');
    var count = 0;
    var uid;
    var _dirCache = {};
    function _rDir(suid) {
      if (_dirCache.hasOwnProperty(suid)) return _dirCache[suid];
      var cE = currFlat[suid];
      if (!cE || !cE.folderDir) { _dirCache[suid] = null; return null; }
      var base = cE.folderDir.split('/').pop();
      var pDir = '';
      if (cE.parentUid && currFlat[cE.parentUid] && currFlat[cE.parentUid].folderDir) {
        pDir = _rDir(cE.parentUid) || '';
      }
      var d = pDir ? pDir + '/' + base : base;
      _dirCache[suid] = d;
      return d;
    }
    for (uid in origFlat) {
      if (!origFlat.hasOwnProperty(uid)) continue;
      var oE = origFlat[uid];
      if (oE.folderDir) continue;
      if (!oE.srcPath) continue;
      if (!currFlat[uid]) { count++; continue; }
      var desiredPath = _computeDesiredItemPath(uid, currFlat, _rDir);
      if (desiredPath !== oE.srcPath) { count++; continue; }
      if (oE.itemType !== 'asset') {
        var cFm = currFlat[uid].item._fm || {};
        var oFm = oE.item._fm || {};
        var fmChanged = false;
        for (var k in cFm) { if (cFm.hasOwnProperty(k) && cFm[k] !== oFm[k]) { fmChanged = true; break; } }
        if (!fmChanged) { for (var k2 in oFm) { if (oFm.hasOwnProperty(k2) && !(k2 in cFm)) { fmChanged = true; break; } } }
        if (fmChanged) count++;
      }
    }
    for (uid in currFlat) {
      if (!currFlat.hasOwnProperty(uid)) continue;
      if (origFlat[uid]) continue;
      if (currFlat[uid].folderDir) continue;
      if (currFlat[uid].srcPath) count++;
    }
    return count;
  }

  // ======================================================================
  // NAV MENU - Save and Discard
  // ======================================================================
  function _confirmNavSave() {
    _proceedWithNavSave();
  }

  function _proceedWithNavSave() {
    _executeNavBatchSave();
  }

  function _confirmNavDiscard() {
    _exitNavEditMode(true);
  }

  // ======================================================================
  // NAV MENU - Diff-based save plan
  // ======================================================================

  function _computeDesiredItemPath(uid, currFlat, resolveDesiredDir) {
    var entry = currFlat[uid];
    if (!entry || !entry.srcPath) return null;
    var fileName = entry.srcPath.split('/').pop();
    var parentDir = '';
    if (entry.parentUid && currFlat[entry.parentUid] && currFlat[entry.parentUid].folderDir) {
      parentDir = resolveDesiredDir(entry.parentUid) || '';
    }
    return parentDir ? parentDir + '/' + fileName : fileName;
  }

  function _computeSavePlan(originalSnap, currentSnap) {
    var origFlat = _flattenNavTree(originalSnap.navData, null, '');
    var currFlat = _flattenNavTree(currentSnap.navData, null, '');

    var items = [];
    var sections = [];
    var uid;

    var _sectionDesiredDirCache = {};
    function _resolveDesiredDir(suid) {
      if (_sectionDesiredDirCache.hasOwnProperty(suid)) return _sectionDesiredDirCache[suid];
      var cEntry = currFlat[suid];
      if (!cEntry || !cEntry.folderDir) { _sectionDesiredDirCache[suid] = null; return null; }
      var baseName = cEntry.folderDir.split('/').pop();
      var effectiveParentDir = '';
      if (cEntry.parentUid && currFlat[cEntry.parentUid] && currFlat[cEntry.parentUid].folderDir) {
        effectiveParentDir = _resolveDesiredDir(cEntry.parentUid) || '';
      }
      var desired = effectiveParentDir ? effectiveParentDir + '/' + baseName : baseName;
      _sectionDesiredDirCache[suid] = desired;
      return desired;
    }

    for (uid in origFlat) {
      if (!origFlat.hasOwnProperty(uid)) continue;
      var origEntry = origFlat[uid];

      if (origEntry.folderDir) {
        if (currFlat[uid]) {
          var _sDesiredDir = _resolveDesiredDir(uid) || origEntry.folderDir;
          sections.push({ uid: uid, diskDir: origEntry.folderDir, desiredDir: _sDesiredDir, isNew: false, isDeleted: false });
        } else {
          sections.push({ uid: uid, diskDir: origEntry.folderDir, desiredDir: null, isNew: false, isDeleted: true });
        }
        continue;
      }

      if (!origEntry.srcPath) continue;

      var isAsset = origEntry.itemType === 'asset';

      if (!currFlat[uid]) {
        items.push({
          uid: uid, diskPath: origEntry.srcPath, desiredPath: null,
          itemType: isAsset ? 'asset' : 'page',
          desiredFm: null, origFm: isAsset ? null : (origEntry.item._fm || {}),
          setContent: null, createContent: null,
          isNew: false, isDeleted: true,
          isIndex: !isAsset && origEntry.srcPath.endsWith('index.md'),
          newFrontmatter: false
        });
      } else {
        var currE = currFlat[uid];
        var desiredPath = _computeDesiredItemPath(uid, currFlat, _resolveDesiredDir);
        if (isAsset) {
          items.push({
            uid: uid, diskPath: origEntry.srcPath, desiredPath: desiredPath,
            itemType: 'asset',
            desiredFm: null, origFm: null,
            setContent: null, createContent: null,
            isNew: false, isDeleted: false,
            isIndex: false, newFrontmatter: false
          });
        } else {
          var cFm = currE.item._fm || {};
          var oFm = origEntry.item._fm || {};
          var isNewFm = oFm.weight === undefined && oFm.headless === undefined &&
            oFm.retitled === undefined && oFm.empty === undefined;
          items.push({
            uid: uid, diskPath: origEntry.srcPath, desiredPath: desiredPath,
            itemType: 'page',
            desiredFm: cFm, origFm: oFm,
            setContent: typeof currE.item.setContent === 'string' ? currE.item.setContent : null,
            createContent: null,
            isNew: false, isDeleted: false,
            isIndex: desiredPath ? desiredPath.endsWith('index.md') : false,
            newFrontmatter: isNewFm
          });
        }
      }
    }

    for (uid in currFlat) {
      if (!currFlat.hasOwnProperty(uid)) continue;
      if (origFlat[uid]) continue;
      var newE = currFlat[uid];

      if (newE.folderDir) {
        sections.push({ uid: uid, diskDir: null, desiredDir: newE.folderDir, isNew: true, isDeleted: false });
        continue;
      }
      if (!newE.srcPath) continue;

      if (newE.itemType === 'asset') {
        items.push({
          uid: uid, diskPath: null, desiredPath: newE.srcPath,
          itemType: 'asset',
          desiredFm: null, origFm: null,
          setContent: null, createContent: null,
          isNew: true, isDeleted: false,
          isIndex: false, newFrontmatter: false
        });
        continue;
      }

      var createContent = null;
      for (var qi = 0; qi < currentSnap.batchQueue.length; qi++) {
        var qop = currentSnap.batchQueue[qi];
        if (qop.type === 'create-page' && qop.path === newE.srcPath) {
          createContent = qop.content != null ? qop.content : '';
          break;
        }
      }
      if (createContent === null && newE.item && typeof newE.item.setContent === 'string') {
        createContent = '';
      }
      if (createContent === null && newE.item && newE.item._new) {
        createContent = '';
      }

      items.push({
        uid: uid, diskPath: null, desiredPath: newE.srcPath,
        itemType: 'page',
        desiredFm: newE.item._fm || {}, origFm: {},
        setContent: typeof newE.item.setContent === 'string' ? newE.item.setContent : null,
        createContent: createContent,
        isNew: true, isDeleted: false,
        isIndex: newE.srcPath.endsWith('index.md'),
        newFrontmatter: false
      });
    }

    var convertOps = [];
    for (var bqi = 0; bqi < currentSnap.batchQueue.length; bqi++) {
      var bqop = currentSnap.batchQueue[bqi];
      if (bqop.type === 'convert-folder-to-page' || bqop.type === 'regenerate-index') {
        convertOps.push(bqop);
      }
    }

    var createFolderOps = [];
    for (uid in currFlat) {
      if (!currFlat.hasOwnProperty(uid)) continue;
      if (origFlat[uid]) continue;
      var newSec = currFlat[uid];
      if (!newSec.folderDir) continue;
      for (var cfi = 0; cfi < currentSnap.batchQueue.length; cfi++) {
        var cfop = currentSnap.batchQueue[cfi];
        if (cfop.type === 'create-folder' && cfop.syntheticSection && cfop.syntheticSection._uid === uid) {
          createFolderOps.push({
            type: 'create-folder', item: cfop.item,
            folderName: cfop.folderName, folderTitle: cfop.folderTitle,
            skipIndex: cfop.skipIndex,
            syntheticSection: cfop.syntheticSection
          });
          break;
        }
      }
    }

    var mkdocsYmlOps = [];
    if (currentSnap.mkdocsYml != null && currentSnap.mkdocsYml !== originalSnap.mkdocsYml) {
      mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: '../mkdocs.yml', content: currentSnap.mkdocsYml });
      if (currentSnap.originalMkdocsYml != null && typeof liveWysiwygOriginalMkdocsYml === 'string' && liveWysiwygOriginalMkdocsYml) {
        mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: liveWysiwygOriginalMkdocsYml, content: currentSnap.originalMkdocsYml });
      }
    }

    return {
      items: items,
      sections: sections,
      convertOps: convertOps,
      createFolderOps: createFolderOps,
      mkdocsYmlOps: mkdocsYmlOps
    };
  }

  // ======================================================================
  // NAV MENU - Disk operation planner (converts desired state to ops)
  // ======================================================================

  function _planDiskOperations(desiredState) {
    var batch1 = [];
    var batch2DeleteFiles = [];
    var batch2MoveFiles = [];
    var batch2CreateFiles = [];
    var batch2ContentMigration = [];
    var i, p;
    var items = desiredState.items || [];

    // --- Folder rename detection from page + asset moves ---
    var dirMoves = {};
    var filesByDiskDir = {};

    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (p.isNew || p.isDeleted || !p.diskPath || !p.desiredPath) continue;
      var diskDir = _getDir(p.diskPath);
      if (!filesByDiskDir[diskDir]) filesByDiskDir[diskDir] = [];
      filesByDiskDir[diskDir].push(p);

      if (p.diskPath !== p.desiredPath) {
        var destDir = _getDir(p.desiredPath);
        if (diskDir !== destDir) {
          if (!dirMoves[diskDir]) dirMoves[diskDir] = {};
          if (!dirMoves[diskDir][destDir]) dirMoves[diskDir][destDir] = [];
          dirMoves[diskDir][destDir].push(p);
        }
      }
    }

    var folderRenames = [];
    var coveredByFolderRename = {};

    for (var srcDir in dirMoves) {
      if (!dirMoves.hasOwnProperty(srcDir)) continue;
      var destDirs = Object.keys(dirMoves[srcDir]);
      if (destDirs.length !== 1) continue;

      var onlyDestDir = destDirs[0];
      var movedFiles = dirMoves[srcDir][onlyDestDir];
      var allFilesInDir = filesByDiskDir[srcDir] || [];

      var allAccountedFor = true;
      for (var ai = 0; ai < allFilesInDir.length; ai++) {
        var ap = allFilesInDir[ai];
        if (ap.isDeleted) continue;
        if (ap.diskPath === ap.desiredPath) { allAccountedFor = false; break; }
        if (_getDir(ap.desiredPath) !== onlyDestDir) { allAccountedFor = false; break; }
      }
      if (!allAccountedFor || movedFiles.length === 0) continue;

      var relativePathsMatch = true;
      for (var ri = 0; ri < movedFiles.length; ri++) {
        var rp = movedFiles[ri];
        if (rp.diskPath.substring(srcDir.length) !== rp.desiredPath.substring(onlyDestDir.length)) {
          relativePathsMatch = false;
          break;
        }
      }
      if (!relativePathsMatch) continue;

      folderRenames.push({ oldFolder: srcDir, newFolder: onlyDestDir });
      for (var ci = 0; ci < movedFiles.length; ci++) {
        coveredByFolderRename[movedFiles[ci].uid] = true;
      }
    }

    folderRenames.sort(function (a, b) {
      return (b.newFolder.match(/\//g) || []).length - (a.newFolder.match(/\//g) || []).length;
    });

    var precomputedRenames = {};
    for (var fri = 0; fri < folderRenames.length; fri++) {
      var frPfx = folderRenames[fri].oldFolder + '/';
      var frNewPfx = folderRenames[fri].newFolder + '/';
      for (var pi = 0; pi < items.length; pi++) {
        var fp = items[pi];
        if (!fp.diskPath || fp.isNew) continue;
        var resolvedPath = precomputedRenames[fp.diskPath] || fp.diskPath;
        if (resolvedPath.indexOf(frPfx) === 0) {
          precomputedRenames[fp.diskPath] = frNewPfx + resolvedPath.substring(frPfx.length);
        }
      }
      batch1.push({ type: 'rename-folder', oldFolder: folderRenames[fri].oldFolder, newFolder: folderRenames[fri].newFolder });
    }

    // --- Folder deletes ---
    for (i = 0; i < desiredState.sections.length; i++) {
      var sec = desiredState.sections[i];
      if (!sec.isDeleted || !sec.diskDir) continue;
      var secPrefix = sec.diskDir + '/';
      var hasLivingChildren = false;
      for (var mi = 0; mi < items.length; mi++) {
        var mp = items[mi];
        if (!mp.isDeleted && mp.diskPath && !mp.isNew && mp.diskPath.indexOf(secPrefix) === 0) {
          hasLivingChildren = true;
          break;
        }
        if (!mp.isDeleted && mp.desiredPath && mp.desiredPath.indexOf(secPrefix) === 0) {
          hasLivingChildren = true;
          break;
        }
      }
      if (!hasLivingChildren) {
        batch1.push({ type: 'delete-folder', folder: sec.diskDir });
      }
    }

    // --- Batch 1 (continued): Asset (binary) file moves ---
    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (p.itemType !== 'asset') continue;
      if (p.isNew || p.isDeleted || !p.diskPath || !p.desiredPath) continue;
      if (p.diskPath === p.desiredPath) continue;
      if (coveredByFolderRename[p.uid]) continue;
      batch1.push({ type: 'move-file', oldPath: p.diskPath, newPath: p.desiredPath });
    }

    // --- Batch 2: Deletes ---
    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (!p.isDeleted || !p.diskPath) continue;
      if (p.itemType === 'asset') {
        batch2DeleteFiles.push({ type: 'delete-file', path: p.diskPath });
      } else {
        batch2DeleteFiles.push({ type: 'delete-page', path: p.diskPath, item: { src_path: p.diskPath } });
      }
    }

    // --- Batch 2: Page moves ---
    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (p.itemType !== 'page') continue;
      if (p.isNew || p.isDeleted || !p.diskPath || !p.desiredPath) continue;
      if (p.diskPath === p.desiredPath) continue;
      if (coveredByFolderRename[p.uid]) continue;
      batch2MoveFiles.push({ type: 'rename-page', oldPath: p.diskPath, newPath: p.desiredPath, item: { src_path: p.desiredPath }, skipDoubleRenderCheck: true });
    }

    var convertOps = desiredState.convertOps || [];
    var createFolderOps = desiredState.createFolderOps || [];

    // --- Batch 2: Creates (pages only) ---
    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (p.itemType !== 'page') continue;
      if (!p.isNew || !p.desiredPath || p.createContent === null) continue;
      batch2CreateFiles.push({
        type: 'create-page', path: p.desiredPath, content: p.createContent,
        item: { src_path: p.desiredPath, title: (p.desiredFm && p.desiredFm.title) || p.desiredPath }
      });
    }

    // --- Batch 2: Content migration (pages only) ---
    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (p.itemType !== 'page') continue;
      if (p.isDeleted || !p.desiredPath) continue;

      var dFm = p.desiredFm || {};
      var oFm = p.origFm || {};
      var hasSetContent = p.setContent !== null;
      var hasFmKeys = Object.keys(dFm).length > 0;
      if (hasFmKeys || hasSetContent) {
        var fmOp = {
          type: 'set-frontmatter', src_path: p.desiredPath,
          fm: dFm, origFm: oFm,
          isIndex: p.isIndex, newFrontmatter: p.newFrontmatter
        };
        if (hasSetContent) fmOp.setContent = p.setContent;
        batch2ContentMigration.push(fmOp);
      }
    }

    // --- Link rewrite aggregation ---
    var allRenames = {};
    for (var prk in precomputedRenames) {
      if (precomputedRenames.hasOwnProperty(prk)) allRenames[prk] = precomputedRenames[prk];
    }
    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (p.diskPath && p.desiredPath && p.diskPath !== p.desiredPath && !p.isNew) {
        allRenames[p.diskPath] = p.desiredPath;
      }
    }
    var deletedPaths = {};
    for (i = 0; i < items.length; i++) {
      p = items[i];
      if (p.isDeleted && p.diskPath) deletedPaths[p.diskPath] = true;
    }
    if (Object.keys(allRenames).length || Object.keys(deletedPaths).length) {
      batch2ContentMigration.push({ type: 'rewrite-links', renameMap: allRenames, deletedPaths: deletedPaths });
    }

    var mkdocsYmlOps = desiredState.mkdocsYmlOps || [];

    var _finalBatch2 = [].concat(mkdocsYmlOps, batch2DeleteFiles, batch2MoveFiles, convertOps, createFolderOps, batch2CreateFiles, batch2ContentMigration);
    return {
      batch1: batch1,
      batch2: _finalBatch2,
      precomputedRenames: precomputedRenames
    };
  }

  // ======================================================================
  // NAV MENU - Batch save execution
  // ======================================================================
  function _executeNavBatchSave() {
    var contentEl = document.querySelector('.live-wysiwyg-focus-content');
    if (!contentEl) { _exitNavEditMode(false); return; }

    if (_navSnapshots.length < 2 || _navSnapshotIndex < 0) {
      _exitNavEditMode(false);
      return;
    }

    var originalSnap = _navSnapshots[0];
    var activeSnap = _navSnapshots[_navSnapshotIndex];

    var desiredState = _computeSavePlan(originalSnap, activeSnap);
    var plan = _planDiskOperations(desiredState);

    var orderedOps = [];
    if (plan.batch1.length) {
      orderedOps = orderedOps.concat(plan.batch1);
      orderedOps.push({ type: 'wait-for-rebuild' });
    }
    orderedOps = orderedOps.concat(plan.batch2);

    if (wysiwygEditor && wysiwygEditor._isDocDirty && wysiwygEditor._isDocDirty()) {
      if (wysiwygEditor._finalizeUpdate) {
        if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
          wysiwygEditor._finalizeUpdate(wysiwygEditor.editableArea.innerHTML);
        } else if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
          wysiwygEditor._finalizeUpdate(wysiwygEditor.markdownArea.value);
        }
      }
      var ta = document.querySelector('.live-edit-source');
      var docContent = ta ? ta.value : '';
      var docPath = _getCurrentSrcPath();
      var docTitle = document.title ? document.title.split(' - ')[0].trim() : docPath;
      orderedOps.unshift({ type: 'save-content', src_path: docPath, content: docContent, title: docTitle });
    }

    var focusTarget = activeSnap.focusTarget || _getCurrentSrcPath() || null;

    if (activeSnap.migrationPending) {
      _setSetting('live_wysiwyg_migration_result', 'success');
      _setSetting('live_wysiwyg_migration_normalize', '1');
    }
    _persistWarningsFromSnapshot();
    _exitNavEditMode(false);
    _warningDirectMode = true;
    _runBatchOps(contentEl, orderedOps, focusTarget, { precomputedRenames: plan.precomputedRenames });
  }

  // ======================================================================
  // NAV MENU - Persistent changes pipeline
  // ======================================================================
  var _PIPELINE_KEY = 'live_wysiwyg_changes_pipeline';

  function _loadPipeline() {
    try {
      var raw = localStorage.getItem(_PIPELINE_KEY);
      if (!raw) return [];
      var parsed = JSON.parse(raw);
      if (!Array.isArray(parsed)) { _clearPipeline(); return []; }
      for (var i = 0; i < parsed.length; i++) {
        var stage = parsed[i];
        if (!stage || typeof stage.title !== 'string' || !Array.isArray(stage.batches)) {
          console.warn('[storage] Invalid pipeline stage at index ' + i + ', clearing pipeline');
          _clearPipeline();
          return [];
        }
        for (var j = 0; j < stage.batches.length; j++) {
          var batch = stage.batches[j];
          if (!batch || !Array.isArray(batch.ops)) {
            console.warn('[storage] Invalid pipeline batch at stage ' + i + ' batch ' + j + ', clearing pipeline');
            _clearPipeline();
            return [];
          }
        }
      }
      return parsed;
    } catch (e) {
      console.warn('[storage] Failed to parse pipeline, clearing:', e);
      _clearPipeline();
      return [];
    }
  }

  function _savePipeline(pipeline) {
    try { localStorage.setItem(_PIPELINE_KEY, JSON.stringify(pipeline)); }
    catch (e) { /* quota exceeded or private browsing */ }
  }

  function _clearPipeline() {
    try { localStorage.removeItem(_PIPELINE_KEY); }
    catch (e) { /* ignore */ }
  }

  function _createPipelineStage(title, batches) {
    return {
      title: title,
      batches: batches.map(function (b) { return { title: b.title, ops: b.ops, type: b.type, completed: false }; }),
      completed: false
    };
  }

  function _showPipelineProgress(stageTitle, batchTitle, overall) {
    var bar = document.getElementById('live-wysiwyg-pipeline-progress');
    if (!bar) {
      bar = document.createElement('div');
      bar.id = 'live-wysiwyg-pipeline-progress';
      bar.style.cssText = 'position:fixed;top:0;left:0;right:0;z-index:100001;background:var(--md-primary-fg-color,#4051b5);' +
        'color:#fff;padding:8px 16px;font-size:.82rem;display:flex;align-items:center;gap:12px;';
      var label = document.createElement('span');
      label.className = 'live-wysiwyg-pipeline-label';
      bar.appendChild(label);
      var fill = document.createElement('div');
      fill.style.cssText = 'flex:1;height:6px;background:rgba(255,255,255,.25);border-radius:3px;overflow:hidden;';
      var inner = document.createElement('div');
      inner.className = 'live-wysiwyg-pipeline-fill';
      inner.style.cssText = 'height:100%;background:#fff;border-radius:3px;transition:width .3s;width:0%;';
      fill.appendChild(inner);
      bar.appendChild(fill);
      document.body.appendChild(bar);
    }
    var labelEl = bar.querySelector('.live-wysiwyg-pipeline-label');
    var fillEl = bar.querySelector('.live-wysiwyg-pipeline-fill');
    if (labelEl) labelEl.textContent = stageTitle + (batchTitle ? ' \u2014 ' + batchTitle : '');
    if (fillEl) fillEl.style.width = Math.min(100, Math.round(overall)) + '%';
  }

  function _hidePipelineProgress() {
    var bar = document.getElementById('live-wysiwyg-pipeline-progress');
    if (bar && bar.parentNode) bar.parentNode.removeChild(bar);
  }

  function _resumePipeline() {
    try {
      var pipeline = _loadPipeline();
      if (!pipeline.length) return;
      var stageIdx = -1;
      for (var i = 0; i < pipeline.length; i++) {
        if (!pipeline[i].completed) { stageIdx = i; break; }
      }
      if (stageIdx === -1) { _clearPipeline(); return; }
      _executePipelineStage(pipeline, stageIdx);
    } catch (e) {
      console.error('[storage] Pipeline resume failed, clearing pipeline:', e);
      _clearPipeline();
      _hidePipelineProgress();
    }
  }

  function _executePipelineStage(pipeline, stageIdx) {
    var stage = pipeline[stageIdx];
    var totalStages = pipeline.length;

    function nextBatch(batchIdx) {
      if (batchIdx >= stage.batches.length) {
        stage.completed = true;
        _savePipeline(pipeline);
        if (stageIdx < totalStages - 1) {
          _installReloadGuard();
          _userActionInProgress = true;
          _waitForRebuild(function () {
            _userActionInProgress = false;
            _executePipelineStage(pipeline, stageIdx + 1);
          });
        } else {
          _clearPipeline();
          _hidePipelineProgress();
          _userActionInProgress = true;
          _installReloadGuard();
          _waitForRebuild(function () {
            _userActionInProgress = false;
            location.reload();
          });
        }
        return;
      }

      var batch = stage.batches[batchIdx];
      var overall = ((stageIdx / totalStages) + ((batchIdx / stage.batches.length) * (1 / totalStages))) * 100;
      _showPipelineProgress(stage.title, batch.title, overall);

      if (!batch.ops.length) {
        batch.completed = true;
        _savePipeline(pipeline);
        nextBatch(batchIdx + 1);
        return;
      }

      var contentEl = document.querySelector('.live-wysiwyg-focus-content');
      if (!contentEl) {
        contentEl = document.createElement('div');
        contentEl.className = 'live-wysiwyg-focus-content';
        document.body.appendChild(contentEl);
      }
      _runBatchOps(contentEl, batch.ops, null);
      batch.completed = true;
      _savePipeline(pipeline);
      overall = ((stageIdx / totalStages) + (((batchIdx + 1) / stage.batches.length) * (1 / totalStages))) * 100;
      _showPipelineProgress(stage.title, batch.title, overall);
      nextBatch(batchIdx + 1);
    }

    var firstIncomplete = 0;
    for (var bi = 0; bi < stage.batches.length; bi++) {
      if (!stage.batches[bi].completed) { firstIncomplete = bi; break; }
    }
    nextBatch(firstIncomplete);
  }

  function _getOpLabel(op) {
    if (op.type === 'wait-for-rebuild') return 'Waiting for rebuild...';
    if (op.type === 'save-content') return 'Saving \'' + (op.title || op.src_path) + '\'';
    if (op.type === 'rename-folder') return 'Renaming folder ' + op.oldFolder + ' \u2192 ' + op.newFolder;
    if (op.type === 'delete-folder') return 'Deleting folder ' + op.folder;
    if (op.type === 'move-file') return 'Moving ' + op.oldPath + ' \u2192 ' + op.newPath;
    if (op.type === 'delete-file') return 'Deleting ' + op.path;
    if (op.type === 'rewrite-links') return 'Rewriting links for moved content';
    if (op.type === 'write-mkdocs-yml') return 'Writing mkdocs.yml';
    return op.path || op.src_path || (op.item && _getItemSrcPath(op.item)) ||
      (op.newPath ? op.newPath : null) || (op.item && op.item.title) || op.type;
  }

  function _executeSaveContentOp(op) {
    return _wsSetContents(op.src_path, op.content);
  }

  function _dispatchSingleOp(op) {
    if (op.type === 'wait-for-rebuild') {
      return _waitForRebuildAndReconnect();
    }
    if (op.type === 'save-content') return _executeSaveContentOp(op);
    if (op.type === 'move-up' || op.type === 'move-down') return _executeMoveWeightOp(op);
    if (op.type === 'move-left' || op.type === 'move-right' || op.type === 'move-into-section') return _executeMoveFolderOp(op);
    if (op.type === 'regenerate-index') return _executeRegenerateIndexOp(op);
    if (op.type === 'create-folder') return _executeCreateFolderOp(op);
    if (op.type === 'create-page') return _executeCreatePageOp(op);
    if (op.type === 'convert-folder-to-page') return _executeConvertFolderToPageOp(op);
    if (op.type === 'delete-page') return _executeDeletePageOp(op);
    if (op.type === 'rename-page') return _executeRenamePageOp(op);

    if (op.type === 'move-file') return _executeMoveFileOp(op);
    if (op.type === 'delete-file') return _executeDeleteFileOp(op);
    if (op.type === 'rename-folder') return _executeRenameFolderOp(op);
    if (op.type === 'delete-folder') return _executeDeleteFolderOp(op);
    if (op.type === 'rewrite-links') return _executeRewriteLinksOp(op);
    if (op.type === 'set-headless') return _executeSetHeadlessOp(op);
    if (op.type === 'set-frontmatter') return _executeSetFrontmatterOp(op);
    if (op.type === 'write-mkdocs-yml') return _wsSetContents(op.path, op.content);
    return Promise.resolve();
  }

  function _runBatchOps(contentEl, orderedOps, focusTarget, options) {
    options = options || {};
    if (!orderedOps.length) {
      _finishBatchSave(contentEl, [], focusTarget, options);
      return;
    }

    _userActionInProgress = true;
    _batchDeletedPaths = {};
    _batchRenamedPaths = {};
    if (options.precomputedRenames) {
      for (var prKey in options.precomputedRenames) {
        if (options.precomputedRenames.hasOwnProperty(prKey)) {
          _batchRenamedPaths[prKey] = options.precomputedRenames[prKey];
        }
      }
    }
    _installReloadGuard();
    if (wysiwygEditor) {
      if (wysiwygEditor.editableArea) wysiwygEditor.editableArea.contentEditable = 'false';
      if (wysiwygEditor.markdownArea) wysiwygEditor.markdownArea.readOnly = true;
    }

    var overlay = document.querySelector('.live-wysiwyg-focus-overlay') || document.body;
    var statusContainer = contentEl || overlay;
    var total = orderedOps.length;
    var completed = 0;
    var failures = [];

    _showNavStatus(statusContainer, options.title || 'Saving nav changes...', { showProgress: true, percent: 0 });

    var wsReady = _getOrCreateBulkWs();
    var indexReady = options.skipLinkIndex
      ? wsReady.then(function () { return null; })
      : wsReady.then(function () { return _fetchLinkIndex(); });

    indexReady.then(function (freshIndex) {
      _batchLinkIndex = freshIndex;
      var chain = Promise.resolve();
      for (var i = 0; i < orderedOps.length; i++) {
        (function (op, idx) {
          chain = chain.then(function () {
            var label = _getOpLabel(op);
            var pct = Math.min(99, Math.round((idx / total) * 100));
            _updateNavProgress(statusContainer, pct, 'Step ' + (idx + 1) + ' of ' + total + ': ' + label);
            return _dispatchSingleOp(op).then(function () {
              completed++;
            }).catch(function (err) {
              var path = _getOpLabel(op);
              console.error('[batch-save] op failed for ' + path, err);
              failures.push({ path: path, msg: err && err.message ? err.message : String(err) });
              if (path.endsWith && path.endsWith('.md')) _addCautionPage(path, 'Batch operation failed: ' + (err && err.message ? err.message : String(err)));
              completed++;
            });
          });
        })(orderedOps[i], i);
      }
      return chain;
    }).then(function () {
      _updateNavProgress(statusContainer, 99, 'Waiting for rebuild...');
      _closeBulkWs();
      return _waitForRebuild();
    }).then(function () {
      _finishBatchSave(statusContainer, failures, focusTarget, options);
    }).catch(function (err) {
      _finishBatchSave(statusContainer, failures, focusTarget, options);
    });
  }

  function _finishBatchSave(container, failures, focusTarget, options) {
    options = options || {};
    _batchDeletedPaths = {};
    _batchRenamedPaths = {};
    _batchLinkIndex = null;
    _userActionInProgress = false;
    if (wysiwygEditor) {
      if (wysiwygEditor.editableArea) wysiwygEditor.editableArea.contentEditable = 'true';
      if (wysiwygEditor.markdownArea) wysiwygEditor.markdownArea.readOnly = false;
    }

    if (options.onComplete) {
      _removeReloadGuard();
      var statusEl = container && container.querySelector('.live-wysiwyg-nav-status');
      if (statusEl && statusEl.parentNode) statusEl.parentNode.removeChild(statusEl);
      options.onComplete(failures);
      return;
    }

    _warningDirectMode = false;
    _setSetting('live_wysiwyg_focus_nav', '1');

    if (failures && failures.length) {
      if (_getSetting('live_wysiwyg_migration_result')) {
        _setSetting('live_wysiwyg_migration_result', 'warnings');
      }
      failures.forEach(function (f) {
        if (f.path !== '_normalize_all' && f.path && typeof f.path === 'string' && f.path.endsWith('.md')) {
          _addCautionPage(f.path, 'Batch save failed: ' + (f.msg || 'unknown error'));
        }
        _queuePostSaveMessage('error', (f.path || 'Unknown') + ': ' + (f.msg || 'unknown error'));
      });
      var detail = failures.map(function (f) { return f.path + ': ' + (f.msg || 'unknown error'); }).join('; ');
      _showNavStatus(container, 'Completed with ' + failures.length + ' error' + (failures.length !== 1 ? 's' : '') + '.', {
        showProgress: true, percent: 100,
        detail: detail,
        showCheckBtn: true,
        onCheck: function () { _navigateAfterBatchComplete(focusTarget); }
      });
    } else {
      if (options.successMessage) {
        _queuePostSaveMessage('success', options.successMessage);
      } else {
        _queuePostSaveMessage('success', 'All changes saved.');
      }
      _showNavStatus(container, 'All changes saved. Reloading...', {
        showProgress: true, percent: 100, indeterminate: true
      });
      setTimeout(function () {
        _navigateAfterBatchComplete(focusTarget);
      }, 1500);
    }
  }

  // ======================================================================
  // BATCH SYSTEM - Post-save notification queue
  // ======================================================================

  var _POST_SAVE_MSG_KEY = 'live_wysiwyg_post_save_messages';

  function _queuePostSaveMessage(type, text) {
    var messages = [];
    try { messages = JSON.parse(localStorage.getItem(_POST_SAVE_MSG_KEY)) || []; } catch (e) {}
    if (!Array.isArray(messages)) messages = [];
    messages.push({ type: type, text: text });
    try { localStorage.setItem(_POST_SAVE_MSG_KEY, JSON.stringify(messages)); } catch (e) {}
  }

  function _showPostSaveMessages() {
    var raw;
    try { raw = localStorage.getItem(_POST_SAVE_MSG_KEY); } catch (e) {}
    if (!raw) return;
    localStorage.removeItem(_POST_SAVE_MSG_KEY);
    var messages;
    try { messages = JSON.parse(raw); } catch (e) { return; }
    if (!messages || !messages.length) return;
    _displayNotifications(messages);
  }

  function _displayNotifications(messages) {
    var normal = [];
    var errors = [];
    for (var i = 0; i < messages.length; i++) {
      if (messages[i].type === 'error') errors.push(messages[i]);
      else normal.push(messages[i]);
    }
    var sorted = normal.concat(errors);
    var hasErrors = errors.length > 0;

    var existing = document.getElementById('live-wysiwyg-post-save-notifications');
    if (existing && existing.parentNode) existing.parentNode.removeChild(existing);

    var container = document.createElement('div');
    container.id = 'live-wysiwyg-post-save-notifications';
    container.style.cssText = 'position:fixed;top:12px;right:12px;z-index:100002;' +
      'max-width:420px;min-width:280px;' +
      'background:var(--md-default-bg-color,#fff);' +
      'border:1px solid var(--md-default-fg-color--lightest,#ddd);' +
      'border-radius:8px;box-shadow:0 4px 24px rgba(0,0,0,.18);' +
      'font-size:.85rem;overflow:hidden;opacity:0;transition:opacity .3s;';

    if (sorted.length > 1 || hasErrors) {
      var header = document.createElement('div');
      header.style.cssText = 'padding:10px 14px;font-weight:600;' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'color:var(--md-default-fg-color,#333);';
      header.textContent = hasErrors
        ? 'Completed with ' + errors.length + ' error' + (errors.length !== 1 ? 's' : '')
        : 'Save complete';
      container.appendChild(header);
    }

    var list = document.createElement('div');
    list.style.cssText = 'max-height:300px;overflow-y:auto;';
    for (var j = 0; j < sorted.length; j++) {
      var msg = sorted[j];
      var row = document.createElement('div');
      row.style.cssText = 'padding:8px 14px;display:flex;align-items:flex-start;gap:8px;' +
        (j < sorted.length - 1 ? 'border-bottom:1px solid var(--md-default-fg-color--lightest,#eee);' : '') +
        'color:var(--md-default-fg-color,#333);';

      var icon = document.createElement('span');
      icon.style.cssText = 'flex-shrink:0;font-size:1rem;line-height:1.3;';
      if (msg.type === 'error') {
        icon.textContent = '\u2717';
        icon.style.color = '#d9534f';
      } else if (msg.type === 'warning') {
        icon.textContent = '\u26A0';
        icon.style.color = 'var(--live-wysiwyg-caution, #f0ad4e)';
      } else if (msg.type === 'info') {
        icon.textContent = '\u2139';
        icon.style.color = 'var(--md-primary-fg-color,#4051b5)';
      } else {
        icon.textContent = '\u2713';
        icon.style.color = '#5cb85c';
      }
      row.appendChild(icon);

      var text = document.createElement('span');
      text.style.cssText = 'flex:1;line-height:1.3;word-break:break-word;';
      text.textContent = msg.text;
      row.appendChild(text);

      list.appendChild(row);
    }
    container.appendChild(list);

    var footer = document.createElement('div');
    footer.style.cssText = 'padding:8px 14px;text-align:right;' +
      'border-top:1px solid var(--md-default-fg-color--lightest,#eee);';
    var dismissBtn = document.createElement('button');
    dismissBtn.textContent = 'Dismiss';
    dismissBtn.style.cssText = 'background:var(--md-primary-fg-color,#4051b5);color:#fff;border:none;' +
      'padding:4px 16px;border-radius:4px;cursor:pointer;font-size:.82rem;';
    dismissBtn.addEventListener('click', function () {
      container.style.opacity = '0';
      setTimeout(function () {
        if (container.parentNode) container.parentNode.removeChild(container);
      }, 350);
    });
    footer.appendChild(dismissBtn);
    container.appendChild(footer);

    document.body.appendChild(container);
    requestAnimationFrame(function () { container.style.opacity = '1'; });

    if (!hasErrors) {
      setTimeout(function () {
        if (container.parentNode) {
          container.style.opacity = '0';
          setTimeout(function () {
            if (container.parentNode) container.parentNode.removeChild(container);
          }, 350);
        }
      }, 5000);
    }
  }

  function _srcPathToUrl(srcPath) {
    if (!srcPath) return '/';
    if (srcPath === 'index.md') return '/';
    if (srcPath.endsWith('/index.md')) return '/' + srcPath.slice(0, -'index.md'.length);
    if (srcPath.endsWith('.md')) return '/' + srcPath.slice(0, -3) + '/';
    return '/' + srcPath;
  }

  function _navigateAfterBatchComplete(focusTarget) {
    var ov = document.querySelector('.live-wysiwyg-nav-transition-overlay') || _showFullScreenTransition(focusTarget ? 'Navigating...' : 'Reloading...');
    _setSetting('live_wysiwyg_focus_nav', '1');
    _fadeOverlayToOpaque(ov, function () {
      if (focusTarget) {
        var targetUrl = _srcPathToUrl(focusTarget);
        if (targetUrl === window.location.pathname || targetUrl === window.location.pathname + window.location.search) {
          window.location.reload();
        } else {
          window.location.href = targetUrl;
        }
      } else {
        window.location.reload();
      }
    });
  }

  function _navigateAfterSave(focusTarget) {
    var ov = _showFullScreenTransition('Navigating...');
    _setSetting('live_wysiwyg_focus_nav', '1');
    _fadeOverlayToOpaque(ov, function () {
      var targetUrl = focusTarget ? _srcPathToUrl(focusTarget) : location.href;
      window.location.href = targetUrl;
    });
  }

  function _executeMoveWeightOp(op) {
    var itemPath = _getItemSrcPath(op.item);
    if (!op.item || !itemPath) return Promise.resolve();
    var actualPath = _resolveChainedRename(itemPath);
    if (_batchDeletedPaths[actualPath]) return Promise.resolve();
    var siblings = _findNavSiblings(op.item).filter(function (s) { return !_isRootIndex(s); });
    function w(navItem) {
      var v = _getItemWeight(navItem);
      return v != null ? v : 0;
    }
    var sorted = siblings.slice().sort(function (a, b) { return w(a) - w(b); });
    var idx = -1;
    for (var i = 0; i < sorted.length; i++) {
      if (_getItemSrcPath(sorted[i]) === itemPath) { idx = i; break; }
    }
    var isIndex = actualPath.endsWith('index.md');
    return _wsGetContents(actualPath).then(function (content) {
      var fm = _parseFrontmatter(content);
      var currentWeight = fm.fields.weight !== undefined ? fm.fields.weight : 0;
      var newWeight;
      if (op.type === 'move-up') {
        if (idx > 0) {
          var prevWeight = w(sorted[idx - 1]);
          var prevPrevWeight = idx > 1 ? w(sorted[idx - 2]) : prevWeight - 100;
          newWeight = Math.round((prevPrevWeight + prevWeight) / 2);
        } else {
          newWeight = currentWeight - 100;
        }
      } else {
        if (idx >= 0 && idx < sorted.length - 1) {
          var nextWeight = w(sorted[idx + 1]);
          var nextNextWeight = idx < sorted.length - 2 ? w(sorted[idx + 2]) : nextWeight + 100;
          newWeight = Math.round((nextWeight + nextNextWeight) / 2);
        } else {
          var lastWeight = sorted.length ? w(sorted[sorted.length - 1]) : 0;
          newWeight = lastWeight + 100;
        }
      }
      if (newWeight === currentWeight) newWeight = op.type === 'move-up' ? currentWeight - 1 : currentWeight + 1;
      var updated = _updateFrontmatter(content, { weight: newWeight }, isIndex);
      return _wsSetContents(actualPath, updated);
    });
  }

  function _collectSectionFilePaths(sectionItem) {
    var paths = [];
    if (sectionItem.src_path) {
      paths.push(sectionItem.src_path);
    }
    if (sectionItem.children) {
      for (var i = 0; i < sectionItem.children.length; i++) {
        var child = sectionItem.children[i];
        if (child.type === 'page' && child.src_path) {
          paths.push(child.src_path);
        } else if (child.type === 'section') {
          paths = paths.concat(_collectSectionFilePaths(child));
        }
      }
    }
    return paths;
  }

  function _executeMoveFolderOp(op) {
    var itemPath = _getItemSrcPath(op.item);
    if (!op.item || !itemPath) return Promise.resolve();

    if (op.item.type === 'section') {
      return _executeSectionMoveFolderOp(op);
    }

    var oldPath = _resolveChainedRename(itemPath);
    if (_batchDeletedPaths[oldPath]) {
      _addCautionPage(itemPath, 'File was already deleted when move was attempted');
      return Promise.reject(new Error('File already deleted: ' + oldPath));
    }
    var fileName = oldPath.split('/').pop();
    var targetDir = _resolveTargetDirFromOp(op);
    var newPath = targetDir ? targetDir + '/' + fileName : fileName;
    if (newPath === oldPath) return Promise.resolve();

    var oldDir = _getDir(oldPath);
    var newDir = _getDir(newPath);
    return _wsGetContents(oldPath).then(function (content) {
      var rewritten = _rewriteOutboundLinks(content, oldDir, newDir);
      return _wsDeleteFile(oldPath).then(function () {
        _batchDeletedPaths[oldPath] = true;
        return _wsNewFile(newPath, '').then(function () {
          return _wsSetContents(newPath, rewritten);
        });
      });
    }).then(function () {
      _batchRenamedPaths[itemPath] = newPath;
      _migrateCautionForRename(oldPath, newPath);
      var linkIndex = _batchLinkIndex;
      return _rewriteInboundLinks(oldPath, newPath, linkIndex).then(function () {
        _updateLinkIndexForMove(oldPath, newPath);
      });
    }).catch(function (err) {
      _addCautionPage(itemPath, 'Move failed: ' + (err && err.message ? err.message : String(err)));
      return Promise.reject(err);
    });
  }

  function _resolveTargetDirFromOp(op) {
    if (op.type === 'move-left' && op.fromSection) {
      var fromIndexPath = op.fromSection.getAttribute && op.fromSection.getAttribute('data-nav-index-path');
      if (fromIndexPath) {
        fromIndexPath = _resolveChainedRename(fromIndexPath);
        var parentOfFrom = _getDir(_getDir(fromIndexPath));
        return parentOfFrom;
      }
      var grandparentUl = op.fromSection.parentNode;
      if (grandparentUl) {
        var grandSectionLi = _getSectionLiFromUl(grandparentUl);
        if (grandSectionLi) {
          var gip = grandSectionLi.getAttribute('data-nav-index-path');
          if (gip) {
            gip = _resolveChainedRename(gip);
            return _getDir(gip);
          }
        }
      }
      return '';
    }
    if (op.targetSection && op.targetSection.querySelector) {
      var targetIndexPath = op.targetSection.getAttribute && op.targetSection.getAttribute('data-nav-index-path');
      if (targetIndexPath) {
        targetIndexPath = _resolveChainedRename(targetIndexPath);
        return _getDir(targetIndexPath);
      }
      var firstPageInSection = op.targetSection.querySelector('[data-nav-src-path]');
      if (firstPageInSection) {
        var sectionPath = _resolveChainedRename(firstPageInSection.getAttribute('data-nav-src-path'));
        return _getDir(sectionPath);
      }
    }
    return '';
  }

  function _executeSectionMoveFolderOp(op) {
    var indexPath = _getItemSrcPath(op.item);
    if (!indexPath) return Promise.resolve();
    var sectionDir = _getDir(indexPath);
    var folderName = sectionDir.split('/').pop();
    if (!folderName) return Promise.resolve();

    var targetParentDir = _resolveTargetDirFromOp(op);
    var newSectionDir = targetParentDir ? targetParentDir + '/' + folderName : folderName;
    if (newSectionDir === sectionDir) return Promise.resolve();

    var allPaths = _collectSectionFilePaths(op.item);
    if (!allPaths.length) return Promise.resolve();

    var resolvedFirst = _resolveChainedRename(allPaths[0] || indexPath);
    var actualSectionDir = _getDir(resolvedFirst);

    var oldPrefix = actualSectionDir + '/';
    var newPrefix = newSectionDir + '/';

    return _apiPost('/rename-folder', { old_path: actualSectionDir, new_path: newSectionDir })
      .then(function () {
        var globalPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
        for (var g = 0; g < globalPaths.length; g++) {
          if (globalPaths[g].indexOf(oldPrefix) === 0) {
            _batchRenamedPaths[globalPaths[g]] = newPrefix + globalPaths[g].substring(oldPrefix.length);
          }
        }
        for (var rk in _batchRenamedPaths) {
          if (Object.prototype.hasOwnProperty.call(_batchRenamedPaths, rk)) {
            var cur = _batchRenamedPaths[rk];
            if (cur.indexOf(oldPrefix) === 0) {
              _batchRenamedPaths[rk] = newPrefix + cur.substring(oldPrefix.length);
            }
          }
        }
        var idx = _batchLinkIndex;
        if (idx && typeof idx === 'object') {
          var keysToMove = [];
          for (var ik in idx) {
            if (Object.prototype.hasOwnProperty.call(idx, ik) && ik.indexOf(oldPrefix) === 0) {
              keysToMove.push(ik);
            }
          }
          for (var km = 0; km < keysToMove.length; km++) {
            var oKey = keysToMove[km];
            var nKey = newPrefix + oKey.substring(oldPrefix.length);
            idx[nKey] = idx[oKey];
            delete idx[oKey];
          }
        }
        return _waitForRebuildAndReconnect();
      }).then(function () {
        var chain = Promise.resolve();
        for (var i = 0; i < allPaths.length; i++) {
          (function (origPath) {
            chain = chain.then(function () {
              var relPart = origPath.substring(sectionDir.length);
              var oldActualPath = actualSectionDir + relPart;
              var newFilePath = newSectionDir + relPart;
              if (_batchDeletedPaths[oldActualPath]) return Promise.resolve();
              var oldDir = _getDir(oldActualPath);
              var newDir = _getDir(newFilePath);
              return _wsGetContents(newFilePath).then(function (content) {
                var rewritten = _rewriteOutboundLinks(content, oldDir, newDir);
                if (rewritten !== content) {
                  return _wsSetContents(newFilePath, rewritten);
                }
              }).then(function () {
                _batchRenamedPaths[origPath] = newFilePath;
                _migrateCautionForRename(oldActualPath, newFilePath);
                return _rewriteInboundLinks(oldActualPath, newFilePath, _batchLinkIndex).then(function () {
                  _updateLinkIndexForMove(oldActualPath, newFilePath);
                });
              });
            });
          })(allPaths[i]);
        }
        return chain;
      }).catch(function (err) {
        _addCautionPage(indexPath, 'Section move failed: ' + (err && err.message ? err.message : String(err)));
        return Promise.reject(err);
      });
  }

  function _executeRegenerateIndexOp(op) {
    if (!op.oldPath || !op.newPath || !op.indexPath || !op.indexContent) return Promise.resolve();
    var actualOldPath = _resolveChainedRename(op.oldPath);
    if (_batchDeletedPaths[actualOldPath]) {
      _addCautionPage(op.oldPath, 'File was already deleted when index regeneration was attempted');
      return Promise.reject(new Error('File already deleted: ' + actualOldPath));
    }
    return _wsGetContents(actualOldPath).then(function (content) {
      var rewritten = _rewriteLinksInContent(content, actualOldPath, op.newPath);
      return _wsDeleteFile(actualOldPath).then(function () {
        _batchDeletedPaths[actualOldPath] = true;
        return _wsNewFile(op.newPath, '').then(function () {
          return _wsSetContents(op.newPath, rewritten);
        }).then(function () {
          _batchRenamedPaths[op.oldPath] = op.newPath;
          _migrateCautionForRename(actualOldPath, op.newPath);
          var linkIndex = _batchLinkIndex;
          return _rewriteInboundLinks(actualOldPath, op.newPath, linkIndex).then(function () {
            _updateLinkIndexForMove(actualOldPath, op.newPath);
            return _wsNewFile(op.indexPath, '').then(function () {
              return _wsSetContents(op.indexPath, op.indexContent);
            });
          });
        });
      });
    });
  }

  function _executeCreateFolderOp(op) {
    if (!op.folderName) return Promise.resolve();
    if (op.skipIndex) return Promise.resolve();
    var parentDir = op.item && op.item.src_path ? _getDir(op.item.src_path) : '';
    var indexPath = (parentDir ? parentDir + '/' : '') + op.folderName + '/index.md';
    var indexContent = '---\ntitle: ' + _fmSerialize(op.folderTitle || op.folderName) +
      '\nretitled: true\nempty: true\n---\nThis section covers information about ' +
      (op.folderTitle || op.folderName) + ' and its contents.\n';
    return _wsNewFile(indexPath, op.folderTitle || op.folderName).then(function () {
      return _wsSetContents(indexPath, indexContent);
    });
  }

  function _executeCreatePageOp(op) {
    if (!op.path || !op.content) {
      return Promise.resolve();
    }
    return _wsNewFile(op.path, '').then(function () {
      delete _batchDeletedPaths[op.path];
      return _wsSetContents(op.path, op.content);
    });
  }

  function _executeConvertFolderToPageOp(op) {
    if (!op.indexPath || !op.newPath || !op.content) return Promise.resolve();
    var actualIndexPath = _resolveChainedRename(op.indexPath);
    if (_batchDeletedPaths[actualIndexPath]) {
      _addCautionPage(op.indexPath, 'File was already deleted when folder-to-page conversion was attempted');
      return Promise.reject(new Error('File already deleted: ' + actualIndexPath));
    }
    return _wsNewFile(op.newPath, '').then(function () {
      return _wsSetContents(op.newPath, op.content);
    }).then(function () {
      return _wsDeleteFile(actualIndexPath);
    }).then(function () {
      _batchDeletedPaths[actualIndexPath] = true;
      _batchRenamedPaths[op.indexPath] = op.newPath;
      var linkIndex = _batchLinkIndex;
      return _rewriteInboundLinks(actualIndexPath, op.newPath, linkIndex).then(function () {
        _updateLinkIndexForMove(actualIndexPath, op.newPath);
      });
    });
  }

  function _executeDeletePageOp(op) {
    if (!op.path) return Promise.resolve();
    return _wsDeleteFile(op.path).then(function (resp) {
      _batchDeletedPaths[op.path] = true;
      return resp;
    });
  }

  function _executeRenamePageOp(op) {
    if (!op.oldPath || !op.newPath) return Promise.resolve();
    var actualOldPath = _resolveChainedRename(op.oldPath);
    if (_batchDeletedPaths[actualOldPath]) {
      _addCautionPage(op.oldPath, 'File was already deleted when rename was attempted');
      return Promise.reject(new Error('File already deleted: ' + actualOldPath));
    }
    return _wsGetContents(actualOldPath).then(function (content) {
      var updated = content;
      if (op.newTitle) {
        updated = _updateFrontmatter(content, { title: op.newTitle }, actualOldPath.endsWith('index.md'));
      }
      var rewritten = _rewriteLinksInContent(updated, actualOldPath, op.newPath);
      var linksChanged = rewritten !== updated;
      if (!op.skipDoubleRenderCheck && linksChanged && !_doubleRenderCheck(rewritten, actualOldPath)) {
        _addCautionPage(op.oldPath, 'Rename skipped because content could not safely round-trip through the editor');
        return Promise.reject(new Error('Double render check failed for ' + actualOldPath));
      }
      return _wsDeleteFile(actualOldPath).then(function () {
        _batchDeletedPaths[actualOldPath] = true;
        return _wsNewFile(op.newPath, '').then(function () {
          return _wsSetContents(op.newPath, rewritten);
        });
      });
    }).then(function () {
      _batchRenamedPaths[op.oldPath] = op.newPath;
      _migrateCautionForRename(actualOldPath, op.newPath);
      var linkIndex = _batchLinkIndex;
      return _rewriteInboundLinks(actualOldPath, op.newPath, linkIndex).then(function () {
        _updateLinkIndexForMove(actualOldPath, op.newPath);
      });
    });
  }

  function _executeSetHeadlessOp(op) {
    if (!op.src_path) return Promise.resolve();
    var actualPath = _resolveChainedRename(op.src_path);
    if (_batchDeletedPaths[actualPath]) return Promise.resolve();
    return _wsGetContents(actualPath).then(function (content) {
      var isIndex = actualPath.endsWith('index.md');
      var updated = _updateFrontmatter(content, { headless: true }, isIndex);
      return _wsSetContents(actualPath, updated);
    });
  }

  function _executeSetFrontmatterOp(op) {
    if (!op.src_path) return Promise.resolve();
    var actualPath = _resolveChainedRename(op.src_path);
    if (_batchDeletedPaths[actualPath]) {
      return Promise.resolve();
    }
    if (op.fm) {
      if (typeof op.setContent === 'string') {
        var scParsed = _parseFrontmatter(op.setContent);
        var scBody = scParsed.hasBlock ? op.setContent.substring(scParsed.bodyStart) : op.setContent;
        var mergedFm = Object.assign({}, scParsed.hasBlock ? scParsed.fields : {}, op.fm);
        var effectiveOrig = scParsed.hasBlock ? scParsed.fields : (op.origFm || {});
        var newFm = _buildFrontmatterFromFm(mergedFm, op.isIndex, effectiveOrig);
        var finalContent = newFm + scBody;
        return _wsSetContents(actualPath, finalContent);
      }
      return _wsGetContents(actualPath).then(function (content) {
        var parsed = _parseFrontmatter(content);
        var body = parsed.hasBlock ? content.substring(parsed.bodyStart) : content;
        var newFm = _buildFrontmatterFromFm(op.fm, op.isIndex, op.origFm);
        var finalContent = newFm + body;
        return _wsSetContents(actualPath, finalContent);
      });
    }
    if (!op.updates) return Promise.resolve();
    return _wsGetContents(actualPath).then(function (content) {
      var isIndex = op.isIndex || actualPath.endsWith('index.md');
      var updated = _updateFrontmatter(content, op.updates, isIndex);
      return _wsSetContents(actualPath, updated);
    });
  }


  // ------------------------------------------------------------------
  // Folder rename / delete / link-rewrite batch executors
  // ------------------------------------------------------------------

  function _apiPost(endpoint, body) {
    if (typeof liveWysiwygLinkCheckPort === 'undefined' || !liveWysiwygLinkCheckPort) {
      return Promise.reject(new Error('Link check server not available'));
    }
    var host = window.location.hostname || '127.0.0.1';
    var maxRetries = 10;
    var retryDelay = 2000;
    var jsonBody = JSON.stringify(body);

    function attempt(retriesLeft) {
      var url = 'http://' + host + ':' + liveWysiwygLinkCheckPort + endpoint;
      return fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: jsonBody
      }).then(function (resp) {
        if (resp.status === 202) {
          if (retriesLeft > 0) {
            return new Promise(function (resolve) { setTimeout(resolve, retryDelay); })
              .then(function () { return attempt(retriesLeft - 1); });
          }
          return resp.json();
        }
        if (resp.status === 201 || resp.status === 200) {
          return resp.json();
        }
        return resp.text().then(function (t) { throw new Error('HTTP ' + resp.status + ': ' + t); });
      }).catch(function (err) {
        var msg = err && err.message ? err.message : String(err);
        var isHttpError = msg.indexOf('HTTP ') === 0;
        if (retriesLeft > 0 && !isHttpError) {
          console.warn('[apiPost] ' + endpoint + ' network error, retrying (' + retriesLeft + ' left):', msg);
          return new Promise(function (resolve) { setTimeout(resolve, retryDelay); })
            .then(function () { return _refreshLinkCheckPort(); })
            .then(function () { return attempt(retriesLeft - 1); });
        }
        throw err;
      });
    }

    return attempt(maxRetries);
  }

  function _executeMoveFileOp(op) {
    return _apiPost('/move-file', { old_path: op.oldPath, new_path: op.newPath }).then(function (result) {
      _batchRenamedPaths[op.oldPath] = op.newPath;
    });
  }

  function _executeDeleteFileOp(op) {
    if (!op.path) return Promise.resolve();
    return _apiPost('/delete-file', { path: op.path }).then(function (result) {
      _batchDeletedPaths[op.path] = true;
    });
  }

  function _executeRenameFolderOp(op) {
    if (!op.oldFolder || !op.newFolder) return Promise.resolve();
    var reqBody = { old_path: op.oldFolder, new_path: op.newFolder };
    var oldPrefix = op.oldFolder + '/';
    var newPrefix = op.newFolder + '/';
    return _apiPost('/rename-folder', reqBody).then(function (result) {
      for (var oldP in _batchRenamedPaths) {
        if (Object.prototype.hasOwnProperty.call(_batchRenamedPaths, oldP)) {
          var cur = _batchRenamedPaths[oldP];
          if (cur.indexOf(oldPrefix) === 0) {
            _batchRenamedPaths[oldP] = newPrefix + cur.substring(oldPrefix.length);
          }
        }
      }
      return _waitForRebuildAndReconnect();
    }).then(function () {
      var movedMdFiles = [];
      for (var rk in _batchRenamedPaths) {
        if (!Object.prototype.hasOwnProperty.call(_batchRenamedPaths, rk)) continue;
        var newP = _batchRenamedPaths[rk];
        if (newP.indexOf(newPrefix) === 0 && /\.md$/i.test(newP)) {
          movedMdFiles.push({ oldPath: rk, diskPath: newP });
        }
      }
      if (!movedMdFiles.length) return;
      var chain = Promise.resolve();
      movedMdFiles.forEach(function (entry) {
        chain = chain.then(function () {
          var oldDir = _getDir(entry.oldPath);
          var newDir = _getDir(entry.diskPath);
          if (oldDir === newDir) return;
          return _wsGetContents(entry.diskPath).then(function (content) {
            var rewritten = _rewriteOutboundLinks(content, oldDir, newDir);
            if (rewritten !== content) {
              return _wsSetContents(entry.diskPath, rewritten);
            }
          });
        });
      });
      return chain;
    });
  }

  function _executeDeleteFolderOp(op) {
    if (!op.folder) return Promise.resolve();
    var body = { folder: op.folder };
    if (op.exclusions && op.exclusions.length) body.exclusions = op.exclusions;
    return _apiPost('/delete-folder', body).then(function (result) {
      if (result && result.deleted_files) {
        result.deleted_files.forEach(function (f) { _batchDeletedPaths[f] = true; });
      }
      var allPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
      var prefix = op.folder + '/';
      for (var i = 0; i < allPaths.length; i++) {
        if (allPaths[i].indexOf(prefix) === 0) {
          var excl = op.exclusions || [];
          if (excl.indexOf(allPaths[i]) === -1) {
            _batchDeletedPaths[allPaths[i]] = true;
          }
        }
      }
      return _waitForRebuildAndReconnect();
    });
  }

  function _rewriteAllMovedLinksInPage(content, renameMap, pageSrcPath, newPageSrcPath) {
    var newPageDir = _getDir(newPageSrcPath || pageSrcPath);
    var oldPageDir = (newPageSrcPath && newPageSrcPath !== pageSrcPath) ? _getDir(pageSrcPath) : null;
    var patterns = [
      { re: /(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, group: 2 },
      { re: /!\[([^\]]*)\]\(([^)]+)\)/g, group: 2 },
      { re: /<img([^>]+)src=["']([^"']+)["']/g, group: 2 },
      { re: /^\[([^\]]+)\]:\s+(\S+)/gm, group: 2 }
    ];
    var replacements = [];

    for (var p = 0; p < patterns.length; p++) {
      var pat = patterns[p];
      pat.re.lastIndex = 0;
      var m;
      while ((m = pat.re.exec(content)) !== null) {
        var fullTarget = m[pat.group];
        if (!fullTarget || /^(https?:|mailto:|data:|#)/.test(fullTarget)) continue;
        var anchorIdx = fullTarget.indexOf('#');
        var queryIdx = fullTarget.indexOf('?');
        var splitIdx = -1;
        if (anchorIdx !== -1 && queryIdx !== -1) splitIdx = Math.min(anchorIdx, queryIdx);
        else if (anchorIdx !== -1) splitIdx = anchorIdx;
        else if (queryIdx !== -1) splitIdx = queryIdx;
        var pathPart = splitIdx >= 0 ? fullTarget.substring(0, splitIdx) : fullTarget;
        var suffix = splitIdx >= 0 ? fullTarget.substring(splitIdx) : '';
        if (!pathPart) continue;
        var decoded = decodeURIComponent(pathPart);
        var absTarget = _resolvePath(newPageDir, decoded);
        if (absTarget === null && oldPageDir !== null) {
          absTarget = _resolvePath(oldPageDir, decoded);
        }
        if (absTarget === null) continue;
        if (!renameMap[absTarget] && oldPageDir !== null) {
          var fallbackAbs = _resolvePath(oldPageDir, decoded);
          if (fallbackAbs !== null && renameMap[fallbackAbs]) {
            absTarget = fallbackAbs;
          }
        }
        if (!renameMap[absTarget]) continue;
        var newAbs = renameMap[absTarget];
        var newRelative = _computeRelativePath(newPageDir, newAbs);
        var needsEncode = pathPart !== decoded;
        if (needsEncode) newRelative = encodeURIComponent(newRelative).replace(/%2F/g, '/');
        var newTarget = newRelative + suffix;
        if (newTarget !== fullTarget) {
          var targetStart = m.index + m[0].lastIndexOf(fullTarget);
          replacements.push({ start: targetStart, end: targetStart + fullTarget.length, replacement: newTarget });
        }
      }
    }

    if (!replacements.length) return content;
    replacements.sort(function (a, b) { return b.start - a.start; });
    var result = content;
    for (var r = 0; r < replacements.length; r++) {
      result = result.substring(0, replacements[r].start) + replacements[r].replacement + result.substring(replacements[r].end);
    }
    return result;
  }

  function _executeRewriteLinksOp(op) {
    var renameMap = op.renameMap || {};
    var deletedPaths = op.deletedPaths || {};
    var linkIndex = _batchLinkIndex;
    if (!linkIndex || typeof linkIndex !== 'object') return Promise.resolve();
    if (!Object.keys(renameMap).length && !Object.keys(deletedPaths).length) return Promise.resolve();

    var pagesToUpdate = {};
    for (var srcPath in linkIndex) {
      if (!Object.prototype.hasOwnProperty.call(linkIndex, srcPath)) continue;
      var refs = linkIndex[srcPath];
      if (!Array.isArray(refs)) continue;
      var pageDir = _getDir(srcPath);
      for (var i = 0; i < refs.length; i++) {
        var ref = refs[i];
        var target = ref && ref.target;
        if (!target || /^(https?:|mailto:|data:|#)/.test(target)) continue;
        var hashIdx = target.indexOf('#');
        var pathPart = hashIdx >= 0 ? target.substring(0, hashIdx) : target;
        var qIdx = pathPart.indexOf('?');
        if (qIdx >= 0) pathPart = pathPart.substring(0, qIdx);
        if (!pathPart) continue;
        var absTarget = _resolvePath(pageDir, pathPart);
        if (absTarget === null) continue;
        if (renameMap[absTarget] || deletedPaths[absTarget]) {
          pagesToUpdate[srcPath] = true;
          break;
        }
      }
    }

    var pages = Object.keys(pagesToUpdate);
    if (!pages.length) return Promise.resolve();

    var chain = Promise.resolve();
    pages.forEach(function (pagePath) {
      chain = chain.then(function () {
        var actualPagePath = _resolveChainedRename(pagePath);
        if (_batchDeletedPaths[actualPagePath]) return;
        return _wsGetContents(actualPagePath).then(function (content) {
          var newPagePath = renameMap[pagePath] || pagePath;
          var updated = _rewriteAllMovedLinksInPage(content, renameMap, pagePath, newPagePath);
          if (updated !== content) {
            return _wsSetContents(actualPagePath, updated);
          }
        }).catch(function (err) {
          console.error('[rewrite-links] FAILED for', pagePath, '(actual:', _resolveChainedRename(pagePath), '):', err);
          _addCautionPage(pagePath, 'Failed to rewrite links after content migration');
        });
      });
    });
    return chain;
  }

  function _listFolderItems(folderDir, includeAll) {
    return _apiPost('/list-items', { folder: folderDir, all: !!includeAll });
  }


  function _applyNormalizeFolderToNavData(sectionItem) {
    _normalizeLevelWeights(sectionItem);
  }

  function _applyNormalizeWeightsToNavData(items) {
    _normalizeLevelWeights(null);
    function recurse(levelItems) {
      for (var i = 0; i < levelItems.length; i++) {
        var item = levelItems[i];
        if (item.type === 'section' && item.children) {
          if (!_hasVisibleMdContent(item.children)) continue;
          _normalizeLevelWeights(item);
          recurse(item.children);
        }
      }
    }
    recurse(items);
  }

  function _findParentSectionItem(pageItem) {
    if (!pageItem || !pageItem.src_path || typeof liveWysiwygNavData === 'undefined') return null;
    function search(items) {
      for (var i = 0; i < items.length; i++) {
        var it = items[i];
        if (it.type === 'section' && it.children) {
          for (var j = 0; j < it.children.length; j++) {
            if (it.children[j].type === 'page' && it.children[j].src_path === pageItem.src_path) return it;
          }
          var deep = search(it.children);
          if (deep) return deep;
        }
      }
      return null;
    }
    return search(liveWysiwygNavData);
  }


  // ======================================================================
  // NAV MENU - Navigation between pages
  // ======================================================================
  function _navigateToPage(url, title, srcPath) {
    if (srcPath && srcPath === _getCurrentSrcPath()) return;
    if (wysiwygEditor && wysiwygEditor._isDocDirty && wysiwygEditor._isDocDirty()) {
      _showNavDialog(
        'The page appears to have changed. Would you like to save or discard changes before navigating away?',
        [
          { text: 'Cancel', value: 'cancel' },
          { text: 'Discard and leave', value: 'discard', className: 'live-wysiwyg-nav-dialog-danger' },
          { text: 'Save and leave', value: 'save', className: 'live-wysiwyg-nav-dialog-primary' }
        ]
      ).then(function (result) {
        if (result === 'save') {
          _doFocusSave().then(function () {
            _doNavigate(url, title, srcPath);
          });
        } else if (result === 'discard') {
          if (wysiwygEditor && wysiwygEditor._resetPristineContent) {
            wysiwygEditor._resetPristineContent(wysiwygEditor.markdownArea ? wysiwygEditor.markdownArea.value : '');
          }
          _doNavigate(url, title, srcPath);
        }
      });
      return;
    }
    _doNavigate(url, title, srcPath);
  }

  function _doNavigate(url, title, srcPath) {
    if (isFocusModeActive && srcPath && wysiwygEditor) {
      _doAjaxNavigate(url, title, srcPath);
      return;
    }
    var navOv = _showFullScreenTransition('Navigating to ' + (title || 'page') + '...');
    _setSetting('live_wysiwyg_focus_nav', '1');
    if (title) _setSetting('live_wysiwyg_focus_nav_target', title);
    _fadeOverlayToOpaque(navOv, function () {
      window.location.href = url;
    });
  }

  function _doAjaxNavigate(url, title, srcPath) {
    var transitionOverlay = _showFullScreenTransition('Loading ' + (title || 'page') + '...');
    _wsGetContents(srcPath).then(function (markdown) {
      _ajaxCurrentSrcPath = srcPath;
      if (wysiwygEditor._loadContent) {
        wysiwygEditor._loadContent(markdown);
      }
      if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
        populateRawHtmlBlocks(wysiwygEditor.editableArea);
        enhanceCodeBlocks(wysiwygEditor.editableArea);
        enhanceChecklists(wysiwygEditor.editableArea);
        enhanceAdmonitions(wysiwygEditor.editableArea);
        enhanceImages(wysiwygEditor.editableArea);
      }
      history.pushState({ srcPath: srcPath }, title || '', url);
      document.title = (title ? title + ' - ' : '') +
        (document.title.indexOf(' - ') !== -1 ? document.title.split(' - ').pop() : document.title);

      _refreshNavActiveState(srcPath);
      _refreshFocusToc();
      _refreshFocusTitle(title);
      _checkDeadLinksForCurrentPage();
      _fadeOutOverlay(transitionOverlay);
    }).catch(function (err) {
      console.error('live-wysiwyg: AJAX navigate failed', err);
      _setSetting('live_wysiwyg_focus_nav', '1');
      if (title) _setSetting('live_wysiwyg_focus_nav_target', title);
      _fadeOverlayToOpaque(transitionOverlay, function () {
        window.location.href = url;
      });
    });
  }

  function _showFullScreenTransition(text) {
    var existing = document.querySelector('.live-wysiwyg-nav-transition-overlay');
    if (existing) existing.parentNode.removeChild(existing);
    var overlay = document.createElement('div');
    overlay.className = 'live-wysiwyg-nav-transition-overlay';
    var spinner = document.createElement('div');
    spinner.className = 'live-wysiwyg-nav-transition-spinner';
    overlay.appendChild(spinner);
    var label = document.createElement('div');
    label.className = 'live-wysiwyg-nav-transition-text';
    label.textContent = text || '';
    overlay.appendChild(label);
    document.body.appendChild(overlay);
    return overlay;
  }

  function _fadeOverlayToOpaque(overlay, callback) {
    if (!overlay || !overlay.parentNode) { if (callback) callback(); return; }
    overlay.style.background = 'rgba(0,0,0,1)';
    setTimeout(function () { if (callback) callback(); }, 350);
  }

  function _fadeOutOverlay(overlay) {
    if (!overlay || !overlay.parentNode) return;
    overlay.style.transition = 'opacity .6s ease-out';
    overlay.style.opacity = '0';
    setTimeout(function () {
      if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
    }, 650);
  }

  function _refreshNavActiveState(srcPath) {
    if (!_focusOverlay) return;
    var sidebar = _focusOverlay.querySelector('.live-wysiwyg-focus-sidebar-left');
    if (!sidebar) return;
    var links = sidebar.querySelectorAll('.md-nav__link');
    for (var i = 0; i < links.length; i++) {
      var a = links[i];
      var li = a.closest('.md-nav__item');
      if (a.getAttribute('data-src-path') === srcPath) {
        a.classList.add('md-nav__link--active');
        if (li) li.classList.add('md-nav__item--active');
      } else {
        a.classList.remove('md-nav__link--active');
        if (li) {
          if (li.classList.contains('md-nav__item--nested')) {
            var childNav = li.querySelector(':scope > .md-nav');
            var isExpanded = childNav && childNav.getAttribute('aria-expanded') === 'true';
            if (!isExpanded) li.classList.remove('md-nav__item--active');
          } else {
            li.classList.remove('md-nav__item--active');
          }
        }
      }
    }
    _syncAllSectionActiveState();

    var prevCurrent = sidebar.querySelectorAll('.live-wysiwyg-nav-hidden-page--current');
    for (var p = 0; p < prevCurrent.length; p++) {
      prevCurrent[p].classList.remove('live-wysiwyg-nav-hidden-page--current');
      var showCb = sidebar.querySelector('.live-wysiwyg-nav-hidden-cb');
      if (!showCb || !showCb.checked) prevCurrent[p].style.display = 'none';
    }
    var hiddenLi = sidebar.querySelector('.live-wysiwyg-nav-hidden-page[data-nav-src-path="' + srcPath + '"]');
    if (hiddenLi) {
      hiddenLi.classList.add('live-wysiwyg-nav-hidden-page--current');
      hiddenLi.style.display = '';
      var parentSection = hiddenLi.closest('.md-nav__item--nested');
      while (parentSection) {
        parentSection.classList.add('md-nav__item--active');
        var parentNav = parentSection.querySelector(':scope > .md-nav');
        if (parentNav) parentNav.setAttribute('aria-expanded', 'true');
        parentSection = parentSection.parentElement ? parentSection.parentElement.closest('.md-nav__item--nested') : null;
      }
    }
  }

  function _syncAllSectionActiveState() {
    if (!_navSidebarEl) return;
    var sections = _navSidebarEl.querySelectorAll('.md-nav__item--nested');
    for (var i = 0; i < sections.length; i++) {
      var sLi = sections[i];
      var childNav = sLi.querySelector(':scope > .md-nav');
      if (!childNav) continue;
      var expanded = childNav.getAttribute('aria-expanded') === 'true';
      if (expanded) {
        sLi.classList.add('md-nav__item--active');
      } else {
        sLi.classList.remove('md-nav__item--active');
      }
    }
  }

  function _refreshFocusToc() {
    if (!_focusOverlay || !wysiwygEditor || !wysiwygEditor.editableArea) return;
    var tocList = _focusOverlay.querySelector('.md-nav--secondary .md-nav__list');
    if (tocList) {
      buildFocusToc(wysiwygEditor.editableArea, tocList);
    }
  }

  function _refreshFocusTitle(pageTitle) {
    if (!_focusOverlay) return;
    var topic2 = _focusOverlay.querySelector('.live-wysiwyg-focus-header-topic:last-child .md-ellipsis');
    if (topic2) topic2.textContent = pageTitle || '';
  }

  function _doFocusSave() {
    var path = _getCurrentSrcPath();
    if (!path) return Promise.resolve();

    var content = '';
    if (wysiwygEditor) {
      if (wysiwygEditor._finalizeUpdate) {
        if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
          wysiwygEditor._finalizeUpdate(wysiwygEditor.editableArea.innerHTML);
        } else if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
          wysiwygEditor._finalizeUpdate(wysiwygEditor.markdownArea.value);
        }
      }
      var ta = document.querySelector('.live-edit-source');
      content = ta ? ta.value : '';
    }

    var pageTitle = document.title ? document.title.split(' - ')[0].trim() : path;
    var ops = [{ type: 'save-content', src_path: path, content: content, title: pageTitle }];
    var container = document.querySelector('.live-wysiwyg-focus-content')
      || document.querySelector('.live-wysiwyg-focus-overlay')
      || document.body;

    return new Promise(function (resolve, reject) {
      _runBatchOps(container, ops, null, {
        title: 'Saving \'' + pageTitle + '\'...',
        skipLinkIndex: true,
        onComplete: function (failures) {
          if (wysiwygEditor && wysiwygEditor._resetPristineContent) {
            wysiwygEditor._resetPristineContent(content);
          }
          _syncBuildEpoch();
          if (failures && failures.length) {
            reject(new Error(failures[0].msg || 'Save failed'));
          } else {
            resolve();
          }
        }
      });
    });
  }

  function _doFocusModeSave() {
    if (_navEditMode) { _confirmNavSave(); return; }
    _doFocusSave().then(function () {
      if (_getSetting('live_wysiwyg_focus_remain') === '1') {
        var currentSrc = _getCurrentSrcPath();
        if (currentSrc) {
          var transitionOv = _showFullScreenTransition('Reloading...');
          _wsGetContents(currentSrc).then(function (md) {
            if (wysiwygEditor && wysiwygEditor._loadContent) {
              wysiwygEditor._loadContent(md);
            }
            _refreshFocusToc();
            _fadeOutOverlay(transitionOv);
            if (_focusOverlay && _focusOverlay._updateSaveDiscard) _focusOverlay._updateSaveDiscard();
          }).catch(function () {
            _fadeOutOverlay(transitionOv);
          });
        }
      }
    });
  }

  // ======================================================================
  // NAV MENU - Focus target management
  // ======================================================================
  function _resolveNavPathThroughQueue(path) {
    if (!path) return path;
    var resolved = path;
    for (var i = 0; i < _navBatchQueue.length; i++) {
      var op = _navBatchQueue[i];
      if (op.type === 'rename-page' && op.oldPath === resolved) resolved = op.newPath;
      if ((op.type === 'move-left' || op.type === 'move-right' || op.type === 'move-into-section') && op.item && _getItemSrcPath(op.item) === resolved) {
        var targetDir = '';
        if (op.targetSection && op.targetSection.querySelector) {
          var firstPage = op.targetSection.querySelector('[data-nav-src-path]');
          if (firstPage) targetDir = _getDir(firstPage.getAttribute('data-nav-src-path'));
        }
        var fileName = resolved.split('/').pop();
        resolved = targetDir ? targetDir + '/' + fileName : fileName;
      }
    }
    return resolved;
  }

  function _setNavFocusTarget(srcPath) {
    var resolved = _resolveNavPathThroughQueue(srcPath);
    _navFocusTarget = resolved != null ? resolved : srcPath;
    if (!_navSidebarEl) return;
    _navSidebarEl.querySelectorAll('.live-wysiwyg-nav-item--focus-target').forEach(function (el) {
      el.classList.remove('live-wysiwyg-nav-item--focus-target');
    });
    var li = _navSidebarEl.querySelector('[data-nav-src-path="' + srcPath + '"]') ||
      (resolved !== srcPath ? _navSidebarEl.querySelector('[data-nav-src-path="' + resolved + '"]') : null);
    if (li) li.classList.add('live-wysiwyg-nav-item--focus-target');
  }

  // ======================================================================
  // NAV MENU - Settings gear popup
  // ======================================================================
  function _isSectionEmpty(item) {
    if (!item || item.type !== 'section') return false;
    var children = item.children || [];
    var hasAssets = children.some(function (c) { return c.type === 'asset'; });
    if (hasAssets) return false;
    var hasSubsections = children.some(function (c) { return c.type === 'section'; });
    if (hasSubsections) return false;
    var pages = children.filter(function (c) { return c.type === 'page'; });
    if (pages.length === 0) return true;
    if (pages.length === 1 && pages[0].isIndex && pages[0].retitled && pages[0].empty) return true;
    return false;
  }

  function _getSectionFolderDir(section) {
    if (!section || !section.children || !section.children.length) return '';
    if (section.src_path) return _getDir(section.src_path);
    for (var i = 0; i < section.children.length; i++) {
      var c = section.children[i];
      if (c.type === 'page' && c.src_path) return _getDir(c.src_path);
    }
    for (var j = 0; j < section.children.length; j++) {
      var c = section.children[j];
      if (c.type === 'asset' && c.src_path) {
        return _getDir(c.src_path);
      }
    }
    for (var j = 0; j < section.children.length; j++) {
      var s = section.children[j];
      if (s.type === 'section') {
        var subDir = _getSectionFolderDir(s);
        if (subDir) return _getDir(subDir);
      }
    }
    return '';
  }

  // ------------------------------------------------------------------
  // Folder rename / delete initiation (from settings gear)
  // ------------------------------------------------------------------

  function _initiateFolderRename(item, oldFolder, newFolder) {
    _enterNavEditModeAsync().then(function (ready) {
      if (!ready) return;

      _navBatchQueue.push({ type: 'rename-folder', oldFolder: oldFolder, newFolder: newFolder });

      var oldPrefix = oldFolder + '/';
      var newPrefix = newFolder + '/';
      _walkNavData(function (navItem) {
        var sp = _getItemSrcPath(navItem);
        if (sp && sp.indexOf(oldPrefix) === 0) {
          var newSp = newPrefix + sp.substring(oldPrefix.length);
          navItem.src_path = newSp;
          if (navItem.index_meta && navItem.index_meta.src_path) {
            navItem.index_meta.src_path = newPrefix + navItem.index_meta.src_path.substring(oldPrefix.length);
          }
        }
      });

      var sectionHasIdx = (item.index_meta != null) ||
        (item.children && item.children.some(function (c) { return c.type === 'page' && c.isIndex; }));
      if (!sectionHasIdx) {
        item.title = newFolder.split('/').pop();
      }

      item._renamed = true;
      _markChildrenRenamed(item);

      _collectRecursiveNormalizeOpsForSection(item);

      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-rename-badge',
        text: 'Rename "' + oldFolder.split('/').pop() + '" \u2192 "' + newFolder.split('/').pop() + '" + normalize'
      });
      _commitNavSnapshot();
    });
  }

  function _markChildrenRenamed(sectionItem) {
    if (!sectionItem || !sectionItem.children) return;
    for (var i = 0; i < sectionItem.children.length; i++) {
      var child = sectionItem.children[i];
      child._renamed = true;
      if (child.type === 'section' && child.children) {
        _markChildrenRenamed(child);
      }
    }
  }

  function _walkNavData(fn) {
    var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        fn(items[i]);
        if (items[i].children) walk(items[i].children);
      }
    })(navItems);
  }

  function _collectRecursiveNormalizeOpsForSection(sectionItem) {
    if (!sectionItem || !sectionItem.children) return;
    _normalizeChildWeightsInMemory(sectionItem.children);
    for (var i = 0; i < sectionItem.children.length; i++) {
      if (sectionItem.children[i].type === 'section') {
        _collectRecursiveNormalizeOpsForSection(sectionItem.children[i]);
      }
    }
  }

  function _normalizeChildWeightsInMemory(children) {
    if (!children || !children.length) return;
    var orderedItems = [];
    for (var i = 0; i < children.length; i++) {
      var child = children[i];
      if (child.type === 'page') {
        if (child.isIndex || child.headless) continue;
        orderedItems.push(child);
      } else if (child.type === 'section') {
        orderedItems.push(child);
      }
    }
    for (var j = 0; j < orderedItems.length; j++) {
      var w = (j + 1) * 100;
      var item = orderedItems[j];
      if (item.type === 'page') {
        if (item.isIndex && w < 0) w = 0;
        item.weight = w;
      } else if (item.type === 'section' && item.index_meta) {
        if (w < 0) w = 0;
        item.index_meta.weight = w;
      }
    }
  }

  function _scanDeleteImpact(deletedDirs) {
    var fileLayout = _buildFileLayoutFromNav(deletedDirs);
    var filterTargets = {};
    var navData = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    (function collectDeleted(items) {
      for (var i = 0; i < items.length; i++) {
        var it = items[i];
        if (it._deleted && it.src_path) filterTargets[it.src_path] = true;
        if (it.children) collectDeleted(it.children);
      }
    })(navData);
    if (deletedDirs) {
      for (var d = 0; d < deletedDirs.length; d++) {
        filterTargets[deletedDirs[d]] = true;
        var prefix = deletedDirs[d] + '/';
        var allPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
        for (var p = 0; p < allPaths.length; p++) {
          if (allPaths[p].indexOf(prefix) === 0) filterTargets[allPaths[p]] = true;
        }
      }
    }
    if (!Object.keys(filterTargets).length) {
      _commitNavSnapshot();
      return;
    }
    _scanDeadLinks('internal', {
      fileLayout: fileLayout,
      filterTargets: filterTargets,
      quiet: true,
      onComplete: function (deadByPage) {
        if (!Object.keys(deadByPage).length) {
          _commitNavSnapshot();
        }
      }
    });
  }

  function _initiateFolderDelete(item, folderDir) {
    _enterNavEditModeAsync().then(function (ready) {
      if (!ready) return;

      _navBatchQueue.push({ type: 'delete-folder', folder: folderDir });
      _removeSectionFromNav(item);

      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-delete-badge',
        text: 'Delete "' + folderDir.split('/').pop() + '"',
        style: 'background:#d9534f'
      });
      _scanDeleteImpact([folderDir]);
    });
  }

  function _removeSectionFromNav(item) {
    var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    (function remove(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i] === item) { items.splice(i, 1); return true; }
        if (items[i].children && remove(items[i].children)) return true;
      }
      return false;
    })(navItems);
  }

  function _buildSettingsContent(dropdown, item, itemType, nwConfig) {
    var _renameRef = {};

    function addTextRow(label, key, val) {
      var row = document.createElement('div');
      row.className = 'live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline';
      var span = document.createElement('span');
      span.textContent = label;
      span.style.flexShrink = '0';
      row.appendChild(span);
      var input = document.createElement('input');
      input.type = 'text';
      input.value = val !== null && val !== undefined ? val : '';
      input.setAttribute('data-fm-key', key);
      row.appendChild(input);
      dropdown.appendChild(row);
      return input;
    }

    function addCheckboxGroup(items) {
      var row = document.createElement('div');
      row.className = 'live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-checkbox-group';
      for (var i = 0; i < items.length; i++) {
        var lbl = document.createElement('label');
        var cb = document.createElement('input');
        cb.type = 'checkbox';
        cb.checked = !!items[i].val;
        cb.setAttribute('data-fm-key', items[i].key);
        lbl.appendChild(cb);
        lbl.appendChild(document.createTextNode(' ' + items[i].label));
        row.appendChild(lbl);
      }
      dropdown.appendChild(row);
    }

    function addDivider() {
      var hr = document.createElement('hr');
      hr.className = 'live-wysiwyg-nav-settings-divider';
      dropdown.appendChild(hr);
    }

    function addButtonRow(buttons) {
      var row = document.createElement('div');
      row.className = 'live-wysiwyg-nav-settings-btn-row';
      for (var i = 0; i < buttons.length; i++) {
        var btn = document.createElement('button');
        btn.className = 'live-wysiwyg-nav-settings-normalize-btn';
        btn.textContent = buttons[i].text;
        if (buttons[i].style) btn.style.cssText += buttons[i].style;
        if (buttons[i].shrink) {
          btn.style.setProperty('flex', '0 0 auto', 'important');
          btn.style.setProperty('width', 'auto', 'important');
          btn.style.setProperty('padding-left', '18px');
          btn.style.setProperty('padding-right', '18px');
        }
        if (buttons[i].disabled) btn.disabled = true;
        if (buttons[i].ref) buttons[i].ref.btn = btn;
        if (buttons[i].syncRef) buttons[i].syncRef.btn = btn;
        btn.addEventListener('click', buttons[i].onClick);
        row.appendChild(btn);
      }
      dropdown.appendChild(row);
    }

    // --- Determine whether this section has an index page ---
    var sectionHasIndex = itemType === 'section' && (
      (item.src_path != null && item.src_path !== '') ||
      (item.index_meta != null) ||
      (item.children && item.children.some(function (c) { return c.type === 'page' && c.isIndex; }))
    );
    var noIndexSection = itemType === 'section' && !sectionHasIndex;

    var effectiveMeta = (itemType === 'section' && item.index_meta) ? item.index_meta : item;
    var effectiveIsIndex = itemType === 'section' || (item.isIndex === true);
    var hasFrontmatter = itemType !== 'asset' && !noIndexSection;
    var isRootIndexItem = _isRootIndex(item) ||
      (itemType === 'section' && sectionHasIndex && item.src_path === 'index.md');

    // ======================================================
    // Content area (above final divider)
    // ======================================================

    // --- Title row (pages and sections with index) ---
    if (hasFrontmatter) {
      addTextRow('Title', 'title', item.title || '');
    }

    // --- Folder name row (sections) ---
    var folderDir, folderBaseName, renameFolderInput, doFolderRename, folderRenameRef;
    if (itemType === 'section' && (nwConfig.enabled || noIndexSection) && !isRootIndexItem) {
      folderDir = _getSectionFolderDir(item);
      if (folderDir) {
        folderBaseName = folderDir.indexOf('/') >= 0 ? folderDir.substring(folderDir.lastIndexOf('/') + 1) : folderDir;
        var folderRow = document.createElement('div');
        folderRow.className = 'live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline';
        var folderLabel = document.createElement('span');
        folderLabel.textContent = 'Folder name';
        folderLabel.style.flexShrink = '0';
        folderRow.appendChild(folderLabel);
        renameFolderInput = document.createElement('input');
        renameFolderInput.type = 'text';
        renameFolderInput.value = folderBaseName;
        renameFolderInput.setAttribute('data-folder-rename', 'true');
        folderRow.appendChild(renameFolderInput);
        dropdown.appendChild(folderRow);

        folderRenameRef = {};
        doFolderRename = function () {
          var newName = renameFolderInput.value.trim().toLowerCase().replace(/[^a-z0-9\-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
          if (!newName || newName === folderBaseName) return;
          var parentDir = folderDir.indexOf('/') >= 0 ? folderDir.substring(0, folderDir.lastIndexOf('/')) : '';
          var newFolder = parentDir ? parentDir + '/' + newName : newName;
          dropdown.parentNode.removeChild(dropdown);
          _initiateFolderRename(item, folderDir, newFolder);
        };
        renameFolderInput.addEventListener('input', function () {
          var normalized = renameFolderInput.value.trim().toLowerCase().replace(/[^a-z0-9\-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
          folderRenameRef.btn.disabled = !normalized || normalized === folderBaseName;
        });

        // Store folder rename info on dropdown for Apply to use implicitly (sections with index)
        if (sectionHasIndex) {
          dropdown._folderRenameInput = renameFolderInput;
          dropdown._folderOriginalName = folderBaseName;
          dropdown._folderDir = folderDir;
        }
      }
    }

    // --- File name row (pages and assets) ---
    var srcPath, fileDisplayName, fileRenameInput, doFileRename, fileRenameRef, isAsset;
    if ((nwConfig.enabled && itemType === 'page' && !_isRootIndex(item)) || itemType === 'asset') {
      srcPath = _getItemSrcPath(item) || '';
      if (srcPath) {
        isAsset = itemType === 'asset';
        var fileName = srcPath.indexOf('/') >= 0 ? srcPath.substring(srcPath.lastIndexOf('/') + 1) : srcPath;
        fileDisplayName = isAsset ? fileName : fileName.replace(/\.md$/, '');
        var fileRow = document.createElement('div');
        fileRow.className = 'live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline';
        var fileLabel = document.createElement('span');
        fileLabel.textContent = 'File name';
        fileLabel.style.flexShrink = '0';
        fileRow.appendChild(fileLabel);
        fileRenameInput = document.createElement('input');
        fileRenameInput.type = 'text';
        fileRenameInput.value = fileDisplayName;
        fileRow.appendChild(fileRenameInput);
        dropdown.appendChild(fileRow);

        fileRenameRef = {};
        doFileRename = function () {
          var dir = srcPath.indexOf('/') >= 0 ? srcPath.substring(0, srcPath.lastIndexOf('/')) : '';
          var newName, newPath, badgeText, badgeAttrs;
          if (isAsset) {
            newName = fileRenameInput.value.trim();
            if (!newName || newName === fileDisplayName) return;
            newPath = dir ? dir + '/' + newName : newName;
            badgeText = 'Rename "' + fileDisplayName + '" \u2192 "' + newName + '"';
            badgeAttrs = { 'data-rename-asset': '1' };
          } else {
            var newBase = fileRenameInput.value.trim().toLowerCase().replace(/[^a-z0-9\-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
            if (!newBase || newBase === fileDisplayName) return;
            newPath = dir ? dir + '/' + newBase + '.md' : newBase + '.md';
            newName = newBase;
            badgeText = 'Rename "' + fileDisplayName + '" \u2192 "' + newBase + '"';
            badgeAttrs = { 'data-rename-page': '1' };
          }
          dropdown.parentNode.removeChild(dropdown);
          _enterNavEditModeAsync().then(function (ready) {
            if (!ready) return;
            if (!isAsset) {
              _navBatchQueue.push({ type: 'rename-page', oldPath: srcPath, newPath: newPath, item: item });
            }
            item.src_path = newPath;
            item._renamed = true;
            if (isAsset) {
              item.title = newName;
              var dotIdx = newName.lastIndexOf('.');
              item.extension = dotIdx > 0 ? newName.substring(dotIdx) : '';
            }
            _addNavBadge({
              className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-rename-badge',
              text: badgeText,
              attrs: badgeAttrs
            });
            _commitNavSnapshot();
          });
        };
        fileRenameInput.addEventListener('input', function () {
          var val = fileRenameInput.value.trim();
          if (isAsset) {
            fileRenameRef.btn.disabled = !val || val === fileDisplayName;
          } else {
            var normalized = val.toLowerCase().replace(/[^a-z0-9\-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
            fileRenameRef.btn.disabled = !normalized || normalized === fileDisplayName;
          }
        });

        // Store file rename info on dropdown for Apply to use implicitly (pages only)
        if (!isAsset) {
          dropdown._fileRenameInput = fileRenameInput;
          dropdown._fileOriginalName = fileDisplayName;
          dropdown._fileSrcPath = srcPath;
        }
      }
    }

    // --- First divider (separates name fields from settings) ---
    if (hasFrontmatter && !isRootIndexItem) {
      addDivider();
    }

    // --- Weight + Headless row (pages and sections with index) ---
    var weightRow, weightInput, headlessCb;
    if (hasFrontmatter && !isRootIndexItem) {
      var defaultWeight = effectiveIsIndex
        ? (nwConfig.frontmatter_defaults && nwConfig.frontmatter_defaults.index_weight !== undefined
          ? nwConfig.frontmatter_defaults.index_weight : -10)
        : (nwConfig.frontmatter_defaults && nwConfig.frontmatter_defaults.weight !== undefined
          ? nwConfig.frontmatter_defaults.weight : 0);
      var wasOriginallyHeadless = !!(effectiveMeta.headless);
      var isPage = itemType === 'page';

      weightRow = document.createElement('div');
      weightRow.className = 'live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline';
      var weightSpan = document.createElement('span');
      weightSpan.textContent = 'Weight';
      weightRow.appendChild(weightSpan);
      weightInput = document.createElement('input');
      weightInput.type = 'number';
      weightInput.value = (effectiveMeta.weight !== undefined && effectiveMeta.weight !== null) ? effectiveMeta.weight : defaultWeight;
      weightInput.setAttribute('data-fm-key', 'weight');
      weightInput.style.width = '80px';
      weightRow.appendChild(weightInput);
      if (_isRootIndex(item)) {
        weightInput.disabled = true;
        weightInput.title = 'Root index page does not use a weight';
      }

      if (nwConfig.enabled) {
        headlessCb = document.createElement('input');
        headlessCb.type = 'checkbox';
        headlessCb.checked = !!wasOriginallyHeadless;
        headlessCb.setAttribute('data-fm-key', 'headless');
        var headlessLbl = document.createElement('label');
        headlessLbl.appendChild(headlessCb);
        headlessLbl.appendChild(document.createTextNode(' Headless'));

        if (isPage && wasOriginallyHeadless) {
          weightRow.style.display = 'none';
        }

        if (isPage) {
          headlessCb.addEventListener('change', function () {
            if (headlessCb.checked) {
              weightRow.style.display = 'none';
            } else {
              weightRow.style.display = '';
              if (wasOriginallyHeadless) {
                weightInput.value = _computeUnhideWeight(item);
              }
            }
          });
        }

        // Headless on the same row as Weight for sections; separate row for pages when headless hides weight
        if (isPage) {
          dropdown.appendChild(weightRow);
          var headlessRow = document.createElement('div');
          headlessRow.className = 'live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline';
          headlessRow.appendChild(headlessLbl);
          dropdown.appendChild(headlessRow);
        } else {
          weightRow.appendChild(headlessLbl);
          dropdown.appendChild(weightRow);
        }
      } else {
        dropdown.appendChild(weightRow);
      }

      if (nwConfig.enabled && effectiveIsIndex) {
        addCheckboxGroup([
          { label: 'Retitled', key: 'retitled', val: effectiveMeta.retitled || false },
          { label: 'Empty', key: 'empty', val: effectiveMeta.empty || false }
        ]);
      }
    }

    // ======================================================
    // Final divider (separates content from action buttons)
    // ======================================================
    addDivider();

    // ======================================================
    // Action buttons area (below final divider)
    // ======================================================

    if (noIndexSection) {
      // --- Indexless section: Create folder index, Delete + Rename Folder ---
      var createIndexBtn = document.createElement('button');
      createIndexBtn.className = 'live-wysiwyg-nav-settings-normalize-btn';
      createIndexBtn.textContent = 'Create folder index';
      createIndexBtn.addEventListener('click', function () {
        dropdown.parentNode.removeChild(dropdown);
        var fd = folderDir || _getSectionFolderDir(item);
        if (!fd) return;
        var indexPath = fd + '/index.md';
        var indexWeight = (nwConfig.frontmatter_defaults && nwConfig.frontmatter_defaults.index_weight !== undefined)
          ? nwConfig.frontmatter_defaults.index_weight
          : (nwConfig.index_weight !== undefined ? nwConfig.index_weight : -10);
        var indexContent = '---\ntitle: ' + _fmSerialize(item.title || 'Untitled') +
          '\nretitled: true\nempty: true\nweight: ' + indexWeight + '\n---\nThis section covers information about ' +
          (item.title || 'Untitled') + ' and its contents.\n';
        _enterNavEditModeAsync().then(function (ready) {
          if (!ready) return;
          _navBatchQueue.push({ type: 'create-page', path: indexPath, content: indexContent });
          item.src_path = indexPath;
          item.index_meta = {
            weight: indexWeight,
            headless: false,
            retitled: true,
            empty: true
          };
          _addNavBadge({
            className: 'live-wysiwyg-nav-normalize-badge',
            text: 'Create index for "' + (item.title || fd) + '"'
          });
          _commitNavSnapshot();
        });
      });
      dropdown.appendChild(createIndexBtn);

      if (folderRenameRef) {
        addButtonRow([
          { text: 'Delete', style: 'background:#d9534f', shrink: true, onClick: function () {
            dropdown.parentNode.removeChild(dropdown);
            _initiateFolderDelete(item, folderDir);
          }},
          { text: 'Rename Folder', disabled: true, ref: folderRenameRef, syncRef: _renameRef, onClick: doFolderRename }
        ]);
      }
      return;
    }

    if (itemType === 'asset') {
      // --- Asset: Delete + Rename File ---
      if (fileRenameRef) {
        addButtonRow([
          { text: 'Delete', style: 'background:#d9534f', shrink: true, onClick: function () {
            dropdown.parentNode.removeChild(dropdown);
            _enterNavEditModeAsync().then(function (ready) {
              if (!ready) return;
              item._deleted = true;
              _addNavBadge({
                className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-delete-badge',
                text: 'Delete "' + fileDisplayName + '"',
                style: 'background:#d9534f'
              });
              _scanDeleteImpact();
            });
          }},
          { text: 'Rename File', disabled: true, ref: fileRenameRef, syncRef: _renameRef, onClick: doFileRename }
        ]);
      }
      return;
    }

    // --- Section with index / Page: Normalize Weights, Delete + Apply ---
    if (nwConfig.enabled && !isRootIndexItem) {
      var normalizeTarget = itemType === 'section' ? item : _findParentSectionItem(item);
      if (normalizeTarget) {
        addButtonRow([{ text: 'Normalize Weights', onClick: function () {
          dropdown.parentNode.removeChild(dropdown);
          _enterNavEditModeAsync().then(function (ready) {
            if (!ready) return;
            _applyNormalizeFolderToNavData(normalizeTarget);
            _adjustDefaultPageWeightSilent();
            _addNavBadge({
              className: 'live-wysiwyg-nav-normalize-badge',
              text: 'Normalize folder weights'
            });
            _commitNavSnapshot();
          });
        }}]);
      }
    }

    var deleteFn;
    var deleteLabel;
    if (itemType === 'section' && folderDir && !isRootIndexItem) {
      deleteLabel = 'Delete';
      deleteFn = function () {
        dropdown.parentNode.removeChild(dropdown);
        _initiateFolderDelete(item, folderDir);
      };
    } else if (itemType === 'page' && !_isRootIndex(item)) {
      var delDisplayName = fileDisplayName || (item.title || 'page');
      deleteLabel = 'Delete';
      deleteFn = function () {
        dropdown.parentNode.removeChild(dropdown);
        _enterNavEditModeAsync().then(function (ready) {
          if (!ready) return;
          item._deleted = true;
          _addNavBadge({
            className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-delete-badge',
            text: 'Delete "' + delDisplayName + '"',
            style: 'background:#d9534f'
          });
          _scanDeleteImpact();
        });
      };
    }

    var actionBtns = [];
    if (deleteFn) {
      actionBtns.push({ text: deleteLabel, style: 'background:#d9534f', shrink: true, onClick: deleteFn });
    }
    actionBtns.push({ text: 'Apply', style: 'background:var(--md-primary-fg-color,#4051b5)', onClick: function () {
      _applySettingsGearChanges(dropdown, item, itemType);
      dropdown.parentNode.removeChild(dropdown);
    }});
    addButtonRow(actionBtns);
  }

  function _repositionDropdown(dropdown) {
    if (!dropdown._gearBtn || !dropdown.parentNode) return;
    var rect = dropdown._gearBtn.getBoundingClientRect();
    var ddRect = dropdown.getBoundingClientRect();
    var vpW = window.innerWidth;
    var vpH = window.innerHeight;

    if (!dropdown._topLocked) {
      var top = rect.bottom + 4;
      if (top + ddRect.height > vpH - 8) {
        top = Math.max(4, rect.top - ddRect.height - 4);
      }
      dropdown.style.top = top + 'px';
      dropdown._topLocked = true;
    }

    var left = Math.max(4, rect.left - 100);
    if (left + ddRect.width > vpW - 8) {
      left = Math.max(4, vpW - ddRect.width - 8);
    }
    dropdown.style.left = left + 'px';
  }

  function _showSettingsGear(item, itemType, gearBtn) {
    var existing = document.querySelector('.live-wysiwyg-nav-settings-dropdown');
    if (existing) { existing.parentNode.removeChild(existing); return; }

    var dropdown = document.createElement('div');
    dropdown.className = 'live-wysiwyg-nav-settings-dropdown';
    var nwConfig = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : { enabled: false };

    _buildSettingsContent(dropdown, item, itemType, nwConfig);

    dropdown._gearBtn = gearBtn;

    var hasApplyBtn = Array.prototype.some.call(
      dropdown.querySelectorAll('.live-wysiwyg-nav-settings-normalize-btn'),
      function (b) { return b.textContent === 'Apply'; }
    );
    var renameBtn = null;
    var renameBtnClick = null;
    Array.prototype.forEach.call(
      dropdown.querySelectorAll('.live-wysiwyg-nav-settings-normalize-btn'),
      function (b) {
        if (b.textContent === 'Rename Folder' || b.textContent === 'Rename File') {
          renameBtn = b;
          renameBtnClick = function () { b.click(); };
        }
      }
    );

    function _dismissGearDropdown() {
      if (dropdown.parentNode) dropdown.parentNode.removeChild(dropdown);
      document.removeEventListener('click', closeHandler, true);
    }

    var firstInput = dropdown.querySelector('input[type="text"], input[type="number"], select');

    if (hasApplyBtn) {
      _attachDialogKeyboard(dropdown, {
        category: 'form',
        trackDirty: true,
        onConfirm: function () {
          _applySettingsGearChanges(dropdown, item, itemType);
          _dismissGearDropdown();
        },
        onDismiss: function () { _dismissGearDropdown(); },
        autoFocus: firstInput ? function () { firstInput.focus(); firstInput.select(); } : null
      });
    } else if (renameBtn) {
      _attachDialogKeyboard(dropdown, {
        category: 'form',
        trackDirty: true,
        isDirty: function () { return !renameBtn.disabled; },
        onConfirm: function () {
          if (!renameBtn.disabled) renameBtnClick();
        },
        onDismiss: function () { _dismissGearDropdown(); },
        autoFocus: firstInput ? function () { firstInput.focus(); firstInput.select(); } : null
      });
    } else {
      _attachDialogKeyboard(dropdown, {
        category: 'settings',
        onDismiss: function () { _dismissGearDropdown(); },
        autoFocus: firstInput ? function () { firstInput.focus(); firstInput.select(); } : null
      });
    }

    dropdown.style.position = 'fixed';
    dropdown.style.visibility = 'hidden';
    document.body.appendChild(dropdown);
    _repositionDropdown(dropdown);
    dropdown.style.visibility = '';
    _attachContainerExpandBehavior(dropdown, {
      onResize: function () { _repositionDropdown(dropdown); }
    });

    var closeHandler = function (e) {
      if (!dropdown.contains(e.target) && e.target !== gearBtn) {
        _dismissGearDropdown();
      }
    };
    setTimeout(function () { document.addEventListener('click', closeHandler, true); }, 0);
  }

  function _computeUnhideWeight(item) {
    var srcPath = _getItemSrcPath(item) || '';
    var dir = _getDir(srcPath);
    var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    var siblingArr = navItems;
    function findSection(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i].type === 'section') {
          var fd = _getSectionFolderDir(items[i]);
          if (fd === dir) { siblingArr = items[i].children || items; return true; }
          if (items[i].children && findSection(items[i].children)) return true;
        }
      }
      return false;
    }
    if (dir) findSection(navItems);
    var maxW = 0;
    for (var i = 0; i < siblingArr.length; i++) {
      var w = _getItemWeight(siblingArr[i]);
      if (w != null && w > maxW) maxW = w;
    }
    return maxW + 100;
  }

  function _applySettingsGearChanges(dropdown, item, itemType) {
    var updates = {};
    dropdown.querySelectorAll('[data-fm-key]').forEach(function (input) {
      if (input.disabled) return;
      var key = input.getAttribute('data-fm-key');
      var val;
      if (input.type === 'checkbox') val = input.checked;
      else if (input.type === 'number') val = input.value !== '' ? parseFloat(input.value) : null;
      else val = input.value || null;
      updates[key] = val;
    });

    var wasHeadless = item.headless || (item.index_meta && item.index_meta.headless);
    var isBeingUnhidden = wasHeadless && updates.headless === false;
    if (isBeingUnhidden) {
      updates.weight = _computeUnhideWeight(item);
    }

    // Check for implicit file rename (pages only — stored by _buildSettingsContent)
    var fileRenameNeeded = false;
    var fileNewPath, fileNewBase, fileBadgeText, fileBadgeAttrs;
    if (dropdown._fileRenameInput && dropdown._fileOriginalName && dropdown._fileSrcPath) {
      var newBase = dropdown._fileRenameInput.value.trim().toLowerCase().replace(/[^a-z0-9\-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
      if (newBase && newBase !== dropdown._fileOriginalName) {
        fileRenameNeeded = true;
        var dir = dropdown._fileSrcPath.indexOf('/') >= 0 ? dropdown._fileSrcPath.substring(0, dropdown._fileSrcPath.lastIndexOf('/')) : '';
        fileNewPath = dir ? dir + '/' + newBase + '.md' : newBase + '.md';
        fileNewBase = newBase;
        fileBadgeText = 'Rename "' + dropdown._fileOriginalName + '" \u2192 "' + newBase + '"';
        fileBadgeAttrs = { 'data-rename-page': '1' };
      }
    }

    // Check for implicit folder rename (sections with index — stored by _buildSettingsContent)
    var folderRenameNeeded = false;
    var folderNewFolder, folderOldFolder, folderBadgeNewName;
    if (dropdown._folderRenameInput && dropdown._folderOriginalName && dropdown._folderDir) {
      var newFolderName = dropdown._folderRenameInput.value.trim().toLowerCase().replace(/[^a-z0-9\-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
      if (newFolderName && newFolderName !== dropdown._folderOriginalName) {
        folderRenameNeeded = true;
        folderOldFolder = dropdown._folderDir;
        var parentDir = folderOldFolder.indexOf('/') >= 0 ? folderOldFolder.substring(0, folderOldFolder.lastIndexOf('/')) : '';
        folderNewFolder = parentDir ? parentDir + '/' + newFolderName : newFolderName;
        folderBadgeNewName = newFolderName;
      }
    }

    var effectivePath = _getItemSrcPath(item);
    var effectiveIsIndex = itemType === 'section' || (item.isIndex === true);

    if (effectivePath === _getCurrentSrcPath() && !fileRenameNeeded && !folderRenameNeeded) {
      if (wysiwygEditor) {
        var md = wysiwygEditor.getValue ? wysiwygEditor.getValue() : '';
        var updated = _updateFrontmatter(md, updates, effectiveIsIndex);
        var parsed = parseFrontmatter(updated);
        wysiwygEditor._liveWysiwygFrontmatter = parsed.frontmatter;
        if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
          wysiwygEditor.markdownArea.value = updated;
        }
        if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate();
      }
      if (updates.title) {
        item.title = updates.title;
        _refreshFocusTitle(updates.title);
      }
      if (updates.weight != null && itemType === 'section' && item.index_meta) {
        item.index_meta.weight = updates.weight;
      } else if (updates.weight != null) {
        item.weight = updates.weight;
      }
      if (updates.headless != null) {
        if (itemType === 'section' && item.index_meta) {
          item.index_meta.headless = updates.headless;
        } else {
          item.headless = updates.headless;
        }
      }
      _commitNavSnapshot();
    } else {
      _enterNavEditModeAsync().then(function (ready) {
        if (!ready) return;
        _navBatchQueue.push({ type: 'set-frontmatter', src_path: effectivePath, updates: updates, isIndex: effectiveIsIndex });
        if (updates.title) item.title = updates.title;
        if (updates.weight != null && itemType === 'section' && item.index_meta) {
          item.index_meta.weight = updates.weight;
        } else if (updates.weight != null && item.type === 'page') {
          item.weight = updates.weight;
        }

        if (isBeingUnhidden && effectivePath) {
          _promoteHiddenToNav(item, updates);
        }

        if (fileRenameNeeded) {
          _navBatchQueue.push({ type: 'rename-page', oldPath: dropdown._fileSrcPath, newPath: fileNewPath, item: item });
          item.src_path = fileNewPath;
          item._renamed = true;
          _addNavBadge({
            className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-rename-badge',
            text: fileBadgeText,
            attrs: fileBadgeAttrs
          });
        }

        if (folderRenameNeeded) {
          _initiateFolderRename(item, folderOldFolder, folderNewFolder);
          return;
        }

        _commitNavSnapshot();
      });
      return;
    }

    if (isBeingUnhidden && effectivePath) {
      _promoteHiddenToNav(item, updates);
    }
  }

  function _promoteHiddenToNav(item, updates) {
    var srcPath = _getItemSrcPath(item);
    if (!srcPath) return;

    item.headless = false;
    if (updates.weight != null) item.weight = updates.weight;
    if (updates.title) item.title = updates.title;

    var dir = _getDir(srcPath);
    var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    var targetArr = navItems;
    function findSection(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i].type === 'section') {
          var fd = _getSectionFolderDir(items[i]);
          if (fd === dir) { targetArr = items[i].children || items; return true; }
          if (items[i].children && findSection(items[i].children)) return true;
        }
      }
      return false;
    }
    if (dir) findSection(navItems);

    var alreadyInNav = targetArr.some(function (c) { return _getItemSrcPath(c) === srcPath; });
    if (!alreadyInNav) {
      targetArr.push(item);
      targetArr.sort(function (a, b) {
        var wa = _getItemWeight(a); var wb = _getItemWeight(b);
        if (wa == null) wa = 99999;
        if (wb == null) wb = 99999;
        return wa - wb;
      });
    }

  }



  function _showEmptyFolderPopup(anchorEl, sectionItem, folderDir) {
    _showNavPopup(anchorEl,
      'This folder is empty (or only has a placeholder index). Choose an action:',
      [
        {
          text: 'Delete Folder',
          action: function () {
            _enterNavEditModeAsync().then(function (ready) {
              if (!ready) return;
              var section = _findSectionByDir(liveWysiwygNavData, folderDir);
              if (section) {
                _markSubtreeDeleted(section);
              }
              _addNavBadge({
                className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-delete-badge',
                text: 'Delete "' + folderDir.split('/').pop() + '"',
                style: 'background:#d9534f'
              });
              _scanDeleteImpact();
            });
          }
        },
        {
          text: 'New Child Page',
          action: function () {
            _showNewPageDialog(folderDir);
          }
        },
        {
          text: 'Convert Folder to Page',
          action: function () {
            _convertFolderToPage(sectionItem);
          }
        }
      ]
    );
  }

  function _convertFolderToPage(sectionItem) {
    var indexPath = sectionItem.src_path || (sectionItem.children && sectionItem.children[0] && sectionItem.children[0].src_path);
    if (!indexPath || !indexPath.endsWith('index.md')) return;
    var folderDir = _getDir(indexPath);
    var folderName = folderDir.split('/').pop() || folderDir;
    var newPath = _getDir(folderDir) ? _getDir(folderDir) + '/' + folderName + '.md' : folderName + '.md';

    _enterNavEditModeAsync().then(function (ready) {
    if (!ready) return;

    _wsGetContents(indexPath).then(function (content) {
      var fm = _parseFrontmatter(content);
      var toStrip = {};
      if (fm.fields.retitled) toStrip.retitled = null;
      if (fm.fields.empty) toStrip.empty = null;
      var updated = _updateFrontmatter(content, toStrip, true);
      var zones = _findExclusionZones(updated);
      var patterns = [
        { re: /(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, group: 2 },
        { re: /!\[([^\]]*)\]\(([^)]+)\)/g, group: 2 },
        { re: /<img([^>]+)src=["']([^"']+)["']/g, group: 2 },
        { re: /^\[([^\]]+)\]:\s+(\S+)/gm, group: 2 }
      ];
      var replacements = [];
      for (var p = 0; p < patterns.length; p++) {
        var pat = patterns[p];
        pat.re.lastIndex = 0;
        var m;
        while ((m = pat.re.exec(updated)) !== null) {
          if (_isInExclusionZone(m.index, zones)) continue;
          var target = m[pat.group];
          if (!target || /^(?:https?:\/\/|\/|#|mailto:|data:)/.test(target)) continue;
          var decoded = decodeURIComponent(target);
          if (decoded.indexOf('/') !== -1) continue;
          var newTarget = folderName + '/' + decoded;
          var start = m.index + m[0].indexOf(target);
          replacements.push({ start: start, end: start + target.length, replacement: newTarget });
        }
      }
      if (replacements.length) {
        replacements.sort(function (a, b) { return b.start - a.start; });
        for (var i = 0; i < replacements.length; i++) {
          var r = replacements[i];
          updated = updated.substring(0, r.start) + r.replacement + updated.substring(r.end);
        }
      }
      _navBatchQueue.push({
        type: 'convert-folder-to-page',
        indexPath: indexPath,
        newPath: newPath,
        content: updated
      });
      _navFocusTarget = newPath;
      _commitNavSnapshot();
    });
    });
  }

  // ======================================================================
  // NAV MENU - Snapshot-driven top warnings
  // ======================================================================
  var _navTopWarningActions = {
    'start-migration': function () { _startMigrationFlow(); },
    'apply-default-weight': function (warn) { _applyDefaultPageWeight(warn._suggestedWeight); }
  };

  function _seedNavTopWarnings() {
    _navTopWarnings = [];
    var cfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
    if (cfg && !cfg.installed) {
      _navTopWarnings.push({
        id: 'nav-weight-not-installed',
        text: 'pip install mkdocs-nav-weight; managing the nav requires this plugin.',
        icon: 'caution',
        title: 'mkdocs-nav-weight not installed'
      });
    } else if ((cfg && !cfg.enabled) || _ymlHasNavKey(_virtualMkdocsYml)) {
      var migText = !cfg.enabled
        ? 'The mkdocs-nav-weight plugin is not configured. Migrate to enable frontmatter-based nav weight management.'
        : 'The nav key in mkdocs.yml can cause ordering conflicts. Migrate fully to mkdocs-nav-weight.';
      _navTopWarnings.push({
        id: 'nav-coexistence',
        text: migText,
        icon: 'warning',
        title: 'Migrate to mkdocs-nav-weight',
        actionId: 'start-migration',
        actionText: 'Migrate to mkdocs-nav-weight'
      });
    }
    if (_navTopWarnings.length) _ensureNavUncollapsed();
  }

  function _removeNavTopWarning(id) {
    for (var i = _navTopWarnings.length - 1; i >= 0; i--) {
      if (_navTopWarnings[i].id === id) _navTopWarnings.splice(i, 1);
    }
  }

  function _hasNavTopWarning(id) {
    for (var i = 0; i < _navTopWarnings.length; i++) {
      if (_navTopWarnings[i].id === id) return true;
    }
    return false;
  }

  // ======================================================================
  // NAV MENU - Warning / tip popups
  // ======================================================================

  function _showUnweightedPopup(anchorEl) {
    _showNavPopup(anchorEl,
      'This page does not define a nav weight. It will appear at the end of explicitly weighted pages. ' +
      'Visit this page to adjust its weight, or use "Normalize Nav Weights" in the settings gear.',
      []
    );
  }

  function _showNavPopup(anchorEl, message, buttons) {
    var existing = document.querySelector('.live-wysiwyg-nav-popup');
    if (existing) existing.parentNode.removeChild(existing);

    var popup = document.createElement('div');
    popup.className = 'live-wysiwyg-nav-popup';

    var msgEl = document.createElement('div');
    msgEl.textContent = message;
    popup.appendChild(msgEl);

    if (buttons.length) {
      var btnRow = document.createElement('div');
      btnRow.style.marginTop = '8px';
      buttons.forEach(function (btn) {
        var b = document.createElement('button');
        b.textContent = btn.text;
        if (btn.primary) b.className = 'live-wysiwyg-nav-popup-primary';
        b.addEventListener('click', function () {
          popup.parentNode.removeChild(popup);
          if (btn.action) btn.action();
        });
        btnRow.appendChild(b);
      });
      popup.appendChild(btnRow);
    }

    var rect = anchorEl.getBoundingClientRect();
    popup.style.position = 'fixed';
    popup.style.left = Math.max(4, rect.left - 50) + 'px';
    popup.style.visibility = 'hidden';
    document.body.appendChild(popup);
    var popupH = popup.offsetHeight;
    var spaceBelow = window.innerHeight - rect.bottom - 8;
    if (spaceBelow < popupH && rect.top > popupH + 8) {
      popup.style.top = (rect.top - popupH - 4) + 'px';
    } else {
      popup.style.top = (rect.bottom + 4) + 'px';
    }
    popup.style.visibility = '';

    function _dismissPopup() {
      if (popup.parentNode) popup.parentNode.removeChild(popup);
      document.removeEventListener('click', closeHandler, true);
    }
    var firstActionBtn = popup.querySelector('button');
    _attachDialogKeyboard(popup, {
      category: 'informational',
      onDismiss: function () { _dismissPopup(); },
      onConfirm: firstActionBtn ? function () { _dismissPopup(); firstActionBtn.click(); } : null,
      autoFocus: firstActionBtn
    });

    var closeHandler = function (e) {
      if (!popup.contains(e.target) && e.target !== anchorEl) {
        _dismissPopup();
      }
    };
    setTimeout(function () { document.addEventListener('click', closeHandler, true); }, 0);
  }

  function _parseYamlNavKey(yaml) {
    if (!yaml || typeof yaml !== 'string') return null;
    var lines = yaml.split('\n');
    var navStart = -1;
    var navIndent = 0;
    for (var i = 0; i < lines.length; i++) {
      var m = lines[i].match(/^(\s*)nav\s*:\s*$/);
      if (m) {
        navStart = i;
        navIndent = m[1].length;
        break;
      }
    }
    if (navStart === -1) return null;

    function parseList(fromIdx, minIndent) {
      var items = [];
      var i = fromIdx;
      while (i < lines.length) {
        var line = lines[i];
        var trimmed = line.trimLeft();
        if (trimmed === '' || trimmed.startsWith('#')) { i++; continue; }
        var indent = line.length - trimmed.length;
        if (indent <= navIndent && i > navStart) break;
        if (indent < minIndent) break;

        var listMatch = trimmed.match(/^-\s+(.*)$/);
        if (!listMatch) { i++; continue; }
        var content = listMatch[1].trim();
        var colonIdx = content.indexOf(':');
        if (colonIdx === -1) {
          items.push({ type: 'page', title: content.replace(/\.md$/, ''), path: content });
          i++;
          continue;
        }
        var key = content.substring(0, colonIdx).trim();
        var val = content.substring(colonIdx + 1).trim();
        if (val !== '') {
          items.push({ type: 'page', title: key, path: val });
          i++;
          continue;
        }
        var childIndent = indent + 2;
        i++;
        var children = parseList(i, childIndent);
        items.push({ type: 'section', title: key, children: children.items });
        i = children.nextIdx;
      }
      return { items: items, nextIdx: i };
    }

    var result = parseList(navStart + 1, navIndent + 2);
    return result.items;
  }

  // ------------------------------------------------------------------
  // NAV MIGRATION - Helpers
  // ------------------------------------------------------------------

  function _migrationCheckDuplicates(navStructure) {
    var seen = {};
    var dupes = [];
    function walk(items) {
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.type === 'page' && item.path) {
          if (seen[item.path]) { if (dupes.indexOf(item.path) === -1) dupes.push(item.path); }
          else { seen[item.path] = true; }
        } else if (item.type === 'section' && item.children) {
          walk(item.children);
        }
      }
    }
    walk(navStructure);
    return dupes;
  }

  function _migrationSectionSlug(title) {
    return title.toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '') || 'section';
  }

  function _migrationComputeTargetTree(navStructure) {
    var pages = [];
    var indexes = [];
    var inNavPaths = {};
    var claimedIndexPaths = {};

    function findSectionIndex(children) {
      for (var j = 0; j < children.length; j++) {
        if (children[j].type === 'page' && children[j].path &&
            children[j].path.endsWith('index.md')) {
          return children[j];
        }
      }
      return null;
    }

    function walk(items, targetDir) {
      var childIdx = 0;
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.type === 'page' && item.path && item.path.endsWith('.md')) {
          if (item.path === 'index.md' && targetDir === '') {
            inNavPaths[item.path] = true;
            pages.push({
              oldPath: item.path,
              targetPath: item.path,
              title: item.title || null,
              weight: null
            });
            continue;
          }
          if (claimedIndexPaths[item.path]) {
            childIdx++;
            claimedIndexPaths[item.path].weight = childIdx * 100;
            inNavPaths[item.path] = true;
            continue;
          }
          childIdx++;
          var filename = item.path.split('/').pop();
          if (filename === 'index.md') {
            var slug = item.title ? _migrationSectionSlug(item.title) : _getDir(item.path).split('/').pop();
            filename = (slug || 'page') + '.md';
          }
          var targetPath = targetDir ? targetDir + '/' + filename : filename;
          inNavPaths[item.path] = true;
          pages.push({
            oldPath: item.path,
            targetPath: targetPath,
            title: item.title || null,
            weight: childIdx * 100
          });
        } else if (item.type === 'section' && item.children) {
          childIdx++;
          var secSlug = _migrationSectionSlug(item.title);
          var secDir = targetDir ? targetDir + '/' + secSlug : secSlug;
          var existingIndex = findSectionIndex(item.children);
          if (existingIndex) {
            claimedIndexPaths[existingIndex.path] = {
              secDir: secDir,
              navTitle: existingIndex.title || null
            };
            inNavPaths[existingIndex.path] = true;
          }
          indexes.push({
            dir: secDir,
            sectionTitle: item.title,
            existingIndexPath: existingIndex ? existingIndex.path : null,
            weight: childIdx * 100
          });
          walk(item.children, secDir);
        }
      }
    }

    walk(navStructure, '');
    return { pages: pages, indexes: indexes, inNavPaths: inNavPaths, claimedIndexPaths: claimedIndexPaths };
  }

  function _precomputeHiddenConsolidation(hiddenItems, navTree, folderRenameMap) {
    if (!hiddenItems.length) return;

    var linkIdx = typeof liveWysiwygLinkIndex !== 'undefined' ? liveWysiwygLinkIndex : {};

    var oldToNew = {};
    for (var ok in folderRenameMap) {
      if (folderRenameMap.hasOwnProperty(ok)) {
        oldToNew[ok] = folderRenameMap[ok];
      }
    }

    function mapDirOldToNew(dir) {
      if (!dir) return dir;
      if (oldToNew[dir] != null) return oldToNew[dir];
      for (var prefix in oldToNew) {
        if (oldToNew.hasOwnProperty(prefix) && dir.indexOf(prefix + '/') === 0) {
          return oldToNew[prefix] + dir.substring(prefix.length);
        }
      }
      return dir;
    }

    var refsByHidden = {};
    for (var srcPath in linkIdx) {
      if (!linkIdx.hasOwnProperty(srcPath)) continue;
      var links = linkIdx[srcPath];
      var srcDir = _getDir(srcPath);
      for (var li = 0; li < links.length; li++) {
        var target = links[li].target;
        if (!target || /^(https?:|mailto:|data:|#)/.test(target)) continue;
        var hashIdx = target.indexOf('#');
        var pathPart = hashIdx >= 0 ? target.substring(0, hashIdx) : target;
        var qIdx = pathPart.indexOf('?');
        if (qIdx >= 0) pathPart = pathPart.substring(0, qIdx);
        if (!pathPart) continue;
        var resolved = _resolvePath(srcDir, pathPart);
        if (resolved === null) continue;
        if (!refsByHidden[resolved]) refsByHidden[resolved] = [];
        refsByHidden[resolved].push({ from: srcPath, fromDir: srcDir });
      }
    }

    for (var hi = 0; hi < hiddenItems.length; hi++) {
      var item = hiddenItems[hi];
      var origPath = item.src_path;
      var filename = origPath.split('/').pop();
      var origDir = _getDir(origPath);
      var postRenameDir = mapDirOldToNew(origDir);
      var postRenamePath = postRenameDir ? postRenameDir + '/' + filename : filename;

      if (postRenamePath !== origPath) {
        item.src_path = postRenamePath;
        item._renamed = true;
        item._originalPath = origPath;
      }

      var refs = refsByHidden[origPath];
      if (refs && refs.length) {
        var targetDir = null;
        var unanimous = true;
        for (var r = 0; r < refs.length; r++) {
          var refDir = mapDirOldToNew(refs[r].fromDir);
          if (targetDir === null) {
            targetDir = refDir;
          } else if (targetDir !== refDir) {
            unanimous = false;
            break;
          }
        }

        if (unanimous && targetDir !== null && targetDir !== postRenameDir) {
          var newPath = targetDir ? targetDir + '/' + filename : filename;
          item.src_path = newPath;
          item._renamed = true;
          item._originalPath = origPath;
          postRenameDir = targetDir;
        }
      }

      var placed = false;
      if (postRenameDir) {
        var section = _findSectionByDir(navTree, postRenameDir);
        if (section && section.children) {
          section.children.push(item);
          placed = true;
        }
      }
      if (!placed) {
        navTree.push(item);
      }
    }
  }

  function _scanClaimedIndexContent(claimedIndexPaths) {
    var existingByPath = {};
    (function collect(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i].src_path) existingByPath[items[i].src_path] = items[i];
        if (items[i].children) collect(items[i].children);
      }
    })(liveWysiwygNavData);
    var paths = Object.keys(claimedIndexPaths);
    var promises = [];
    for (var ci = 0; ci < paths.length; ci++) {
      var item = existingByPath[paths[ci]];
      if (item && !item._indexContent) {
        (function (it) {
          promises.push(
            _wsGetContents(it.src_path).then(function (content) {
              if (content) it._indexContent = content;
            }).catch(function () {})
          );
        })(item);
      }
    }
    return promises.length ? Promise.all(promises) : Promise.resolve();
  }

  function _applyMigrationToNavData(navStructure, allMdSrcPaths, suggestedDefaultWeight) {
    var tree = _migrationComputeTargetTree(navStructure);
    var fmMap = typeof liveWysiwygFrontmatterMap !== 'undefined' ? liveWysiwygFrontmatterMap : {};

    var existingByPath = {};
    (function collect(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i].src_path) existingByPath[items[i].src_path] = items[i];
        if (items[i].children) collect(items[i].children);
      }
    })(liveWysiwygNavData);

    var existingSectionsByDir = {};
    (function collectSections(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i].type === 'section') {
          var fd = _getSectionFolderDir(items[i]);
          if (fd) existingSectionsByDir[fd] = items[i];
          if (items[i].children) collectSections(items[i].children);
        }
      }
    })(liveWysiwygNavData);

    var dirMapping = {};
    for (var dp = 0; dp < tree.pages.length; dp++) {
      var dpg = tree.pages[dp];
      var od = _getDir(dpg.oldPath), nd = _getDir(dpg.targetPath);
      if (od && nd) {
        if (!dirMapping[od]) dirMapping[od] = {};
        dirMapping[od][nd] = (dirMapping[od][nd] || 0) + 1;
      }
    }
    var folderRenameMap = {};
    for (var fod in dirMapping) {
      if (!dirMapping.hasOwnProperty(fod)) continue;
      var fTargets = Object.keys(dirMapping[fod]);
      if (fTargets.length === 1 && fod !== fTargets[0]) {
        folderRenameMap[fod] = fTargets[0];
      }
    }

    _navBatchQueue = [];
    var splitContentPages = [];

    for (var idx = 0; idx < tree.indexes.length; idx++) {
      var sec = tree.indexes[idx];
      var idxPath = sec.dir + '/index.md';
      if (sec.existingIndexPath) {
        var claimed = tree.claimedIndexPaths[sec.existingIndexPath];
        var contentTitle = (claimed && claimed.navTitle) || sec.sectionTitle;
        var contentFilename = _generateFilename(contentTitle);
        var contentPath = sec.dir + '/' + contentFilename;
        splitContentPages.push({
          oldPath: sec.existingIndexPath,
          targetPath: contentPath,
          title: contentTitle,
          weight: (claimed && claimed.weight) || 100
        });
      }
    }

    function buildTree(navItems, targetDir) {
      var result = [];
      var childIdx = 0;
      for (var i = 0; i < navItems.length; i++) {
        var navItem = navItems[i];
        if (navItem.type === 'page' && navItem.path && navItem.path.endsWith('.md')) {
          if (navItem.path === 'index.md' && targetDir === '') {
            var rootExisting = existingByPath['index.md'];
            if (rootExisting) {
              if (navItem.title) {
                rootExisting.title = navItem.title;
                if (rootExisting._fm) rootExisting._fm.title = navItem.title;
              }
              result.push(rootExisting);
            }
            continue;
          }
          if (tree.claimedIndexPaths[navItem.path]) {
            var claimedInfo = tree.claimedIndexPaths[navItem.path];
            if (claimedInfo.weight) {
              var splitPage = null;
              for (var sp = 0; sp < splitContentPages.length; sp++) {
                if (splitContentPages[sp].oldPath === navItem.path) {
                  splitPage = splitContentPages[sp]; break;
                }
              }
              if (splitPage) {
                var splitExisting = existingByPath[navItem.path];
                if (splitExisting && splitExisting._indexContent) {
                  var splitFmSource = (splitExisting && splitExisting._fm)
                    ? Object.assign({}, splitExisting._fm)
                    : (fmMap[navItem.path] ? Object.assign({}, fmMap[navItem.path]) : {});
                  splitFmSource.title = splitPage.title;
                  splitFmSource.weight = splitPage.weight;
                  delete splitFmSource.headless;
                  delete splitFmSource.retitled;
                  delete splitFmSource.empty;
                  var splitIsSection = splitExisting.type === 'section';
                  var splitItem = {
                    type: 'page',
                    src_path: splitPage.targetPath,
                    title: splitPage.title,
                    weight: splitPage.weight,
                    _fm: splitFmSource,
                    setContent: splitExisting._indexContent
                  };
                  if (splitIsSection) {
                    splitItem._new = true;
                    splitItem._uid = _generateUid();
                  } else {
                    splitItem._uid = splitExisting._uid;
                    splitItem._renamed = true;
                    splitItem._originalPath = navItem.path;
                  }
                  result.push(splitItem);
                }
              }
            }
            continue;
          }
          childIdx++;
          var pageEntry = null;
          for (var pe = 0; pe < tree.pages.length; pe++) {
            if (tree.pages[pe].oldPath === navItem.path) {
              pageEntry = tree.pages[pe]; break;
            }
          }
          if (pageEntry) {
            var existing = existingByPath[navItem.path];
            var pageFmSource = (existing && existing._fm)
              ? Object.assign({}, existing._fm)
              : (fmMap[navItem.path] ? Object.assign({}, fmMap[navItem.path]) : {});
            pageFmSource.title = pageEntry.title || (existing ? existing.title : '');
            pageFmSource.weight = pageEntry.weight;
            delete pageFmSource.headless;
            delete pageFmSource.retitled;
            delete pageFmSource.empty;
            var pageItem = {
              type: 'page',
              src_path: pageEntry.targetPath,
              title: pageFmSource.title,
              weight: pageEntry.weight,
              _fm: pageFmSource,
              _uid: existing ? existing._uid : _generateUid()
            };
            if (pageEntry.oldPath !== pageEntry.targetPath) {
              pageItem._renamed = true;
              pageItem._originalPath = pageEntry.oldPath;
            }
            result.push(pageItem);
          }
        } else if (navItem.type === 'section' && navItem.children) {
          childIdx++;
          var secSlug = _migrationSectionSlug(navItem.title);
          var secDir = targetDir ? targetDir + '/' + secSlug : secSlug;

          var indexInfo = null;
          for (var ii = 0; ii < tree.indexes.length; ii++) {
            if (tree.indexes[ii].dir === secDir) { indexInfo = tree.indexes[ii]; break; }
          }

          var indexPath = secDir + '/index.md';
          var indexWeight = indexInfo ? indexInfo.weight : childIdx * 100;
          var existingIndex = indexInfo && indexInfo.existingIndexPath
            ? existingByPath[indexInfo.existingIndexPath] : null;
          var indexItem;

          if (existingIndex && existingIndex._indexContent) {
            var thinFm = { title: navItem.title, empty: true, retitled: true, weight: indexWeight };
            var thinContent = '---\ntitle: ' + _fmSerialize(navItem.title) +
              '\nempty: true\nretitled: true\nweight: ' + indexWeight + '\n---\n';
            indexItem = {
              type: 'page', src_path: indexPath, title: navItem.title,
              isIndex: true, weight: indexWeight,
              retitled: true, empty: true,
              _fm: thinFm, _new: true, _uid: _generateUid()
            };
            _navBatchQueue.push({
              type: 'create-page', path: indexPath,
              content: thinContent, item: indexItem
            });
          } else if (existingIndex) {
            indexItem = {
              type: 'page', src_path: indexPath, title: navItem.title,
              isIndex: true, weight: indexWeight,
              retitled: true, empty: true,
              _fm: { title: navItem.title, empty: true, retitled: true, weight: indexWeight },
              _uid: existingIndex._uid
            };
            if (existingIndex.src_path !== indexPath) {
              indexItem._renamed = true;
              indexItem._originalPath = existingIndex.src_path;
            }
          } else {
            var newIdxFm = { title: navItem.title, empty: true, retitled: true, weight: indexWeight };
            var newIdxContent = '---\ntitle: ' + _fmSerialize(navItem.title) +
              '\nempty: true\nretitled: true\nweight: ' + indexWeight + '\n---\n';
            indexItem = {
              type: 'page', src_path: indexPath, title: navItem.title,
              isIndex: true, weight: indexWeight,
              retitled: true, empty: true,
              _fm: newIdxFm, _new: true, _uid: _generateUid()
            };
            _navBatchQueue.push({
              type: 'create-page', path: indexPath,
              content: newIdxContent, item: indexItem
            });
          }

          var matchingOldDir = null;
          for (var fmk in folderRenameMap) {
            if (folderRenameMap.hasOwnProperty(fmk) && folderRenameMap[fmk] === secDir) {
              matchingOldDir = fmk; break;
            }
          }
          var oldSection = matchingOldDir ? existingSectionsByDir[matchingOldDir] : null;

          var sectionItem = {
            type: 'section',
            title: navItem.title,
            _uid: oldSection ? oldSection._uid : _generateUid(),
            index_meta: { weight: indexWeight },
            children: []
          };
          if (!oldSection) {
            sectionItem._new = true;
          } else if (matchingOldDir !== secDir) {
            sectionItem._renamed = true;
            sectionItem._originalPath = matchingOldDir;
          }

          var sectionChildren = buildTree(navItem.children, secDir);
          sectionItem.children = [indexItem].concat(sectionChildren);
          result.push(sectionItem);
        }
      }
      return result;
    }

    var newNavData = buildTree(navStructure, '');

    var placedPaths = {};
    (function collectPlaced(items) {
      for (var pi = 0; pi < items.length; pi++) {
        var pItem = items[pi];
        if (pItem.src_path) placedPaths[pItem.src_path] = true;
        if (pItem._originalPath) placedPaths[pItem._originalPath] = true;
        if (pItem.children) collectPlaced(pItem.children);
      }
    })(newNavData);

    var allPaths = allMdSrcPaths || (typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : []);
    var hiddenItems = [];
    for (var h = 0; h < allPaths.length; h++) {
      var hp = allPaths[h];
      if (!placedPaths[hp]) {
        var hiddenExisting = existingByPath[hp];
        var hiddenFm = (hiddenExisting && hiddenExisting._fm)
          ? Object.assign({}, hiddenExisting._fm)
          : (fmMap[hp] ? Object.assign({}, fmMap[hp]) : {});
        hiddenFm.headless = true;
        hiddenItems.push({
          type: 'page',
          src_path: hp,
          title: hiddenExisting ? hiddenExisting.title : hp,
          headless: true,
          _fm: hiddenFm,
          _uid: hiddenExisting ? hiddenExisting._uid : _generateUid()
        });
      }
    }

    _precomputeHiddenConsolidation(hiddenItems, newNavData, folderRenameMap);

    var ymlTransforms = [_removeNavKeyFromYaml];
    if (suggestedDefaultWeight) {
      ymlTransforms.push(function (yml) {
        return _replaceDefaultPageWeight(yml, suggestedDefaultWeight);
      });
    }

    for (var vt = 0; vt < ymlTransforms.length; vt++) {
      _virtualMkdocsYml = ymlTransforms[vt](_virtualMkdocsYml || '');
    }
    if (_virtualOriginalMkdocsYml != null) {
      for (var vo = 0; vo < ymlTransforms.length; vo++) {
        _virtualOriginalMkdocsYml = ymlTransforms[vo](_virtualOriginalMkdocsYml);
      }
    }

    if (suggestedDefaultWeight) {
      liveWysiwygNavWeightConfig.default_page_weight = suggestedDefaultWeight;
    }

    var oldAssets = [];
    (function collectAssets(items) {
      for (var ca = 0; ca < items.length; ca++) {
        if (items[ca].type === 'asset' && items[ca].src_path) oldAssets.push(items[ca]);
        if (items[ca].children) collectAssets(items[ca].children);
      }
    })(liveWysiwygNavData);

    for (var oa = 0; oa < oldAssets.length; oa++) {
      var asset = oldAssets[oa];
      var assetDir = _getDir(asset.src_path) || '';
      var targetDir = assetDir;
      for (var frk in folderRenameMap) {
        if (!folderRenameMap.hasOwnProperty(frk)) continue;
        if (assetDir === frk) {
          targetDir = folderRenameMap[frk];
          break;
        }
        if (assetDir.indexOf(frk + '/') === 0) {
          targetDir = folderRenameMap[frk] + assetDir.substring(frk.length);
          break;
        }
      }
      if (targetDir !== assetDir) {
        var filename = asset.src_path.split('/').pop();
        asset._originalPath = asset.src_path;
        asset._renamed = true;
        asset.src_path = targetDir ? targetDir + '/' + filename : filename;
      }
      var targetItems = _findSectionChildren(newNavData, targetDir);
      var createdSection = false;
      if (!targetItems) {
        targetItems = _ensureSectionForDirIn(newNavData, targetDir);
        createdSection = true;
      }
      targetItems.push(asset);
    }

    liveWysiwygNavData.length = 0;
    for (var n = 0; n < newNavData.length; n++) {
      liveWysiwygNavData.push(newNavData[n]);
    }
    _assignUids(liveWysiwygNavData);
  }

  function _removeNavKeyFromYaml(yaml) {
    if (!yaml || typeof yaml !== 'string') return yaml;
    var lines = yaml.split('\n');
    var result = [];
    var inNav = false;
    var navIndent = 0;
    for (var i = 0; i < lines.length; i++) {
      var line = lines[i];
      var m = line.match(/^(\s*)nav\s*:\s*$/);
      if (m) {
        inNav = true;
        navIndent = m[1].length;
        continue;
      }
      if (inNav) {
        var trimmed = line.trimLeft();
        if (trimmed === '' || trimmed.startsWith('#')) {
          var indent = line.length - trimmed.length;
          if (indent <= navIndent) inNav = false;
          else { continue; }
        } else {
          var indent = line.length - trimmed.length;
          if (indent <= navIndent) inNav = false;
          else { continue; }
        }
      }
      result.push(line);
    }
    return result.join('\n');
  }

  function _startMigrationFlow() {
    _prefetchMkdocsYml().then(function () {
      var cfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
      var pluginJustAdded = !cfg.enabled;
      var navStructure = _parseYamlNavKey(_virtualMkdocsYml);
      if (!navStructure || !navStructure.length) {
        _showNavDialog('No nav structure found in mkdocs.yml. Nothing to migrate.', [{ text: 'OK', value: 'ok' }]);
        return;
      }

      var dupes = _migrationCheckDuplicates(navStructure);
      if (dupes.length) {
        var html = '<p style="margin:0 0 8px"><strong>Cannot migrate:</strong> the nav key contains duplicate page entries.</p>' +
          '<p style="margin:0 0 8px">Remove duplicates from mkdocs.yml before migrating:</p>' +
          '<ul style="margin:4px 0;padding-left:20px;font-family:monospace;font-size:.8rem">';
        for (var d = 0; d < dupes.length; d++) {
          html += '<li>' + dupes[d].replace(/</g, '&lt;') + '</li>';
        }
        html += '</ul>';
        return _showNavDialogHtml(html, [{ text: 'OK', value: 'ok' }]);
      }

      var tree = _migrationComputeTargetTree(navStructure);
      return _scanClaimedIndexContent(tree.claimedIndexPaths).then(function () {

      var moveCount = 0;
      for (var m = 0; m < tree.pages.length; m++) {
        if (tree.pages[m].oldPath !== tree.pages[m].targetPath) moveCount++;
      }
      var splitCount = 0;
      var createCount = 0;
      for (var c = 0; c < tree.indexes.length; c++) {
        if (tree.indexes[c].existingIndexPath) splitCount++;
        else createCount++;
      }

      var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
      var curDefaultWeight = nwCfg.default_page_weight !== undefined ? nwCfg.default_page_weight : 1000;
      var migMaxWeight = 0;
      for (var mw = 0; mw < tree.pages.length; mw++) {
        if (tree.pages[mw].weight != null && tree.pages[mw].weight > migMaxWeight) migMaxWeight = tree.pages[mw].weight;
      }
      for (var iw = 0; iw < tree.indexes.length; iw++) {
        if (tree.indexes[iw].weight != null && tree.indexes[iw].weight > migMaxWeight) migMaxWeight = tree.indexes[iw].weight;
      }
      var suggestedWeight = migMaxWeight > curDefaultWeight ? Math.ceil((migMaxWeight + 500) / 1000) * 1000 : 0;

      var summaryHtml = '<p style="margin:0 0 12px">This will migrate your navigation from the mkdocs.yml <code>nav</code> key to mkdocs-nav-weight frontmatter.</p>' +
        '<p style="margin:0 0 4px"><strong>Summary:</strong></p>' +
        '<ul style="margin:4px 0 12px;padding-left:20px;font-size:.83rem">';
      if (pluginJustAdded) summaryHtml += '<li>Add <code>mkdocs-nav-weight</code> plugin to mkdocs.yml</li>';
      if (splitCount) summaryHtml += '<li>Split ' + splitCount + ' existing index.md file' + (splitCount > 1 ? 's' : '') + ' (content renamed, thin index created)</li>';
      if (createCount) summaryHtml += '<li>Create ' + createCount + ' new index.md file' + (createCount > 1 ? 's' : '') + ' for sections</li>';
      if (moveCount) summaryHtml += '<li>Move ' + moveCount + ' document' + (moveCount > 1 ? 's' : '') + ' to match nav structure</li>';
      summaryHtml += '<li>Set titles and weights on all ' + (Object.keys(tree.inNavPaths).length) + ' nav pages</li>';
      var hiddenCount = 0;
      var allPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
      for (var h = 0; h < allPaths.length; h++) {
        if (!tree.inNavPaths[allPaths[h]]) hiddenCount++;
      }
      if (hiddenCount) summaryHtml += '<li>Mark ' + hiddenCount + ' unlisted page' + (hiddenCount > 1 ? 's' : '') + ' as headless</li>';
      summaryHtml += '<li>Remove <code>nav</code> key from mkdocs.yml</li>';
      if (suggestedWeight) summaryHtml += '<li>Update <code>default_page_weight</code> to ' + suggestedWeight + ' in mkdocs.yml (current: ' + curDefaultWeight + ', max assigned: ' + migMaxWeight + ')</li>';
      if (hiddenCount) summaryHtml += '<li>Consolidate hidden docs into referencing directories where possible</li>';
      summaryHtml += '</ul>';
      summaryHtml += '<p style="margin:0 0 12px;font-size:.83rem">Relative links will be updated automatically when documents are moved.</p>';
      summaryHtml += '<p style="margin:0 0 12px;font-size:.83rem">Would you like to stage a migration of your nav data?</p>';

      return _showNavDialogHtml(summaryHtml, [
        { text: 'Cancel', value: 'cancel' },
        { text: 'Stage Migration', value: 'start', className: 'live-wysiwyg-nav-dialog-primary' }
      ]).then(function (result) {
        if (result !== 'start') return;
        if (!_navEditMode) _enterNavEditMode();
        if (pluginJustAdded) _stageNavWeightPlugin();
        _applyMigrationToNavData(navStructure, allPaths, suggestedWeight);
        _navMigrationPending = true;
        _removeNavTopWarning('nav-coexistence');
        _addNavBadge({
          className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-migration-badge',
          text: 'Pending mkdocs.yml nav migration'
        });
        _commitNavSnapshot();
      });
      }); // _scanClaimedIndexContent.then
    });
  }

  function _insertNavWeightEntry(yml) {
    var pluginsMatch = yml.match(/^plugins:\s*$/m);
    var newEntry = '\n  - mkdocs-nav-weight:\n      default_page_weight: 1000\n';
    if (pluginsMatch) {
      return yml.substring(0, pluginsMatch.index + pluginsMatch[0].length) + newEntry +
        yml.substring(pluginsMatch.index + pluginsMatch[0].length);
    }
    return yml + '\nplugins:' + newEntry;
  }

  function _stageNavWeightPlugin() {
    if (typeof liveWysiwygNavWeightConfig === 'undefined') {
      window.liveWysiwygNavWeightConfig = {};
    }
    liveWysiwygNavWeightConfig.enabled = true;
    if (liveWysiwygNavWeightConfig.default_page_weight == null) {
      liveWysiwygNavWeightConfig.default_page_weight = 1000;
    }
    if (!liveWysiwygNavWeightConfig.frontmatter_defaults) {
      var dpw = liveWysiwygNavWeightConfig.default_page_weight;
      liveWysiwygNavWeightConfig.frontmatter_defaults = {
        weight: dpw, index_weight: -10, headless: false, retitled: false, empty: false
      };
    }
    _virtualMkdocsYml = _insertNavWeightEntry(_virtualMkdocsYml || '');
    if (_virtualOriginalMkdocsYml != null) {
      _virtualOriginalMkdocsYml = _insertNavWeightEntry(_virtualOriginalMkdocsYml);
    }
    _removeNavTopWarning('nav-weight-not-installed');
    if (!_navBadges.some(function (b) { return b.text === 'mkdocs-nav-weight plugin staged'; })) {
      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge',
        text: 'mkdocs-nav-weight plugin staged'
      });
    }
  }

  function _applyNavWeightPlugin() {
    _stageNavWeightPlugin();
    _commitNavSnapshot();
    if (!_navEditMode) _enterNavEditMode();
  }

  function _applyDefaultPageWeight(newWeight) {
    _virtualMkdocsYml = _replaceDefaultPageWeight(_virtualMkdocsYml || '', newWeight);
    if (_virtualOriginalMkdocsYml != null) {
      _virtualOriginalMkdocsYml = _replaceDefaultPageWeight(_virtualOriginalMkdocsYml, newWeight);
    }
    liveWysiwygNavWeightConfig.default_page_weight = newWeight;
    _removeNavTopWarning('weight-exceeds-default');
    _commitNavSnapshot();
    if (!_navEditMode) _enterNavEditMode();
  }

  function _replaceDefaultPageWeight(yml, newWeight) {
    var re = /^(\s*default_page_weight\s*:\s*)\d+/m;
    if (re.test(yml)) {
      return yml.replace(re, '$1' + newWeight);
    }
    var pluginRe = /^(\s*-\s*mkdocs-nav-weight\s*:\s*\n)/m;
    var match = pluginRe.exec(yml);
    if (match) {
      var indent = match[1].match(/^(\s*)/)[1];
      return yml.substring(0, match.index + match[0].length) +
        indent + '    default_page_weight: ' + newWeight + '\n' +
        yml.substring(match.index + match[0].length);
    }
    return yml;
  }

  // ======================================================================
  // NAV MENU - Caution icon system
  // ======================================================================
  function _getCautionPages() {
    var raw;
    try { raw = localStorage.getItem('live_wysiwyg_caution_pages'); } catch (e) { /* private browsing */ }
    if (!raw) return [];
    try {
      var parsed = JSON.parse(raw);
      if (!Array.isArray(parsed)) return [];
      return parsed.map(function (entry) {
        var reasons = Array.isArray(entry.reasons) ? entry.reasons : [];
        if (!reasons.length) reasons = ['Link integrity may need attention'];
        return { path: entry.path || '', reasons: reasons, renames: entry.renames || 0 };
      });
    } catch (e) { return []; }
  }

  function _setCautionPages(pages) {
    try { localStorage.setItem('live_wysiwyg_caution_pages', JSON.stringify(pages)); } catch (e) { /* private browsing */ }
  }

  function _addCautionPage(srcPath, reason) {
    var actualPath = _resolveChainedRename(srcPath);
    var msg = reason || 'Link integrity may need attention';
    if (_warningDirectMode) {
      var pages = _getCautionPages();
      for (var i = 0; i < pages.length; i++) {
        if (pages[i].path === actualPath) {
          if (pages[i].reasons.indexOf(msg) === -1) {
            pages[i].reasons.push(msg);
            _setCautionPages(pages);
            _ensureNavUncollapsed();
          }
          return;
        }
      }
      pages.push({ path: actualPath, reasons: [msg], renames: 0 });
      _setCautionPages(pages);
      _ensureNavUncollapsed();
      return;
    }
    var item = _findNavItemByPath(actualPath);
    if (!item) return;
    if (!item._warnings) item._warnings = [];
    for (var w = 0; w < item._warnings.length; w++) {
      if (item._warnings[w].reason === msg) return;
    }
    item._warnings.push({ reason: msg, renames: 0 });
    if (!_suppressWarningSnapshot) _commitNavSnapshot();
    _ensureNavUncollapsed();
  }

  function _migrateCautionForRename(oldPath, newPath) {
    var pages = _getCautionPages();
    var changed = false;
    for (var i = 0; i < pages.length; i++) {
      if (pages[i].path === oldPath) {
        pages[i].path = newPath;
        pages[i].renames = (pages[i].renames || 0) + 1;
        changed = true;
      }
    }
    if (changed) _setCautionPages(pages);
  }

  // _cautionRenamePrefix and _applyCautionIcons removed — warnings now render
  // inline from item._warnings during _buildNavItems

  function _showCautionPopup(anchorEl, navItem) {
    var existing = document.querySelector('.live-wysiwyg-nav-popup');
    if (existing) existing.parentNode.removeChild(existing);

    var popup = document.createElement('div');
    popup.className = 'live-wysiwyg-nav-popup';

    var warnings = navItem._warnings || [];
    var renames = (warnings.length && warnings[0].renames) ? warnings[0].renames : 0;
    var prefix = '';
    if (renames === 1) prefix = 'Before document was renamed: ';
    else if (renames > 1) prefix = 'The document was renamed ' + renames + ' times after warning: ';
    var reasons = warnings.map(function (w) { return w.reason; });
    if (!reasons.length) reasons = ['Link integrity may need attention'];

    if (prefix) {
      var prefixEl = document.createElement('div');
      prefixEl.style.fontWeight = 'bold';
      prefixEl.style.marginBottom = '4px';
      prefixEl.textContent = prefix;
      popup.appendChild(prefixEl);
    }

    var intro = document.createElement('div');
    intro.style.marginBottom = '6px';
    intro.textContent = 'Review content for the following issues:';
    popup.appendChild(intro);

    if (reasons.length === 1) {
      var single = document.createElement('div');
      single.style.fontSize = '.8rem';
      single.style.opacity = '.85';
      single.textContent = '\u2022 ' + reasons[0];
      popup.appendChild(single);
    } else {
      var ul = document.createElement('ul');
      ul.style.margin = '4px 0';
      ul.style.paddingLeft = '16px';
      ul.style.fontSize = '.8rem';
      ul.style.opacity = '.85';
      for (var r = 0; r < reasons.length; r++) {
        var li = document.createElement('li');
        li.textContent = reasons[r];
        ul.appendChild(li);
      }
      popup.appendChild(ul);
    }

    var totalCautionItems = _collectNavWarnings().length;
    var buttons = [
      {
        text: 'Resolve', action: function () {
          delete navItem._warnings;
          delete navItem._deadLinks;
          _hideDeadLinkPanel();
          _commitNavSnapshot();
        }
      }
    ];
    if (totalCautionItems > 1) {
      buttons.push({
        text: 'Resolve All', action: function () {
          _clearAllNavWarnings();
          _hideDeadLinkPanel();
          _commitNavSnapshot();
        }
      });
    }
    var cautionBtnRow = document.createElement('div');
    cautionBtnRow.style.marginTop = '8px';
    buttons.forEach(function (btn) {
      var b = document.createElement('button');
      b.textContent = btn.text;
      b.addEventListener('click', function () {
        popup.parentNode.removeChild(popup);
        if (btn.action) btn.action();
      });
      cautionBtnRow.appendChild(b);
    });
    popup.appendChild(cautionBtnRow);

    var rect = anchorEl.getBoundingClientRect();
    popup.style.position = 'fixed';
    popup.style.left = Math.max(4, rect.left - 50) + 'px';
    popup.style.visibility = 'hidden';
    document.body.appendChild(popup);
    var popupH = popup.offsetHeight;
    var spaceBelow = window.innerHeight - rect.bottom - 8;
    if (spaceBelow < popupH && rect.top > popupH + 8) {
      popup.style.top = (rect.top - popupH - 4) + 'px';
    } else {
      popup.style.top = (rect.bottom + 4) + 'px';
    }
    popup.style.visibility = '';

    function _dismissCautionPopup() {
      if (popup.parentNode) popup.parentNode.removeChild(popup);
      document.removeEventListener('mousedown', closeHandler, true);
    }
    var resolveBtn = cautionBtnRow.querySelector('button');
    _attachDialogKeyboard(popup, {
      category: 'informational',
      onDismiss: function () { _dismissCautionPopup(); },
      autoFocus: resolveBtn
    });

    var closeHandler = function (e) {
      if (!popup.contains(e.target) && e.target !== anchorEl) {
        _dismissCautionPopup();
      }
    };
    setTimeout(function () {
      document.addEventListener('mousedown', closeHandler, true);
    }, 0);
  }

  // ======================================================================
  // DEAD LINK FINDER — localStorage storage
  // ======================================================================
  function _getDeadLinkPages() {
    try {
      var raw = localStorage.getItem('live_wysiwyg_dead_links');
      if (!raw) return [];
      var parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed : [];
    } catch (e) { return []; }
  }

  function _setDeadLinkPages(pages) {
    try {
      if (!pages || !pages.length) {
        localStorage.removeItem('live_wysiwyg_dead_links');
        return;
      }
      localStorage.setItem('live_wysiwyg_dead_links', JSON.stringify(pages));
    } catch (e) { /* storage full or unavailable */ }
  }

  function _getUnreferencedAssets() {
    try {
      var raw = localStorage.getItem('live_wysiwyg_unreferenced_assets');
      if (!raw) return [];
      var parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed : [];
    } catch (e) { return []; }
  }

  function _setUnreferencedAssets(files) {
    try {
      if (!files || !files.length) {
        localStorage.removeItem('live_wysiwyg_unreferenced_assets');
        return;
      }
      localStorage.setItem('live_wysiwyg_unreferenced_assets', JSON.stringify(files));
    } catch (e) {}
  }

  function _fetchUnreferencedFiles() {
    return _apiPost('/unreferenced-files', {}).then(function (resp) {
      return (resp && resp.files) ? resp.files : [];
    });
  }

  function _addDeadLinksForPage(srcPath, internal, external) {
    if (_warningDirectMode) {
      var pages = _getDeadLinkPages();
      var found = null;
      for (var i = 0; i < pages.length; i++) {
        if (pages[i].path === srcPath) { found = pages[i]; break; }
      }
      if (!found) {
        found = { path: srcPath, internal: [], external: [] };
        pages.push(found);
      }
      if (internal) found.internal = internal;
      if (external) found.external = external;
      if (!found.internal.length && !found.external.length) {
        pages = pages.filter(function (p) { return p.path !== srcPath; });
      }
      _setDeadLinkPages(pages);
      return;
    }
    var item = _findNavItemByPath(srcPath);
    if (!item) return;
    if (!item._deadLinks) item._deadLinks = { internal: [], external: [] };
    if (internal) item._deadLinks.internal = internal;
    if (external) item._deadLinks.external = external;
    if (!item._deadLinks.internal.length && !item._deadLinks.external.length) {
      delete item._deadLinks;
    }
    if (!_suppressWarningSnapshot) _commitNavSnapshot();
  }

  // ======================================================================
  // DEAD LINK FINDER — Scanner
  // ======================================================================
  function _scanDeadLinks(mode, options) {
    if (!options) options = {};
    if (typeof liveWysiwygLinkCheckPort === 'undefined' || !liveWysiwygLinkCheckPort) {
      if (!options.quiet) {
        _showNavDialog('Dead link checker server is not available.', [
          { text: 'OK', value: 'ok' }
        ]);
      }
      if (options.onComplete) options.onComplete({});
      return;
    }
    var overlay = options.quiet ? null : _showFullScreenTransition('Scanning pages for links...');
    var allPaths = (typeof liveWysiwygAllMdSrcPaths !== 'undefined') ? liveWysiwygAllMdSrcPaths : [];
    var linkPatterns = [
      { re: /(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, textGroup: 1, targetGroup: 2 },
      { re: /!\[([^\]]*)\]\(([^)]+)\)/g, textGroup: 1, targetGroup: 2 },
      { re: /<img[^>]+src=["']([^"']+)["']/g, textGroup: 0, targetGroup: 1 },
      { re: /^\[([^\]]+)\]:\s+(\S+)/gm, textGroup: 1, targetGroup: 2 }
    ];

    var allChecks = [];
    var checkMeta = [];
    var externalUrlMap = {};
    var pageIdx = 0;

    function processNextPage() {
      if (pageIdx >= allPaths.length) {
        _sendLinkChecks(allChecks, checkMeta, externalUrlMap, mode, overlay, options);
        return;
      }
      var path = allPaths[pageIdx];
      pageIdx++;
      if (!options.quiet) _updateTransitionText(overlay, 'Scanning page ' + pageIdx + ' of ' + allPaths.length + '...');
      _wsGetContents(path).then(function (content) {
        if (!content) { processNextPage(); return; }
        var zones = _findExclusionZones(content);
        for (var p = 0; p < linkPatterns.length; p++) {
          var pat = linkPatterns[p];
          pat.re.lastIndex = 0;
          var m;
          while ((m = pat.re.exec(content)) !== null) {
            if (_isInExclusionZone(m.index, zones)) continue;
            var target = m[pat.targetGroup];
            var text = pat.textGroup === 0 ? target : m[pat.textGroup];
            if (!target) continue;

            var hashIdx = target.indexOf('#');
            var queryIdx = target.indexOf('?');
            var splitIdx = -1;
            if (hashIdx !== -1 && queryIdx !== -1) splitIdx = Math.min(hashIdx, queryIdx);
            else if (hashIdx !== -1) splitIdx = hashIdx;
            else if (queryIdx !== -1) splitIdx = queryIdx;
            var pathPart = splitIdx >= 0 ? target.substring(0, splitIdx) : target;
            if (!pathPart) continue;

            var isExternal = pathPart.indexOf('http://') === 0 || pathPart.indexOf('https://') === 0;
            var isInternal = !isExternal && pathPart.indexOf('mailto:') !== 0 &&
              pathPart.indexOf('data:') !== 0 && pathPart.indexOf('#') !== 0;

            if (mode === 'internal' && !isInternal) continue;
            if (mode === 'external' && !isExternal) continue;

            if (isExternal) {
              if (!externalUrlMap[pathPart]) {
                externalUrlMap[pathPart] = [];
                allChecks.push({ type: 'external', url: pathPart });
                checkMeta.push({ srcPath: path, text: text, target: pathPart, kind: 'external' });
              }
              externalUrlMap[pathPart].push({ srcPath: path, text: text, target: pathPart });
            } else if (isInternal) {
              allChecks.push({ type: 'internal', from: path, target: pathPart });
              checkMeta.push({ srcPath: path, text: text, target: pathPart, kind: 'internal' });
            }
          }
        }
        processNextPage();
      }).catch(function () { processNextPage(); });
    }
    processNextPage();
  }

  function _sendLinkChecks(allChecks, checkMeta, externalUrlMap, mode, overlay, options) {
    if (!options) options = {};
    if (!allChecks.length) {
      _processDeadLinkResults(allChecks, [], checkMeta, externalUrlMap, mode, overlay, options);
      return;
    }
    var port = liveWysiwygLinkCheckPort;
    var host = window.location.hostname || '127.0.0.1';
    var baseUrl = 'http://' + host + ':' + port + '/check-links';
    var allResults = new Array(allChecks.length);
    var filled = 0;

    if (!options.quiet) _updateTransitionText(overlay, 'Checking ' + allChecks.length + ' links (this may take a moment for external links)...');

    _postLinkBatch(baseUrl, allChecks, 300000, options.fileLayout).then(function (results) {
      for (var i = 0; i < results.length; i++) { allResults[i] = results[i]; }
      filled = results.length;
      _processDeadLinkResults(allChecks, allResults, checkMeta, externalUrlMap, mode, overlay, options);
    }).catch(function () {
      _sendLinkBatches(baseUrl, allChecks, allResults, filled, checkMeta, externalUrlMap, mode, overlay, options);
    });
  }

  function _postLinkBatch(url, checks, timeoutMs, fileLayout) {
    var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
    var timer = null;
    if (controller && timeoutMs) {
      timer = setTimeout(function () { controller.abort(); }, timeoutMs);
    }
    var payload = { checks: checks };
    if (fileLayout) payload.file_layout = fileLayout;
    var opts = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    };
    if (controller) opts.signal = controller.signal;
    return fetch(url, opts).then(function (resp) {
      if (timer) clearTimeout(timer);
      if (!resp.ok) throw new Error('HTTP ' + resp.status);
      return resp.json();
    }).then(function (data) {
      return data.results || [];
    }).catch(function (err) {
      if (timer) clearTimeout(timer);
      throw err;
    });
  }

  function _sendLinkBatches(baseUrl, allChecks, allResults, startIdx, checkMeta, externalUrlMap, mode, overlay, options) {
    if (!options) options = {};
    var batchSize = 50;
    var remaining = allChecks.slice(startIdx);
    var totalBatches = Math.ceil(remaining.length / batchSize);
    var batchIdx = 0;

    function sendNext() {
      if (batchIdx >= totalBatches) {
        _processDeadLinkResults(allChecks, allResults, checkMeta, externalUrlMap, mode, overlay, options);
        return;
      }
      var chunk = remaining.slice(batchIdx * batchSize, (batchIdx + 1) * batchSize);
      if (!options.quiet) _updateTransitionText(overlay, 'Checking links: batch ' + (batchIdx + 1) + ' of ' + totalBatches + '...');
      _postLinkBatch(baseUrl, chunk, 60000, options.fileLayout).then(function (results) {
        for (var i = 0; i < results.length; i++) {
          allResults[startIdx + batchIdx * batchSize + i] = results[i];
        }
        batchIdx++;
        sendNext();
      }).catch(function () {
        batchIdx++;
        sendNext();
      });
    }
    sendNext();
  }

  function _processDeadLinkResults(allChecks, allResults, checkMeta, externalUrlMap, mode, overlay, options) {
    if (!options) options = {};
    var deadByPage = {};
    for (var i = 0; i < allResults.length; i++) {
      var result = allResults[i];
      if (!result || result.ok) continue;
      var meta = checkMeta[i];
      if (!meta) continue;

      if (meta.kind === 'external' && externalUrlMap[meta.target]) {
        var occurrences = externalUrlMap[meta.target];
        for (var j = 0; j < occurrences.length; j++) {
          var occ = occurrences[j];
          if (!deadByPage[occ.srcPath]) deadByPage[occ.srcPath] = { internal: [], external: [] };
          deadByPage[occ.srcPath].external.push({
            text: occ.text, target: occ.target,
            status: result.status || 0, error: result.error || ''
          });
        }
      } else if (meta.kind === 'internal') {
        if (options.filterTargets && !options.filterTargets[meta.target]) {
          var pageDir = _getDir(meta.srcPath);
          var absTarget = _resolvePath(pageDir, meta.target);
          if (!absTarget || !options.filterTargets[absTarget]) continue;
        }
        if (!deadByPage[meta.srcPath]) deadByPage[meta.srcPath] = { internal: [], external: [] };
        deadByPage[meta.srcPath].internal.push({
          text: meta.text, target: meta.target
        });
      }
    }

    if (options.quiet) {
      _finalizeDeadLinkResults(deadByPage, mode, overlay, [], options);
      return;
    }

    if (mode === 'internal') {
      _updateTransitionText(overlay, 'Checking for unreferenced assets...');
      _fetchUnreferencedFiles().catch(function () { return []; }).then(function (unreferenced) {
        _finalizeDeadLinkResults(deadByPage, mode, overlay, unreferenced || [], options);
      });
    } else {
      _finalizeDeadLinkResults(deadByPage, mode, overlay, [], options);
    }
  }

  function _finalizeDeadLinkResults(deadByPage, mode, overlay, unreferenced, options) {
    if (!options) options = {};
    var deadPageCount = Object.keys(deadByPage).length;
    if (deadPageCount === 0 && !unreferenced.length) {
      if (!options.quiet) {
        _fadeOutOverlay(overlay);
        _showToast('No dead links found!');
      }
      if (options.onComplete) options.onComplete(deadByPage);
      return;
    }

    if (options.quiet) {
      _commitDeadLinkResults(deadByPage, mode, unreferenced, options);
      return;
    }

    var analysis = _buildDeadLinkGroups(deadByPage);
    if (analysis.groups.length > 0) {
      _fadeOutOverlay(overlay);
      _showDeadLinkAnalysisWizard(analysis, deadByPage, mode).then(function (filtered) {
        if (filtered) _commitDeadLinkResults(filtered, mode, unreferenced, options);
      });
    } else {
      _fadeOutOverlay(overlay);
      _commitDeadLinkResults(deadByPage, mode, unreferenced, options);
    }
  }

  function _commitDeadLinkResults(deadByPage, mode, unreferenced, options) {
    if (!options) options = {};
    if (!unreferenced) unreferenced = [];
    var deadPageCount = Object.keys(deadByPage).length;
    if (deadPageCount === 0 && !unreferenced.length) {
      if (!options.quiet) _showToast('No dead links remain after exclusions.');
      if (options.onComplete) options.onComplete(deadByPage);
      return;
    }

    var needsSnapshot = false;
    _suppressWarningSnapshot = true;

    if (deadPageCount > 0) {
      for (var pagePath in deadByPage) {
        if (!deadByPage.hasOwnProperty(pagePath)) continue;
        var info = deadByPage[pagePath];
        _addDeadLinksForPage(pagePath,
          (mode === 'external') ? null : info.internal,
          (mode === 'internal') ? null : info.external
        );
        if (info.internal.length) _addCautionPage(pagePath, 'Internal dead links found');
        if (info.external.length) _addCautionPage(pagePath, 'External dead links found');
      }
      needsSnapshot = true;
    }

    if (!options.quiet) {
      _clearUnreferencedAssetWarnings();
      if (unreferenced.length) {
        for (var u = 0; u < unreferenced.length; u++) {
          var assetItem = _findNavItemByPath(unreferenced[u]);
          if (assetItem) {
            if (!assetItem._warnings) assetItem._warnings = [];
            var alreadyWarned = false;
            for (var w = 0; w < assetItem._warnings.length; w++) {
              if (assetItem._warnings[w].reason === 'Unreferenced asset') { alreadyWarned = true; break; }
            }
            if (!alreadyWarned) assetItem._warnings.push({ reason: 'Unreferenced asset', renames: 0 });
          }
        }
        needsSnapshot = true;
      }
    }

    _suppressWarningSnapshot = false;

    if (!options.quiet) {
      var needsShowHidden = unreferenced.length > 0;
      if (!needsShowHidden && deadPageCount > 0) {
        for (var hp in deadByPage) {
          if (!deadByPage.hasOwnProperty(hp)) continue;
          var hpItem = _findNavItemByPath(hp);
          if (hpItem && hpItem.headless) { needsShowHidden = true; break; }
        }
      }
      if (needsShowHidden) _setSetting('live_wysiwyg_show_hidden', '1');
    }

    if (needsSnapshot) {
      _commitNavSnapshot();
      if (!options.quiet) _checkDeadLinksForCurrentPage();
    }

    if (!options.quiet) {
      _setUnreferencedAssets(unreferenced);

      var totalDead = 0;
      for (var p in deadByPage) {
        if (deadByPage.hasOwnProperty(p)) {
          totalDead += deadByPage[p].internal.length + deadByPage[p].external.length;
        }
      }
      var parts = [];
      if (totalDead > 0) {
        parts.push(totalDead + ' dead link' + (totalDead !== 1 ? 's' : '') + ' across ' +
          deadPageCount + ' page' + (deadPageCount !== 1 ? 's' : ''));
      }
      if (unreferenced.length) {
        parts.push(unreferenced.length + ' unreferenced asset' + (unreferenced.length !== 1 ? 's' : '') + ' in docs');
      }
      _showToast(parts.length ? 'Found ' + parts.join(', ') + '.' : 'No issues found.');
    }

    if (options.onComplete) options.onComplete(deadByPage);
  }

  function _updateTransitionText(overlay, text) {
    if (!overlay) return;
    var el = overlay.querySelector('.live-wysiwyg-nav-transition-text');
    if (el) el.textContent = text;
  }

  // ======================================================================
  // DEAD LINK FINDER — Analysis wizard (grouping + exclude UI)
  // ======================================================================
  function _extractUrlPrefix(url) {
    try {
      var m = url.match(/^(https?:\/\/[^/]+)(\/[^/]*\/?)?/);
      if (!m) return url;
      return m[1] + (m[2] || '/');
    } catch (e) { return url; }
  }

  function _buildDeadLinkGroups(deadByPage) {
    var groupMap = {};
    var totalExternal = 0;
    for (var pagePath in deadByPage) {
      if (!deadByPage.hasOwnProperty(pagePath)) continue;
      var ext = deadByPage[pagePath].external;
      for (var i = 0; i < ext.length; i++) {
        totalExternal++;
        var status = ext[i].status || 0;
        var prefix = _extractUrlPrefix(ext[i].target);
        var key = status + '|' + prefix;
        if (!groupMap[key]) {
          groupMap[key] = { status: status, prefix: prefix, count: 0 };
        }
        groupMap[key].count++;
      }
    }
    var groups = [];
    var groupedCount = 0;
    for (var k in groupMap) {
      if (groupMap.hasOwnProperty(k) && groupMap[k].count >= 2) {
        groups.push(groupMap[k]);
        groupedCount += groupMap[k].count;
      }
    }
    groups.sort(function (a, b) { return b.count - a.count; });
    return { groups: groups, groupedCount: groupedCount, ungroupedCount: totalExternal - groupedCount };
  }

  function _showDeadLinkAnalysisWizard(analysis, deadByPage, mode) {
    var totalDead = 0;
    var pageCount = 0;
    for (var p in deadByPage) {
      if (!deadByPage.hasOwnProperty(p)) continue;
      pageCount++;
      totalDead += deadByPage[p].internal.length + deadByPage[p].external.length;
    }

    return new Promise(function (resolve) {
      var overlay = document.createElement('div');
      overlay.className = 'live-wysiwyg-nav-dialog';
      var content = document.createElement('div');
      content.className = 'live-wysiwyg-nav-dialog-content';
      content.style.maxWidth = '580px';

      var title = document.createElement('div');
      title.style.fontWeight = '700';
      title.style.fontSize = '.95rem';
      title.style.marginBottom = '4px';
      title.textContent = 'Dead Link Analysis';
      content.appendChild(title);

      var summary = document.createElement('div');
      summary.style.fontSize = '.8rem';
      summary.style.color = 'var(--md-default-fg-color--light,#666)';
      summary.style.marginBottom = '12px';
      summary.textContent = 'Found ' + totalDead + ' dead link' + (totalDead !== 1 ? 's' : '') +
        ' across ' + pageCount + ' page' + (pageCount !== 1 ? 's' : '') +
        '. Exclude noisy patterns below.';
      content.appendChild(summary);

      var body = document.createElement('div');
      body.style.maxHeight = '45vh';
      body.style.overflowY = 'auto';
      body.style.marginBottom = '12px';

      var excludeSet = {};

      for (var g = 0; g < analysis.groups.length; g++) {
        (function (group, idx) {
          var row = document.createElement('div');
          row.className = 'live-wysiwyg-dead-link-wizard-row';

          var badge = document.createElement('span');
          badge.className = 'live-wysiwyg-dead-link-wizard-badge';
          badge.textContent = group.status || '?';
          row.appendChild(badge);

          var desc = document.createElement('span');
          desc.className = 'live-wysiwyg-dead-link-wizard-desc';
          var prefixDisplay = group.prefix.length > 50 ? group.prefix.substring(0, 47) + '...' : group.prefix;
          desc.textContent = group.count + ' link' + (group.count !== 1 ? 's' : '') +
            ' starting with ' + prefixDisplay;
          desc.title = group.prefix;
          row.appendChild(desc);

          var toggle = document.createElement('button');
          toggle.className = 'live-wysiwyg-dead-link-wizard-toggle';
          toggle.textContent = 'Include';
          var key = group.status + '|' + group.prefix;

          toggle.addEventListener('click', function () {
            if (excludeSet[key]) {
              delete excludeSet[key];
              toggle.textContent = 'Include';
              row.classList.remove('live-wysiwyg-dead-link-wizard-excluded');
            } else {
              excludeSet[key] = group;
              toggle.textContent = 'Exclude';
              row.classList.add('live-wysiwyg-dead-link-wizard-excluded');
            }
          });
          row.appendChild(toggle);
          body.appendChild(row);
        })(analysis.groups[g], g);
      }

      if (analysis.ungroupedCount > 0) {
        var other = document.createElement('div');
        other.className = 'live-wysiwyg-dead-link-wizard-row live-wysiwyg-dead-link-wizard-other';
        other.textContent = analysis.ungroupedCount + ' other external dead link' +
          (analysis.ungroupedCount !== 1 ? 's' : '') + ' (always included)';
        body.appendChild(other);
      }

      var internalCount = 0;
      for (var pp in deadByPage) {
        if (deadByPage.hasOwnProperty(pp)) internalCount += deadByPage[pp].internal.length;
      }
      if (internalCount > 0) {
        var intRow = document.createElement('div');
        intRow.className = 'live-wysiwyg-dead-link-wizard-row live-wysiwyg-dead-link-wizard-other';
        intRow.textContent = internalCount + ' internal dead link' +
          (internalCount !== 1 ? 's' : '') + ' (always included)';
        body.appendChild(intRow);
      }

      content.appendChild(body);

      var actions = document.createElement('div');
      actions.className = 'live-wysiwyg-nav-dialog-actions';

      var finished = false;
      function finishWizard(val) {
        if (finished) return;
        finished = true;
        if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
        resolve(val);
      }

      var applyBtn = document.createElement('button');
      applyBtn.className = 'live-wysiwyg-nav-dialog-primary';
      applyBtn.textContent = 'Apply';
      applyBtn.tabIndex = 1;
      applyBtn.addEventListener('click', function () {
        finishWizard(_applyDeadLinkExclusions(deadByPage, excludeSet));
      });
      actions.appendChild(applyBtn);

      var includeAllBtn = document.createElement('button');
      includeAllBtn.textContent = 'Include All';
      includeAllBtn.tabIndex = 2;
      includeAllBtn.addEventListener('click', function () {
        finishWizard(deadByPage);
      });
      actions.appendChild(includeAllBtn);

      _attachDialogKeyboard(overlay, {
        category: 'confirmation',
        onDismiss: function () { finishWizard(null); },
        onConfirm: function () { applyBtn.click(); },
        autoFocus: applyBtn
      });

      content.appendChild(actions);
      overlay.appendChild(content);
      document.body.appendChild(overlay);
    });
  }

  function _applyDeadLinkExclusions(deadByPage, excludeSet) {
    var hasExclusions = false;
    for (var k in excludeSet) { if (excludeSet.hasOwnProperty(k)) { hasExclusions = true; break; } }
    if (!hasExclusions) return deadByPage;

    for (var pagePath in deadByPage) {
      if (!deadByPage.hasOwnProperty(pagePath)) continue;
      deadByPage[pagePath].external = deadByPage[pagePath].external.filter(function (entry) {
        var prefix = _extractUrlPrefix(entry.target);
        var key = (entry.status || 0) + '|' + prefix;
        return !excludeSet[key];
      });
      if (!deadByPage[pagePath].internal.length && !deadByPage[pagePath].external.length) {
        delete deadByPage[pagePath];
      }
    }
    return deadByPage;
  }

  // ======================================================================
  // DEAD LINK FINDER — Panel overlay on TOC
  // ======================================================================
  function _showDeadLinkPanel(tocEl, pageDeadLinks) {
    _hideDeadLinkPanel();
    if (!tocEl || !pageDeadLinks || !pageDeadLinks._deadLinks) return;
    var dl = pageDeadLinks._deadLinks;
    var allLinks = [];
    if (dl.internal) {
      for (var i = 0; i < dl.internal.length; i++) {
        allLinks.push({ kind: 'internal', text: dl.internal[i].text, target: dl.internal[i].target });
      }
    }
    if (dl.external) {
      for (var j = 0; j < dl.external.length; j++) {
        var ext = dl.external[j];
        allLinks.push({
          kind: 'external', text: ext.text, target: ext.target,
          status: ext.status, error: ext.error
        });
      }
    }
    if (!allLinks.length) return;

    var panel = document.createElement('div');
    panel.className = 'live-wysiwyg-dead-link-panel';

    var header = document.createElement('div');
    header.className = 'live-wysiwyg-dead-link-panel-header';
    var headerTitle = document.createElement('span');
    headerTitle.textContent = 'Dead links on this page';
    header.appendChild(headerTitle);
    var closeBtn = document.createElement('button');
    closeBtn.className = 'live-wysiwyg-dead-link-panel-close';
    closeBtn.textContent = '\u00D7';
    closeBtn.title = 'Close panel';
    closeBtn.addEventListener('click', function () { _hideDeadLinkPanel(); });
    header.appendChild(closeBtn);
    panel.appendChild(header);

    var list = document.createElement('div');
    list.className = 'live-wysiwyg-dead-link-panel-list';

    for (var k = 0; k < allLinks.length; k++) {
      (function (link) {
        var entry = document.createElement('div');
        entry.className = 'live-wysiwyg-dead-link-entry';
        entry.title = link.target;

        var nameEl = document.createElement('span');
        nameEl.className = 'live-wysiwyg-dead-link-entry-text';
        var displayText = link.text || link.target;
        nameEl.textContent = displayText.length > 40 ? displayText.substring(0, 37) + '...' : displayText;
        entry.appendChild(nameEl);

        var label = document.createElement('span');
        label.className = 'live-wysiwyg-dead-link-entry-label';
        if (link.kind === 'internal') {
          label.textContent = 'internal';
        } else {
          label.textContent = link.status ? 'external (' + link.status + ')' : 'external';
        }
        entry.appendChild(label);

        var resolveOne = document.createElement('button');
        resolveOne.className = 'live-wysiwyg-dead-link-entry-resolve';
        resolveOne.textContent = '\u2715';
        resolveOne.title = 'Resolve this link';
        resolveOne.addEventListener('click', function (e) {
          e.stopPropagation();
          _resolveOneDeadLink(currentPath, link.kind, link.target);
          entry.parentNode.removeChild(entry);
          var remaining = list.querySelectorAll('.live-wysiwyg-dead-link-entry');
          if (!remaining.length) _hideDeadLinkPanel();
        });
        entry.appendChild(resolveOne);

        entry.addEventListener('click', function () {
          _scrollToDeadLink(link.target, link.text);
        });
        list.appendChild(entry);
      })(allLinks[k]);
    }
    panel.appendChild(list);

    var actions = document.createElement('div');
    actions.className = 'live-wysiwyg-dead-link-panel-actions';

    var currentPath = _getCurrentSrcPath();

    var resolvePageBtn = document.createElement('button');
    resolvePageBtn.textContent = 'Resolve Page';
    resolvePageBtn.addEventListener('click', function () {
      var pageItem = _findNavItemByPath(currentPath);
      if (pageItem) {
        delete pageItem._deadLinks;
        _removeNavWarningReason(pageItem, 'Internal dead links found');
        _removeNavWarningReason(pageItem, 'External dead links found');
        _commitNavSnapshot();
      }
      _hideDeadLinkPanel();
    });
    actions.appendChild(resolvePageBtn);

    var allDeadLinks = _collectNavDeadLinks();
    if (allDeadLinks.length > 1) {
      var resolveAllBtn = document.createElement('button');
      resolveAllBtn.textContent = 'Resolve All';
      resolveAllBtn.addEventListener('click', function () {
        _clearAllNavDeadLinks();
        _commitNavSnapshot();
        _hideDeadLinkPanel();
      });
      actions.appendChild(resolveAllBtn);
    }
    panel.appendChild(actions);

    _attachDialogKeyboard(panel, {
      category: 'informational',
      onDismiss: function () { _hideDeadLinkPanel(); },
      autoFocus: closeBtn
    });

    var tocRect = tocEl.getBoundingClientRect();
    panel.style.top = tocRect.top + 'px';
    panel.style.left = tocRect.left + 'px';
    panel.style.width = tocRect.width + 'px';
    panel.style.maxHeight = (window.innerHeight - tocRect.top) + 'px';
    document.body.appendChild(panel);
  }

  function _hideDeadLinkPanel() {
    var existing = document.querySelector('.live-wysiwyg-dead-link-panel');
    if (existing && existing.parentNode) existing.parentNode.removeChild(existing);
  }

  function _resolveOneDeadLink(pagePath, kind, target) {
    var item = _findNavItemByPath(pagePath);
    if (!item || !item._deadLinks) return;
    var arr = kind === 'internal' ? item._deadLinks.internal : item._deadLinks.external;
    for (var j = arr.length - 1; j >= 0; j--) {
      if (arr[j].target === target) { arr.splice(j, 1); break; }
    }
    var hasInternal = item._deadLinks.internal.length > 0;
    var hasExternal = item._deadLinks.external.length > 0;
    if (!hasInternal && !hasExternal) {
      delete item._deadLinks;
      _removeNavWarningReason(item, 'Internal dead links found');
      _removeNavWarningReason(item, 'External dead links found');
    } else {
      if (!hasInternal) _removeNavWarningReason(item, 'Internal dead links found');
      if (!hasExternal) _removeNavWarningReason(item, 'External dead links found');
    }
    _commitNavSnapshot();
  }

  function _removeDeadLinkCaution(pagePath) {
    var item = _findNavItemByPath(pagePath);
    if (!item) return;
    _removeNavWarningReason(item, 'Internal dead links found');
    _removeNavWarningReason(item, 'External dead links found');
  }

  function _removeCautionReason(pagePath, reason) {
    var item = _findNavItemByPath(pagePath);
    if (item) _removeNavWarningReason(item, reason);
  }

  function _stripDeadLinkCautionReasons(paths) {
    for (var i = 0; i < paths.length; i++) {
      var item = _findNavItemByPath(paths[i]);
      if (!item) continue;
      _removeNavWarningReason(item, 'Internal dead links found');
      _removeNavWarningReason(item, 'External dead links found');
    }
  }

  function _clearUnreferencedAssetWarnings() {
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i].type === 'asset') {
          _removeNavWarningReason(items[i], 'Unreferenced asset');
        }
        if (items[i].children) walk(items[i].children);
      }
    })(typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
  }


  // ======================================================================
  // DEAD LINK FINDER — Click to scroll and select
  // ======================================================================
  function _scrollToDeadLink(target, text) {
    if (!wysiwygEditor) return;
    var mainArea = _focusOverlay ? _focusOverlay.querySelector('.live-wysiwyg-focus-main') : null;

    if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
      var ta = wysiwygEditor.markdownArea;
      var val = ta.value;
      var escaped = target.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      var patterns = [
        new RegExp('\\[([^\\]]*)\\]\\(' + escaped + '[^)]*\\)'),
        new RegExp('!\\[([^\\]]*)\\]\\(' + escaped + '[^)]*\\)'),
        new RegExp('<img[^>]+src=["\']' + escaped + '["\']'),
        new RegExp('^\\[[^\\]]+\\]:\\s+' + escaped, 'm')
      ];
      for (var p = 0; p < patterns.length; p++) {
        var match = patterns[p].exec(val);
        if (match) {
          ta.focus();
          ta.setSelectionRange(match.index, match.index + match[0].length);
          var sc = wysiwygEditor.markdownEditorContainer;
          if (sc) {
            var lineHeight = parseInt(window.getComputedStyle(ta).lineHeight, 10) || 20;
            var linesAbove = val.substring(0, match.index).split('\n').length - 1;
            var scrollTarget = Math.max(0, linesAbove * lineHeight - sc.clientHeight * 0.15);
            _smoothScrollTo(sc, scrollTarget, 350);
          }
          return;
        }
      }
    } else if (wysiwygEditor.editableArea) {
      var anchors = wysiwygEditor.editableArea.querySelectorAll('a[href], img[src]');
      for (var i = 0; i < anchors.length; i++) {
        var el = anchors[i];
        var href = el.getAttribute('href') || el.getAttribute('src') || '';
        var hrefPath = href.split('#')[0].split('?')[0];
        if (hrefPath === target) {
          if (mainArea) {
            var rect = el.getBoundingClientRect();
            var mainRect = mainArea.getBoundingClientRect();
            var scrollPos = Math.max(0, mainArea.scrollTop + (rect.top - mainRect.top) - mainArea.clientHeight * 0.15);
            _smoothScrollTo(mainArea, scrollPos, 350);
          }
          var sel = window.getSelection();
          var range = document.createRange();
          range.selectNode(el);
          sel.removeAllRanges();
          sel.addRange(range);
          return;
        }
      }
    }
  }

  // ======================================================================
  // DEAD LINK FINDER — Panel lifecycle
  // ======================================================================
  function _checkDeadLinksForCurrentPage() {
    var currentPath = _getCurrentSrcPath();
    if (!currentPath) return;
    var item = _findNavItemByPath(currentPath);
    if (!item || !item._deadLinks || (!item._deadLinks.internal.length && !item._deadLinks.external.length)) {
      _hideDeadLinkPanel();
      return;
    }
    _ensureTocUncollapsed();
    var tocEl = document.querySelector('.live-wysiwyg-focus-toc');
    if (tocEl) _showDeadLinkPanel(tocEl, item);
  }

  // ======================================================================
  // ======================================================================
  // Focus Mode Settings Dropdown
  // ======================================================================
  function _createSettingsDropdown(gearBtn) {
    var existing = document.querySelector('.live-wysiwyg-focus-settings-dropdown');
    if (existing) { existing.parentNode.removeChild(existing); return; }

    var dropdown = document.createElement('div');
    dropdown.className = 'live-wysiwyg-focus-settings-dropdown';

    var title = document.createElement('div');
    title.className = 'live-wysiwyg-focus-settings-title';
    title.textContent = 'Settings';
    dropdown.appendChild(title);

    function addCheckbox(label, settingKey) {
      var lbl = document.createElement('label');
      var cb = document.createElement('input');
      cb.type = 'checkbox';
      cb.className = 'live-wysiwyg-focus-settings-cb';
      cb.checked = _getSetting(settingKey) === '1';
      cb.addEventListener('change', function () {
        _setSetting(settingKey, cb.checked ? '1' : '0');
      });
      lbl.appendChild(cb);
      lbl.appendChild(document.createTextNode(label));
      dropdown.appendChild(lbl);
      return cb;
    }

    addCheckbox('Auto-launch editor on page load', 'live_wysiwyg_autolaunch');
    addCheckbox('Focus Mode by default', 'live_wysiwyg_autofocus');
    addCheckbox('Remain in Focus Mode on Save', 'live_wysiwyg_focus_remain');

    var rect = gearBtn.getBoundingClientRect();
    dropdown.style.position = 'fixed';
    dropdown.style.top = (rect.bottom + 2) + 'px';
    dropdown.style.left = rect.left + 'px';
    document.body.appendChild(dropdown);

    var ddRect = dropdown.getBoundingClientRect();
    if (ddRect.right > window.innerWidth - 8) {
      dropdown.style.left = Math.max(4, window.innerWidth - ddRect.width - 8) + 'px';
    }

    function _dismissSettingsDd() {
      if (dropdown.parentNode) dropdown.parentNode.removeChild(dropdown);
      document.removeEventListener('click', closeHandler, true);
    }
    var firstCb = dropdown.querySelector('.live-wysiwyg-focus-settings-cb');
    _attachDialogKeyboard(dropdown, {
      category: 'settings',
      onDismiss: function () { _dismissSettingsDd(); },
      autoFocus: firstCb
    });

    var closeHandler = function (e) {
      if (!dropdown.contains(e.target) && e.target !== gearBtn) {
        _dismissSettingsDd();
      }
    };
    setTimeout(function () { document.addEventListener('click', closeHandler, true); }, 0);
  }

  // NAV MENU - WYSIWYG Page Management Submenu
  // ======================================================================
  function _createPageSubmenu(contentBtn) {
    var existing = document.querySelector('.live-wysiwyg-page-submenu');
    if (existing) { existing.parentNode.removeChild(existing); return null; }

    var submenu = document.createElement('div');
    submenu.className = 'live-wysiwyg-page-submenu';

    function _closeSubmenu() {
      if (submenu.parentNode) submenu.parentNode.removeChild(submenu);
      var arrow = contentBtn.querySelector('.live-wysiwyg-page-submenu-arrow');
      if (arrow) arrow.classList.remove('live-wysiwyg-page-submenu-arrow--open');
    }

    var renameBtn = document.createElement('button');
    renameBtn.textContent = 'Rename Page';
    renameBtn.addEventListener('click', function () {
      _closeSubmenu();
      _showRenameDialog();
    });
    submenu.appendChild(renameBtn);

    var newPageBtn = document.createElement('button');
    newPageBtn.textContent = 'New Page';
    newPageBtn.addEventListener('click', function () {
      _closeSubmenu();
      _showNewPageDialog();
    });
    submenu.appendChild(newPageBtn);

    var deleteBtn = document.createElement('button');
    deleteBtn.textContent = 'Delete Current Document';
    deleteBtn.addEventListener('click', function () {
      _closeSubmenu();
      _deleteCurrentDocument();
    });
    submenu.appendChild(deleteBtn);

    var normalizeBtn = document.createElement('button');
    normalizeBtn.textContent = 'Normalize All Nav Weights';
    normalizeBtn.addEventListener('click', function () {
      _closeSubmenu();
      _normalizeAllNavWeights();
    });
    submenu.appendChild(normalizeBtn);

    var findDeadLinksBtn = document.createElement('button');
    findDeadLinksBtn.textContent = 'Find Dead Links';
    findDeadLinksBtn.addEventListener('click', function () {
      _closeSubmenu();
      _showNavDialog('Scan for dead links:', [
        { text: 'All', value: 'all' },
        { text: 'Internal', value: 'internal' },
        { text: 'External', value: 'external' },
        { text: 'Cancel', value: 'cancel' }
      ]).then(function (mode) {
        if (mode && mode !== 'cancel') _scanDeadLinks(mode);
      });
    });
    submenu.appendChild(findDeadLinksBtn);

    var firstItem = submenu.querySelector('button');
    _attachDialogKeyboard(submenu, {
      category: 'settings',
      onDismiss: function () { _closeSubmenu(); document.removeEventListener('click', closeHandler, true); },
      autoFocus: firstItem
    });

    var rect = contentBtn.getBoundingClientRect();
    submenu.style.position = 'fixed';
    submenu.style.top = (rect.bottom + 2) + 'px';
    submenu.style.left = rect.left + 'px';
    document.body.appendChild(submenu);

    var closeHandler = function (e) {
      if (!submenu.contains(e.target) && e.target !== contentBtn) {
        _closeSubmenu();
        document.removeEventListener('click', closeHandler, true);
      }
    };
    setTimeout(function () { document.addEventListener('click', closeHandler, true); }, 0);
    return submenu;
  }

  function _showRenameDialog() {
    var currentSrcPath = _getCurrentSrcPath();
    var currentFilename = currentSrcPath.split('/').pop().replace('.md', '');
    var currentTitle = document.title ? document.title.split(' - ')[0].trim() : currentFilename;

    var dialogOverlay = document.createElement('div');
    dialogOverlay.className = 'live-wysiwyg-nav-dialog';
    var content = document.createElement('div');
    content.className = 'live-wysiwyg-nav-dialog-content';
    content.innerHTML = '<p>Rename this page:</p>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline"><span>File name</span>' +
      '<input type="text" class="live-wysiwyg-rename-filename" value="' + currentFilename.replace(/"/g, '&quot;') + '"></div>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline"><span>Title</span>' +
      '<input type="text" class="live-wysiwyg-rename-title" value="' + currentTitle.replace(/"/g, '&quot;') + '"></div>';
    var actions = document.createElement('div');
    actions.className = 'live-wysiwyg-nav-dialog-actions';
    var cancelBtn = document.createElement('button');
    cancelBtn.textContent = 'Cancel';
    var confirmBtn = document.createElement('button');
    confirmBtn.className = 'live-wysiwyg-nav-dialog-primary';
    confirmBtn.textContent = 'Rename';
    actions.appendChild(cancelBtn);
    actions.appendChild(confirmBtn);
    content.appendChild(actions);
    dialogOverlay.appendChild(content);
    document.body.appendChild(dialogOverlay);
    _attachContainerExpandBehavior(content, { prop: 'maxWidth' });

    var filenameInput = content.querySelector('.live-wysiwyg-rename-filename');
    var titleInput = content.querySelector('.live-wysiwyg-rename-title');

    filenameInput.tabIndex = 1;
    titleInput.tabIndex = 2;
    confirmBtn.tabIndex = 3;
    cancelBtn.tabIndex = 4;

    var dirty = false;
    function markDirty() { dirty = true; }

    filenameInput.addEventListener('input', function () {
      filenameInput.value = filenameInput.value.replace(/[^a-z0-9-]/g, '');
      markDirty();
    });
    titleInput.addEventListener('input', markDirty);

    _attachDialogKeyboard(dialogOverlay, {
      category: 'form',
      isDirty: function () { return dirty; },
      onConfirm: function () { confirmBtn.click(); },
      onDismiss: function () { if (dialogOverlay.parentNode) dialogOverlay.parentNode.removeChild(dialogOverlay); },
      autoFocus: function () { filenameInput.focus(); filenameInput.select(); }
    });

    cancelBtn.addEventListener('click', function () { dialogOverlay.parentNode.removeChild(dialogOverlay); });
    confirmBtn.addEventListener('click', function () {
      var newFilename = filenameInput.value.trim();
      var newTitle = content.querySelector('.live-wysiwyg-rename-title').value.trim();
      if (!newFilename) { filenameInput.focus(); return; }
      dialogOverlay.parentNode.removeChild(dialogOverlay);

      if (!_navEditMode) _enterNavEditMode();
      var dir = _getDir(currentSrcPath);
      var existingPaths = (typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [])
        .filter(function (p) { return _getDir(p) === dir && p !== currentSrcPath; });
      var baseName = newFilename + '.md';
      var resolvedName = _resolveFilenameConflict(baseName, existingPaths, _batchClaimedPaths);
      var newPath = (dir ? dir + '/' : '') + resolvedName;
      if (_batchClaimedPaths) _batchClaimedPaths.add(newPath);
      _navFocusTarget = newPath;

      var navItem = _findNavItemByPath(currentSrcPath);
      if (navItem) {
        navItem.src_path = newPath;
        navItem._renamed = true;
        if (newTitle) navItem.title = newTitle;
      }
      _commitNavSnapshot();
    });
  }

  function _showNewPageDialog(optionalFolderDir) {
    var currentSrcPath = _getCurrentSrcPath();
    var currentDir = optionalFolderDir != null ? optionalFolderDir : _getDir(currentSrcPath);

    var dialogOverlay = document.createElement('div');
    dialogOverlay.className = 'live-wysiwyg-nav-dialog';
    var content = document.createElement('div');
    content.className = 'live-wysiwyg-nav-dialog-content';
    content.innerHTML = '<p>Create a new page:</p>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline"><span>File name</span>' +
      '<input type="text" class="live-wysiwyg-new-filename" placeholder="new-page"></div>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline"><span>Title</span>' +
      '<input type="text" class="live-wysiwyg-new-title" placeholder="New Page"></div>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline"><span>Weight</span>' +
      '<input type="number" class="live-wysiwyg-new-weight" placeholder="optional"></div>' +
      '<div class="live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline"><span>Content (optional)</span>' +
      '<input type="text" class="live-wysiwyg-new-content" placeholder="Short description or TODO"></div>';
    var actions = document.createElement('div');
    actions.className = 'live-wysiwyg-nav-dialog-actions';
    var cancelBtn = document.createElement('button');
    cancelBtn.textContent = 'Cancel';
    var confirmBtn = document.createElement('button');
    confirmBtn.className = 'live-wysiwyg-nav-dialog-primary';
    confirmBtn.textContent = 'Create';
    actions.appendChild(cancelBtn);
    actions.appendChild(confirmBtn);
    content.appendChild(actions);
    dialogOverlay.appendChild(content);
    document.body.appendChild(dialogOverlay);
    _attachContainerExpandBehavior(content, { prop: 'maxWidth' });

    var filenameInput = content.querySelector('.live-wysiwyg-new-filename');
    var newTitleInput = content.querySelector('.live-wysiwyg-new-title');
    var newWeightInput = content.querySelector('.live-wysiwyg-new-weight');
    var newContentInput = content.querySelector('.live-wysiwyg-new-content');

    filenameInput.tabIndex = 1;
    newTitleInput.tabIndex = 2;
    newWeightInput.tabIndex = 3;
    newContentInput.tabIndex = 4;
    confirmBtn.tabIndex = 5;
    cancelBtn.tabIndex = 6;

    var dirty = false;
    function markDirty() { dirty = true; }

    var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    var parentSection = currentDir ? _findSectionByDir(navItems, currentDir) : null;
    var siblingChildren = parentSection && parentSection.children ? parentSection.children : (currentDir ? [] : navItems);
    var maxWeight = -Infinity;
    for (var wi = 0; wi < siblingChildren.length; wi++) {
      var sw = _getItemWeight(siblingChildren[wi]);
      if (sw != null && sw > maxWeight) maxWeight = sw;
    }
    if (maxWeight > -Infinity) {
      newWeightInput.value = maxWeight + 100;
      dirty = true;
    } else {
      var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
      var defW = nwCfg.frontmatter_defaults && nwCfg.frontmatter_defaults.weight !== undefined ? nwCfg.frontmatter_defaults.weight : 100;
      newWeightInput.value = defW;
      dirty = true;
    }

    filenameInput.addEventListener('input', function () {
      filenameInput.value = filenameInput.value.replace(/[^a-z0-9-]/g, '');
      markDirty();
    });
    newTitleInput.addEventListener('input', markDirty);
    newWeightInput.addEventListener('input', markDirty);
    newContentInput.addEventListener('input', markDirty);

    _attachDialogKeyboard(dialogOverlay, {
      category: 'form',
      isDirty: function () { return dirty; },
      onConfirm: function () { confirmBtn.click(); },
      onDismiss: function () { if (dialogOverlay.parentNode) dialogOverlay.parentNode.removeChild(dialogOverlay); },
      autoFocus: filenameInput
    });

    cancelBtn.addEventListener('click', function () { dialogOverlay.parentNode.removeChild(dialogOverlay); });
    confirmBtn.addEventListener('click', function () {
      var filename = filenameInput.value.trim();
      var title = content.querySelector('.live-wysiwyg-new-title').value.trim();
      var weightInput = content.querySelector('.live-wysiwyg-new-weight');
      var weightVal = weightInput && weightInput.value.trim();
      var bodyContent = content.querySelector('.live-wysiwyg-new-content').value.trim();
      if (!filename) { filenameInput.focus(); return; }
      if (!title) title = filename;
      dialogOverlay.parentNode.removeChild(dialogOverlay);

      _enterNavEditModeAsync().then(function (ready) {
      if (!ready) return;

      var existingPaths = (typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [])
        .filter(function (p) { return _getDir(p) === currentDir; });
      var baseName = filename + '.md';
      var resolvedName = _resolveFilenameConflict(baseName, existingPaths, _batchClaimedPaths);
      var newPath = (currentDir ? currentDir + '/' : '') + resolvedName;
      if (_batchClaimedPaths) _batchClaimedPaths.add(newPath);
      var fmLines = ['title: ' + _fmSerialize(title)];
      if (weightVal !== '') {
        var w = parseInt(weightVal, 10);
        if (!isNaN(w)) fmLines.push('weight: ' + w);
      }
      var pageContent = '---\n' + fmLines.join('\n') + '\n---\n' + (bodyContent ? bodyContent + '\n' : '');
      _navFocusTarget = newPath;

      var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
      var syntheticPage = {
        type: 'page', title: title, src_path: newPath,
        _new: true, _uid: _generateUid(),
        setContent: pageContent
      };
      if (currentDir) {
        var parentSection = _findSectionByDir(navItems, currentDir);
        if (parentSection && parentSection.children) {
          parentSection.children.push(syntheticPage);
        } else {
          navItems.push(syntheticPage);
        }
      } else {
        navItems.push(syntheticPage);
      }
      _commitNavSnapshot();
      });
    });
  }

  function _deleteCurrentDocument() {
    var currentSrcPath = _getCurrentSrcPath();
    if (!currentSrcPath) return;
    _enterNavEditModeAsync().then(function (ready) {
    if (!ready) return;

    _navBatchQueue.push({
      type: 'delete-page',
      item: { src_path: currentSrcPath },
      path: currentSrcPath
    });

    var navItems = typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : [];
    _removeNavItemByPath(navItems, currentSrcPath);

    _commitNavSnapshot();
    });
  }

  function _removeNavItemByPath(items, path) {
    for (var i = items.length - 1; i >= 0; i--) {
      if (_getItemSrcPath(items[i]) === path) { items.splice(i, 1); return true; }
      if (items[i].children && _removeNavItemByPath(items[i].children, path)) return true;
    }
    return false;
  }

  function _normalizeAllNavWeights() {
    _enterNavEditModeAsync().then(function (ready) {
      if (!ready) return;
      _applyNormalizeWeightsToNavData(liveWysiwygNavData);
      _adjustDefaultPageWeightSilent();
      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge',
        text: 'Normalize all weights'
      });
      _commitNavSnapshot();
    });
  }

  var _themeColorsDetected = false;
  function _detectThemeColors() {
    var colors = {};
    var cs = getComputedStyle(document.documentElement);

    function _cssVar(name) {
      var v = cs.getPropertyValue(name);
      return v ? v.trim() : '';
    }
    function _luminance(r, g, b) {
      var a = [r, g, b].map(function (v) {
        v /= 255;
        return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
      });
      return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
    }
    function _parseRgb(str) {
      if (!str) return null;
      var m = str.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
      return m ? { r: +m[1], g: +m[2], b: +m[3] } : null;
    }
    function _isLight(rgb) {
      return rgb && _luminance(rgb.r, rgb.g, rgb.b) > 0.4;
    }
    function _darken(rgb, factor) {
      var f = 1 - (factor || 0.15);
      return 'rgb(' + Math.round(rgb.r * f) + ',' + Math.round(rgb.g * f) + ',' + Math.round(rgb.b * f) + ')';
    }
    function _lighten(rgb, factor) {
      var f = factor || 0.15;
      return 'rgb(' +
        Math.round(rgb.r + (255 - rgb.r) * f) + ',' +
        Math.round(rgb.g + (255 - rgb.g) * f) + ',' +
        Math.round(rgb.b + (255 - rgb.b) * f) + ')';
    }
    function _alpha(rgb, a) {
      return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + a + ')';
    }

    var hasMdVars = !!_cssVar('--md-primary-fg-color');
    if (hasMdVars) {
      if (!_themeColorsDetected) {
        _themeColorsDetected = true;
        if (!_cssVar('--md-footer-bg-color')) {
          var primary = _parseRgb(_cssVar('--md-primary-fg-color'));
          if (primary) {
            var root = document.documentElement;
            root.style.setProperty('--md-footer-bg-color', _darken(primary, 0.1));
          }
        }
        if (!_cssVar('--md-code-font-family')) {
          document.documentElement.style.setProperty('--md-code-font-family',
            getComputedStyle(document.body).fontFamily || 'monospace');
        }
      }
      return colors;
    }

    var root = document.documentElement;
    var navbar = document.body.children[0];
    if (!navbar || navbar.nodeType !== 1) return colors;
    var navCs = getComputedStyle(navbar);
    var navBg = navCs.backgroundColor;
    var navFg = navCs.color;
    var navBgRgb = _parseRgb(navBg);
    var navFgRgb = _parseRgb(navFg);

    if (navBg && navBgRgb) {
      colors['--md-primary-fg-color'] = navBg;
      colors['--md-primary-fg-color--dark'] = _darken(navBgRgb, 0.15);
      colors['--md-footer-bg-color'] = _darken(navBgRgb, 0.1);
    }
    if (navFg && navFgRgb) {
      colors['--md-primary-bg-color'] = navFg;
    }

    var bodyCs = getComputedStyle(document.body);
    var bodyBg = bodyCs.backgroundColor;
    var bodyFg = bodyCs.color;
    var bodyBgRgb = _parseRgb(bodyBg);
    var bodyFgRgb = _parseRgb(bodyFg);

    if (bodyBg && bodyBgRgb) {
      colors['--md-default-bg-color'] = bodyBg;
      colors['--md-default-bg-color--light'] = _isLight(bodyBgRgb)
        ? _darken(bodyBgRgb, 0.04) : _lighten(bodyBgRgb, 0.06);
      colors['--md-default-bg-color--lighter'] = _isLight(bodyBgRgb)
        ? _darken(bodyBgRgb, 0.07) : _lighten(bodyBgRgb, 0.1);
    }
    if (bodyFg && bodyFgRgb) {
      colors['--md-default-fg-color'] = bodyFg;
      colors['--md-default-fg-color--light'] = _alpha(bodyFgRgb, 0.54);
      colors['--md-default-fg-color--lighter'] = _alpha(bodyFgRgb, 0.32);
      colors['--md-default-fg-color--lightest'] = _alpha(bodyFgRgb, 0.12);
    }

    var link = document.querySelector('a[href]');
    if (link) {
      var linkColor = getComputedStyle(link).color;
      if (linkColor) {
        colors['--md-accent-fg-color'] = linkColor;
        colors['--md-typeset-a-color'] = linkColor;
      }
    }

    colors['--md-text-font-family'] = bodyCs.fontFamily || 'inherit';
    colors['--md-code-font-family'] = bodyCs.fontFamily || 'monospace';

    if (!_themeColorsDetected) {
      _themeColorsDetected = true;
      for (var v in colors) {
        if (colors.hasOwnProperty(v)) {
          root.style.setProperty(v, colors[v]);
        }
      }
    }
    return colors;
  }

  function _ensureNavUncollapsed() {
    if (!_focusOverlay) return;
    if (_focusOverlay.classList.contains('live-wysiwyg-focus-nav-collapsed')) {
      _focusOverlay.classList.remove('live-wysiwyg-focus-nav-collapsed');
      _setSetting('live_wysiwyg_focus_nav', '1');
    }
  }

  function _ensureTocUncollapsed() {
    if (!_focusOverlay) return;
    if (_focusOverlay.classList.contains('live-wysiwyg-focus-toc-collapsed')) {
      _focusOverlay.classList.remove('live-wysiwyg-focus-toc-collapsed');
      _setSetting('live_wysiwyg_focus_toc', '1');
    }
  }

  function _updateToolbarHeight(overlayEl, drawerEl) {
    if (!overlayEl || !drawerEl) return;
    function measure() { overlayEl.style.setProperty('--_toolbar-h', drawerEl.scrollHeight + 'px'); }
    drawerEl.addEventListener('transitionend', function onEnd(e) {
      if (e.target !== drawerEl) return;
      drawerEl.removeEventListener('transitionend', onEnd);
      measure();
    });
    measure();
  }

  function _getFocusModeCSS() {
    return '' +
      ':root{--live-wysiwyg-caution:#d9534f;--live-wysiwyg-caution-hover:#c9302c;}' +
      '[data-md-color-scheme="slate"]{--live-wysiwyg-caution:#f0ad4e;--live-wysiwyg-caution-hover:#ec971f;}' +
      '.live-wysiwyg-focus-overlay{' +
        'position:fixed;inset:0;z-index:99990;' +
        'display:flex;flex-direction:column;' +
        'background-color:var(--md-default-bg-color,#fff);' +
        'color:var(--md-default-fg-color,#333);' +
        'font-family:var(--md-text-font-family,inherit);' +
        '--_panel-h:calc(100vh - 2.4rem);' +
      '}' +
      '.live-wysiwyg-focus-toolbar-open{--_panel-h:calc(100vh - 2.4rem - var(--_toolbar-h,0px));}' +

      '.live-wysiwyg-focus-header{' +
        'display:flex;align-items:center;' +
        'background-color:var(--md-primary-fg-color,#4051b5);' +
        'color:var(--md-primary-bg-color,#fff);' +
        'box-shadow:0 0 .2rem #0000001a,0 .2rem .4rem #0003;' +
        'position:relative;flex-shrink:0;z-index:4;' +
        'height:2.4rem;padding:0 .4rem;' +
      '}' +

      '.live-wysiwyg-focus-header-left{' +
        'display:flex;align-items:center;gap:4px;flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-focus-drawer-toggle{' +
        'background:none;border:none;cursor:pointer;padding:.4rem;' +
        'color:var(--md-primary-bg-color,#fff);' +
        'display:flex;align-items:center;opacity:.7;transition:opacity .25s;' +
      '}' +
      '.live-wysiwyg-focus-drawer-toggle:hover{opacity:1;}' +
      '.live-wysiwyg-focus-drawer-toggle svg{width:1.2rem;height:1.2rem;}' +

      '.live-wysiwyg-focus-nav-toggle{' +
        'background:none;border:none;cursor:pointer;padding:.4rem;' +
        'color:var(--md-primary-bg-color,#fff);' +
        'display:flex;align-items:center;opacity:.7;transition:opacity .25s;' +
      '}' +
      '.live-wysiwyg-focus-nav-toggle:hover{opacity:1;}' +
      '.live-wysiwyg-focus-nav-toggle svg{width:1.2rem;height:1.2rem;transform:rotate(90deg);}' +

      '.live-wysiwyg-focus-toc-toggle{' +
        'background:none;border:none;cursor:pointer;padding:.4rem;' +
        'color:var(--md-primary-bg-color,#fff);' +
        'display:flex;align-items:center;opacity:.7;transition:opacity .25s;' +
      '}' +
      '.live-wysiwyg-focus-toc-toggle:hover{opacity:1;}' +
      '.live-wysiwyg-focus-toc-toggle svg{width:1.2rem;height:1.2rem;transform:rotate(90deg);}' +

      '.live-wysiwyg-focus-header-title{' +
        'flex-grow:1;font-size:.9rem;height:2.4rem;line-height:2.4rem;' +
        'margin-left:.6rem;margin-right:.4rem;' +
        'overflow:hidden;position:relative;' +
      '}' +
      '.live-wysiwyg-focus-header-ellipsis{' +
        'height:100%;position:relative;width:100%;' +
      '}' +
      '.live-wysiwyg-focus-header-topic{' +
        'display:flex;max-width:100%;position:absolute;' +
        'transition:transform .4s cubic-bezier(.1,.7,.1,1),opacity .15s;' +
        'white-space:nowrap;' +
      '}' +
      '.live-wysiwyg-focus-header-topic span{' +
        'overflow:hidden;text-overflow:ellipsis;' +
      '}' +
      '.live-wysiwyg-focus-header-topic:first-child{font-weight:700;}' +
      '.live-wysiwyg-focus-header-topic+.live-wysiwyg-focus-header-topic{' +
        'opacity:0;pointer-events:none;' +
        'transform:translateX(1.25rem);' +
        'transition:transform .4s cubic-bezier(1,.7,.1,.1),opacity .15s;' +
        'z-index:-1;' +
      '}' +
      '.live-wysiwyg-focus-header-title--active .live-wysiwyg-focus-header-topic{' +
        'opacity:0;pointer-events:none;' +
        'transform:translateX(-1.25rem);' +
        'transition:transform .4s cubic-bezier(1,.7,.1,.1),opacity .15s;' +
        'z-index:-1;' +
      '}' +
      '.live-wysiwyg-focus-header-title--active .live-wysiwyg-focus-header-topic+.live-wysiwyg-focus-header-topic{' +
        'opacity:1;pointer-events:auto;' +
        'transform:translateX(0);' +
        'transition:transform .4s cubic-bezier(.1,.7,.1,1),opacity .15s;' +
        'z-index:0;' +
      '}' +

      '.live-wysiwyg-focus-close{' +
        'background:none;border:none;cursor:pointer;padding:.4rem;' +
        'color:var(--md-primary-bg-color,#fff);opacity:.7;' +
        'font-size:1.1rem;line-height:1;transition:opacity .25s;flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-focus-close:hover{opacity:1;}' +

      '.live-wysiwyg-focus-palette{' +
        'background:none;border:none;cursor:pointer;padding:.4rem;' +
        'color:var(--md-primary-bg-color,#fff);opacity:.7;' +
        'font-size:1.1rem;line-height:1;transition:opacity .25s;flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-focus-palette:hover{opacity:1;}' +
      '.live-wysiwyg-focus-palette svg{width:1.2rem;height:1.2rem;fill:currentColor;}' +

      '.live-wysiwyg-focus-toolbar-drawer{' +
        'max-height:0;overflow:hidden;' +
        'transition:max-height .25s ease-in-out;' +
        'background-color:var(--md-default-bg-color--light,#f7f7f7);' +
        'border-bottom:1px solid transparent;flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-focus-toolbar-open .live-wysiwyg-focus-toolbar-drawer{' +
        'max-height:260px;' +
        'border-bottom-color:var(--md-default-fg-color--lightest,#ddd);' +
      '}' +
      '.live-wysiwyg-focus-drawer-controls{' +
        'display:flex;align-items:center;justify-content:center;gap:8px;padding:8px 16px;flex-wrap:wrap;' +
      '}' +
      '.live-wysiwyg-focus-mode-toggle{' +
        'display:inline-flex;border-radius:4px;overflow:hidden;' +
        'border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
      '}' +
      '.live-wysiwyg-focus-mode-toggle button{' +
        'border:none;padding:4px 12px;cursor:pointer;font-size:.75rem;' +
        'transition:background-color .15s,color .15s;' +
      '}' +
      '.live-wysiwyg-focus-mode-toggle button.active{' +
        'background-color:var(--md-accent-fg-color,#007bff);color:#fff;' +
      '}' +
      '.live-wysiwyg-focus-mode-toggle button:not(.active){' +
        'background-color:var(--md-default-bg-color--light,#f7f7f7);' +
        'color:var(--md-default-fg-color--light,#555);' +
      '}' +
      '.live-wysiwyg-focus-mode-toggle button:not(.active):hover{' +
        'background-color:var(--md-default-bg-color--lighter,#e9e9e9);' +
      '}' +
      '.live-wysiwyg-focus-save-btn,.live-wysiwyg-focus-discard-btn{' +
        'background-color:var(--md-accent-fg-color,#007bff);color:#fff;' +
        'border:1px solid var(--md-accent-fg-color,#007bff);' +
        'border-radius:4px;padding:4px 14px;cursor:pointer;font-size:.75rem;' +
        'overflow:hidden;max-width:0;opacity:0;padding-left:0;padding-right:0;' +
        'border-width:0;margin:0;white-space:nowrap;' +
        'transition:max-width .3s ease,opacity .25s ease,padding .3s ease,border-width .3s ease,margin .3s ease;' +
      '}' +
      '.live-wysiwyg-focus-save-btn.visible,.live-wysiwyg-focus-discard-btn.visible{' +
        'max-width:120px;opacity:1;padding:4px 14px;border-width:1px;margin:0;' +
      '}' +
      '.live-wysiwyg-focus-save-btn:hover,.live-wysiwyg-focus-discard-btn:hover{' +
        'background-color:var(--md-primary-fg-color--dark,#0056b3);' +
        'border-color:var(--md-primary-fg-color--dark,#0056b3);' +
      '}' +
      '.live-wysiwyg-focus-content-btn{' +
        'background-color:var(--md-default-bg-color,#fff);' +
        'color:var(--md-default-fg-color,#333);' +
        'border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
        'border-radius:4px;padding:4px 14px;cursor:pointer;font-size:.75rem;' +
        'position:relative;' +
      '}' +
      '.live-wysiwyg-focus-content-btn:hover{' +
        'background-color:var(--md-default-bg-color--lighter,#e9e9e9);' +
      '}' +
      '.live-wysiwyg-focus-settings-btn{' +
        'background:none;border:none;cursor:pointer;font-size:1.4rem;padding:2px 6px;' +
        'color:var(--md-accent-fg-color,#7c4dff);line-height:1;position:relative;' +
        'border-radius:4px;transition:background .15s,color .15s;' +
      '}' +
      '.live-wysiwyg-focus-settings-btn:hover{' +
        'color:var(--md-primary-fg-color,#4051b5);background:var(--md-default-bg-color--lighter,#e9e9e9);' +
      '}' +
      '.live-wysiwyg-focus-settings-dropdown{' +
        'position:fixed;z-index:99995;background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);border-radius:6px;' +
        'box-shadow:0 4px 16px rgba(0,0,0,.15);min-width:220px;padding:6px 0;' +
      '}' +
      '.live-wysiwyg-focus-settings-title{' +
        'padding:6px 12px 4px;font-size:.7rem;font-weight:600;letter-spacing:.03em;' +
        'text-transform:uppercase;color:var(--md-accent-fg-color,#7c4dff);' +
        'border-bottom:1px solid var(--md-accent-fg-color--transparent,rgba(124,77,255,.25));margin-bottom:2px;' +
      '}' +
      '.live-wysiwyg-focus-settings-dropdown label{' +
        'display:flex;align-items:center;gap:6px;padding:5px 12px;cursor:pointer;' +
        'font-size:.75rem;color:var(--md-default-fg-color,#333);user-select:none;' +
        'transition:background .1s;' +
      '}' +
      '.live-wysiwyg-focus-settings-dropdown label:hover{' +
        'background:var(--md-accent-fg-color--transparent,#cce5ff);' +
      '}' +
      '.live-wysiwyg-focus-settings-cb{' +
        'appearance:none;-webkit-appearance:none;width:14px;height:14px;' +
        'border:2px solid var(--md-default-fg-color--lighter,#ccc);border-radius:3px;' +
        'cursor:pointer;position:relative;flex-shrink:0;transition:background-color .15s,border-color .15s;' +
      '}' +
      '.live-wysiwyg-focus-settings-cb:checked{' +
        'background-color:var(--md-accent-fg-color,#7c4dff);' +
        'border-color:var(--md-accent-fg-color,#7c4dff);' +
      '}' +
      '.live-wysiwyg-focus-settings-cb:checked::after{' +
        'content:"";position:absolute;left:3px;top:0px;width:4px;height:8px;' +
        'border:solid #fff;border-width:0 2px 2px 0;transform:rotate(45deg);' +
      '}' +
      '.live-wysiwyg-focus-drawer-toolbar-wrap{' +
        'padding:4px 16px 8px;display:flex;justify-content:center;' +
      '}' +
      '.live-wysiwyg-focus-drawer-toolbar-wrap.focus-markdown-mode{' +
        'display:none;' +
      '}' +

      '.live-wysiwyg-focus-main{' +
        'flex:1;overflow-y:auto;' +
      '}' +
      '.live-wysiwyg-focus-grid{' +
        'display:flex;margin-left:auto;margin-right:auto;max-width:61rem;' +
        'margin-top:1.5rem;min-height:calc(var(--_panel-h,calc(100vh - 2.4rem)) - 1.5rem);' +
        '--_nav-extend:clamp(0px,(100vw - 61rem) / 2 - 2em,10rem);' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left{' +
        'width:calc(15.8rem + var(--_nav-extend,0px));flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-focus-content{' +
        'flex-grow:1;min-width:0;' +
        'margin:0 .8rem 1.2rem;padding-top:.6rem;' +
      '}' +
      '.live-wysiwyg-focus-content .md-wysiwyg-editor-wrapper{' +
        'border:none;border-radius:0;' +
        'background-color:var(--md-default-bg-color,#fff);' +
        'box-shadow:none;' +
      '}' +
      '.live-wysiwyg-focus-content .md-editor-content-area{' +
        'height:auto!important;min-height:100%;' +
        'display:flex;flex-direction:column;' +
      '}' +
      '.live-wysiwyg-focus-content .md-editable-area{' +
        'min-height:calc(var(--_panel-h,calc(100vh - 2.4rem)) - 5.1rem);flex-grow:1;' +
      '}' +
      '.live-wysiwyg-focus-content .md-markdown-editor-container{' +
        'height:calc(var(--_panel-h,calc(100vh - 2.4rem)) - 4.6rem)!important;' +
      '}' +
      '.live-wysiwyg-focus-content .md-tabs{display:none;}' +
      '.live-wysiwyg-focus-content .md-toolbar{display:none;}' +

      '.live-wysiwyg-focus-toc{' +
        'width:12.1rem;flex-shrink:0;align-self:flex-start;' +
        'position:sticky;top:0;padding:1.2rem 0;' +
        'font-size:.7rem;overflow-y:auto;max-height:calc(var(--_panel-h,calc(100vh - 2.4rem)) - 1.5rem);' +
        'scrollbar-color:var(--md-default-fg-color--lighter,#ccc) transparent;' +
        'scrollbar-width:thin;' +
        'transition:transform .3s ease-in-out,opacity .3s ease-in-out;' +
      '}' +
      '.live-wysiwyg-focus-toc .md-nav__title{' +
        'font-size:.7rem;font-weight:700;' +
        'color:var(--md-default-fg-color--light,#999);' +
        'padding:.8rem .6rem .4rem;' +
      '}' +
      '.live-wysiwyg-focus-toc .md-nav__list{' +
        'list-style:none;margin:0;padding:0;' +
      '}' +
      '.live-wysiwyg-focus-toc .md-nav__item{padding:0;}' +
      '.live-wysiwyg-focus-toc .md-nav__link{' +
        'display:block;padding:4px .6rem;' +
        'color:var(--md-default-fg-color--light,#999);' +
        'text-decoration:none;cursor:pointer;' +
        'transition:color .15s;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
      '}' +
      '.live-wysiwyg-focus-toc .md-nav__link:hover{' +
        'color:var(--md-accent-fg-color,#007bff);' +
      '}' +
      '.live-wysiwyg-focus-toc .md-nav__link--active{' +
        'color:var(--md-typeset-a-color,#007bff);font-weight:600;' +
      '}' +

      

      '@media screen and (max-width:76.25em){' +
        '.live-wysiwyg-focus-sidebar-left{display:none;}' +
        '.live-wysiwyg-focus-nav-toggle{display:none;}' +
        '.live-wysiwyg-focus-content{margin-left:1.2rem;margin-right:1.2rem;}' +
      '}' +

      '.live-wysiwyg-focus-nav-collapsed .live-wysiwyg-focus-sidebar-left{' +
        'transform:translateX(-100%);opacity:0;pointer-events:none;' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-sidebar-left{' +
        'transition:transform .3s ease-in-out,opacity .3s ease-in-out,width .3s ease-in-out,margin .3s ease-in-out;' +
      '}' +
      '.focus-mode-markdown.live-wysiwyg-focus-nav-collapsed .live-wysiwyg-focus-sidebar-left{' +
        'width:0;margin-left:0;padding:0;' +
      '}' +
      '.live-wysiwyg-focus-toc-collapsed .live-wysiwyg-focus-toc{' +
        'transform:translateX(100%);opacity:0;pointer-events:none;' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-toc{' +
        'transition:transform .3s ease-in-out,opacity .3s ease-in-out,width .3s ease-in-out,margin .3s ease-in-out;' +
      '}' +
      '.focus-mode-markdown.live-wysiwyg-focus-toc-collapsed .live-wysiwyg-focus-toc{' +
        'width:0;margin-right:0;padding:0;' +
      '}' +
      '@media screen and (max-width:60em){' +
        '.live-wysiwyg-focus-toc{display:none;}' +
        '.live-wysiwyg-focus-toc-toggle{display:none;}' +
      '}' +

      // --- Nav menu in left sidebar (matches md-sidebar--primary / md-nav--primary at >=76.25em) ---
      '.live-wysiwyg-focus-sidebar-left{' +
        'display:flex;flex-direction:column;overflow:hidden;max-height:calc(var(--_panel-h,calc(100vh - 2.4rem)) - 1.5rem);' +
        'padding:1.2rem .2rem 0 0;position:sticky;top:0;' +
        'font-size:.7rem;line-height:1.3;' +
        'margin-left:calc(-56px - var(--_nav-extend,0px));background-color:var(--md-default-bg-color,#fff);' +
        'transition:transform .3s ease-in-out,opacity .3s ease-in-out;' +
      '}' +
      '.live-wysiwyg-nav-scroll-wrap{' +
        'flex:1;min-height:0;overflow-y:auto;padding-left:56px;' +
        'scrollbar-gutter:stable;' +
        'scrollbar-color:var(--md-default-fg-color--lighter,#ccc) transparent;' +
        'scrollbar-width:thin;' +
      '}' +
      '.live-wysiwyg-nav-scroll-wrap:hover,' +
      '.live-wysiwyg-nav-scroll-wrap:focus-within{' +
        'scrollbar-color:var(--md-accent-fg-color,#526cfe) transparent;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav--primary{' +
        'font-size:.7rem;line-height:1.3;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__title{' +
        'display:block;padding:.4rem .6rem;font-weight:700;' +
        'color:var(--md-default-fg-color--light,#999);' +
        'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
        'background:var(--md-default-bg-color,#fff);' +
        'box-shadow:0 0 .4rem .4rem var(--md-default-bg-color,#fff);' +
        'position:sticky;top:0;z-index:1;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__title .md-nav__icon{display:none;}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__list{' +
        'list-style:none;margin:0;padding:0 .6rem .4rem;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item{' +
        'padding:0 0 0 56px;margin-left:-56px;position:relative;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__link{' +
        'display:flex;align-items:flex-start;gap:.4rem;' +
        'margin-top:.625em;margin-left:.4rem;margin-right:.4rem;' +
        'color:var(--md-default-fg-color--light,#999);' +
        'text-decoration:none;cursor:pointer;transition:color 125ms;' +
        'scroll-snap-align:start;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__link:hover,' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__link:focus{' +
        'color:var(--md-accent-fg-color,#526cfe);' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__link--active,' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--active>.md-nav__link{' +
        'color:var(--md-typeset-a-color,#4051b5);' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--active>.md-nav__link:hover,' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--active>.md-nav__link:focus{' +
        'color:var(--md-accent-fg-color,#526cfe);' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested>.md-nav{' +
        'display:grid;grid-template-rows:0fr;opacity:0;' +
        'transition:grid-template-rows .25s cubic-bezier(.86,0,.07,1),' +
        'opacity .25s,visibility 0ms .25s;' +
        'visibility:collapse;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested>.md-nav>.md-nav__list{overflow:hidden;}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested>.md-nav[aria-expanded=\"true\"]>.md-nav__list{overflow:visible;}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested>.md-nav[aria-expanded=\"true\"]{' +
        'grid-template-rows:1fr;opacity:1;' +
        'transition:grid-template-rows .25s cubic-bezier(.86,0,.07,1),' +
        'opacity .15s .1s,visibility 0ms;' +
        'visibility:visible;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested>.md-nav .md-nav__title{' +
        'display:none;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__icon{' +
        'flex-shrink:0;border-radius:100%;height:.9rem;width:.9rem;' +
        'margin-left:auto;transition:background-color .25s;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__icon:hover{' +
        'background-color:var(--md-accent-fg-color--transparent,rgba(82,108,254,.1));' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__icon:after{' +
        'background-color:currentcolor;border-radius:100%;content:"";display:inline-block;' +
        'height:100%;width:100%;' +
        '-webkit-mask-image:var(--md-nav-icon--next);mask-image:var(--md-nav-icon--next);' +
        '-webkit-mask-position:center;mask-position:center;' +
        '-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;' +
        '-webkit-mask-size:contain;mask-size:contain;' +
        'transition:transform .25s;vertical-align:-.1rem;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested.md-nav__item--active>.md-nav__link .md-nav__icon:after{' +
        'transform:rotate(90deg);' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .md-nav__link .md-ellipsis{' +
        'position:relative;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
      '}' +
      '.live-wysiwyg-focus-sidebar-left .live-wysiwyg-nav-tip-icon{' +
        'margin-left:4px;cursor:pointer;' +
      '}' +

      // (settings checkboxes now live inside the gear dropdown)

      // --- Link chain indicator + themed link dropdown overrides ---
      '.md-link-chain-indicator{' +
        'background-color:var(--md-accent-fg-color,#7c4dff)!important;' +
        'border-color:var(--md-accent-fg-color,#7c4dff)!important;' +
        'color:#fff!important;' +
        'box-shadow:0 2px 8px rgba(0,0,0,.2);' +
      '}' +
      '.md-link-chain-indicator:hover{' +
        'background-color:var(--md-primary-fg-color,#4051b5)!important;' +
        'border-color:var(--md-primary-fg-color,#4051b5)!important;' +
        'box-shadow:0 2px 12px rgba(0,0,0,.3);' +
      '}' +
      '.md-link-settings-dropdown{' +
        'background:var(--md-default-bg-color,#fff)!important;' +
        'border-color:var(--md-default-fg-color--lightest,#ddd)!important;' +
        'color:var(--md-default-fg-color,#333)!important;' +
        'box-shadow:0 4px 16px rgba(0,0,0,.15)!important;' +
        'min-width:220px;' +
      '}' +
      '.md-link-settings-input{' +
        'background:var(--md-default-bg-color--light,#f7f7f7)!important;' +
        'color:var(--md-default-fg-color,#333)!important;' +
        'border-color:var(--md-default-fg-color--lighter,#ccc)!important;' +
      '}' +
      '.md-link-settings-input:focus{' +
        'border-color:var(--md-accent-fg-color,#7c4dff)!important;' +
      '}' +
      '.md-link-settings-input::placeholder{' +
        'color:var(--md-default-fg-color--lighter,#888)!important;' +
      '}' +
      '.md-link-settings-apply{' +
        'background:var(--md-accent-fg-color,#7c4dff)!important;' +
        'color:#fff!important;border-color:var(--md-accent-fg-color,#7c4dff)!important;' +
      '}' +
      '.md-link-settings-apply:hover{' +
        'background:var(--md-primary-fg-color,#4051b5)!important;' +
        'border-color:var(--md-primary-fg-color,#4051b5)!important;' +
      '}' +
      '.md-link-settings-remove{' +
        'background:none;color:var(--md-default-fg-color--light,#888);' +
        'border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
        'border-radius:3px;padding:4px 12px;cursor:pointer;' +
        'font-family:inherit;font-size:inherit;transition:background .1s,color .1s;' +
      '}' +
      '.md-link-settings-remove:hover{' +
        'background:#d9534f;color:#fff;border-color:#d9534f;' +
      '}' +

      // --- Arrow controls wrapper (arrows + gear grouped on the left) ---
      '.live-wysiwyg-nav-controls-wrapper{' +
        'display:none;position:absolute;left:2px;z-index:2;' +
        'align-items:center;gap:3px;' +
      '}' +
      '.live-wysiwyg-nav-weight-controls{' +
        'display:grid;' +
        'grid-template-columns:12px 12px 12px;grid-template-rows:12px 12px 12px;' +
        'gap:0px;align-items:center;justify-items:center;' +
      '}' +
      '.live-wysiwyg-nav-weight-controls .live-wysiwyg-nav-arrow{' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'border-radius:2px;cursor:pointer;padding:0;font-size:.45rem;line-height:1;' +
        'color:var(--md-default-fg-color--light,#777);transition:background .15s,color .15s;' +
        'width:12px;height:12px;display:flex;align-items:center;justify-content:center;' +
      '}' +
      '.live-wysiwyg-nav-weight-controls .live-wysiwyg-nav-arrow:hover{' +
        'background:var(--md-accent-fg-color,#007bff);color:#fff;border-color:var(--md-accent-fg-color,#007bff);' +
      '}' +
      '.live-wysiwyg-nav-weight-controls .live-wysiwyg-nav-arrow:disabled{opacity:.3;cursor:default;pointer-events:none;}' +
      '.live-wysiwyg-nav-weight-controls .live-wysiwyg-nav-arrow-up{grid-column:2;grid-row:1;}' +
      '.live-wysiwyg-nav-weight-controls .live-wysiwyg-nav-arrow-left{grid-column:1;grid-row:2;}' +
      '.live-wysiwyg-nav-weight-controls .live-wysiwyg-nav-arrow-right{grid-column:3;grid-row:2;}' +
      '.live-wysiwyg-nav-weight-controls .live-wysiwyg-nav-arrow-down{grid-column:2;grid-row:3;}' +
      '.live-wysiwyg-nav-target-dot{' +
        'grid-column:2;grid-row:2;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'border-radius:50%;cursor:pointer;padding:0;' +
        'font-size:.5rem;line-height:1;' +
        'color:var(--md-default-fg-color--light,#777);transition:background .15s,color .15s,border-color .15s;' +
        'width:12px;height:12px;display:none;align-items:center;justify-content:center;' +
      '}' +
      '.live-wysiwyg-nav-edit-mode .live-wysiwyg-nav-target-dot{display:flex;}' +
      '.live-wysiwyg-nav-target-dot:hover{' +
        'background:var(--md-accent-fg-color,#007bff);color:#fff;border-color:var(--md-accent-fg-color,#007bff);' +
      '}' +
      '.live-wysiwyg-nav-settings-gear{' +
        'background:none;border:none;cursor:pointer;padding:1px;' +
        'font-size:.7rem;line-height:1;' +
        'color:var(--md-default-fg-color--light,#777);transition:color .15s;' +
        'align-self:center;' +
      '}' +
      '.live-wysiwyg-nav-settings-gear:hover{' +
        'color:var(--md-accent-fg-color,#007bff);' +
      '}' +
      // Show controls on JS-managed hover (unified for pages and sections)
      '.md-nav__item.live-wysiwyg-nav-hover>.live-wysiwyg-nav-controls-wrapper{display:flex;}' +
      // Focused item: always show its controls (direct child only)
      '.md-nav__item.live-wysiwyg-nav-item--focused>.live-wysiwyg-nav-controls-wrapper{display:flex!important;}' +
      // Selected items in group mode: show controls wrapper for layout consistency
      '.live-wysiwyg-nav-group-active .md-nav__item.live-wysiwyg-nav-item--selected>.live-wysiwyg-nav-controls-wrapper{display:flex!important;}' +

      // --- Nav edit mode visual states ---
      '.live-wysiwyg-nav-item--renamed,.live-wysiwyg-nav-item--new{background:rgba(92,184,92,.15);}' +
      '.live-wysiwyg-nav-item--focus-target{' +
        'box-shadow:inset 0 0 0 2px rgba(255,255,255,.25);' +
      '}' +
      '.live-wysiwyg-nav-item--focus-target.live-wysiwyg-nav-item--renamed,' +
      '.live-wysiwyg-nav-item--focus-target.live-wysiwyg-nav-item--new{' +
        'box-shadow:inset 0 0 0 2px rgba(255,255,255,.35);' +
      '}' +
      '.live-wysiwyg-nav-item--focused{' +
        'outline:2.5px solid var(--md-accent-fg-color,#007bff);outline-offset:-2px;border-radius:2px;z-index:1;position:relative;' +
      '}' +
      '.live-wysiwyg-nav-item--selected{' +
        'outline:2px solid var(--md-accent-fg-color,#007bff);outline-offset:-2px;border-radius:2px;position:relative;' +
      '}' +
      '.live-wysiwyg-nav-item--selected.live-wysiwyg-nav-item--focused{' +
        'outline-width:2.5px;z-index:1;' +
      '}' +
      '.live-wysiwyg-nav-group-active .live-wysiwyg-nav-item--selected .live-wysiwyg-nav-target-dot,' +
      '.live-wysiwyg-nav-group-active .live-wysiwyg-nav-item--selected .live-wysiwyg-nav-settings-gear{' +
        'display:none!important;' +
      '}' +
      '.live-wysiwyg-nav-group-active .live-wysiwyg-nav-item--selected:not(.live-wysiwyg-nav-item--focused) .live-wysiwyg-nav-arrow{' +
        'visibility:hidden;' +
      '}' +

      // --- Nav edit save/discard/undo/redo buttons ---
      '.live-wysiwyg-nav-edit-actions{' +
        'display:flex;flex-wrap:wrap;gap:4px;padding:8px .6rem 8px 56px;' +
        'flex-shrink:0;background:var(--md-default-bg-color,#fff);' +
        'border-top:1px solid var(--md-default-fg-color--lightest,#ddd);z-index:2;' +
        'position:relative;' +
      '}' +
      '.live-wysiwyg-nav-edit-actions button{' +
        'border:1px solid var(--md-default-fg-color--lighter,#ccc);border-radius:3px;' +
        'padding:3px 8px;font-size:.65rem;cursor:pointer;transition:background .15s;' +
      '}' +
      '.live-wysiwyg-nav-save-btn{background:#5cb85c;color:#fff;border-color:#4cae4c!important;}' +
      '.live-wysiwyg-nav-save-btn:hover{background:#4cae4c;}' +
      '.live-wysiwyg-nav-discard-btn{background:#d9534f;color:#fff;border-color:#d43f3a!important;}' +
      '.live-wysiwyg-nav-discard-btn:hover{background:#d43f3a;}' +
      '.live-wysiwyg-nav-undo-btn,.live-wysiwyg-nav-redo-btn{' +
        'background:var(--md-default-bg-color--light,#f7f7f7);' +
        'color:var(--md-default-fg-color--light,#555);' +
      '}' +
      '.live-wysiwyg-nav-undo-btn:hover,.live-wysiwyg-nav-redo-btn:hover{' +
        'background:var(--md-default-bg-color--lighter,#e9e9e9);' +
      '}' +
      '.live-wysiwyg-nav-undo-btn:disabled,.live-wysiwyg-nav-redo-btn:disabled{opacity:.35;cursor:default;}' +
      '.live-wysiwyg-nav-normalize-badge{' +
        'font-size:.6rem;padding:2px 6px;border-radius:8px;' +
        'background:var(--md-accent-fg-color,#007bff);color:#fff;margin-left:auto;' +
      '}' +
      '.live-wysiwyg-nav-review-btn{' +
        'font-size:.65rem;padding:3px 8px;border-radius:8px;border:1px solid var(--md-accent-fg-color,#007bff);' +
        'background:var(--md-accent-fg-color,#007bff);color:#fff;cursor:pointer;white-space:nowrap;' +
      '}' +
      '.live-wysiwyg-nav-review-btn:hover{opacity:.85;}' +
      '.live-wysiwyg-nav-review-popup{' +
        'position:fixed;z-index:999999;' +
        'background:var(--md-default-bg-color,#fff);border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
        'border-radius:8px;padding:10px 12px;box-shadow:0 4px 16px rgba(0,0,0,.18);' +
        'display:flex;flex-direction:column;gap:4px;max-height:240px;overflow-y:auto;' +
        'transform:translateY(12px);opacity:0;' +
        'transition:transform .25s ease-out,opacity .25s ease-out;' +
      '}' +
      '.live-wysiwyg-nav-review-popup-open{' +
        'transform:translateY(0);opacity:1;' +
      '}' +
      '.live-wysiwyg-nav-review-popup .live-wysiwyg-nav-normalize-badge{margin-left:0;}' +
      '.live-wysiwyg-nav-review-empty{font-size:.7rem;opacity:.6;font-style:italic;}' +

      '.live-wysiwyg-nav-pending-deletes{' +
        'display:flex;flex-direction:column;gap:2px;margin-top:6px;padding:6px 8px;' +
        'border-radius:6px;background:rgba(217,83,79,.12);font-size:.65rem;' +
      '}' +
      '.live-wysiwyg-nav-pending-deletes-header{' +
        'font-weight:600;color:rgba(217,83,79,1);margin-bottom:2px;' +
      '}' +
      '.live-wysiwyg-nav-pending-delete-item{' +
        'color:var(--md-default-fg-color,#333);opacity:.85;padding-left:10px;' +
        'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;' +
      '}' +
      '.live-wysiwyg-nav-pending-delete-item::before{content:"\\2022 ";color:rgba(217,83,79,.8);}' +

      // --- Save/Discard confirmation dialog ---
      '.live-wysiwyg-nav-dialog{' +
        'position:fixed;inset:0;z-index:99999;' +
        'background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;' +
      '}' +
      '.live-wysiwyg-nav-dialog-content{' +
        'background:var(--md-default-bg-color,#fff);border-radius:8px;padding:24px 28px;' +
        'max-width:420px;width:90%;box-shadow:0 8px 32px rgba(0,0,0,.25);' +
        'color:var(--md-default-fg-color,#333);font-size:.75rem;' +
      '}' +
      '.live-wysiwyg-nav-dialog-content p{margin:0 0 16px;font-size:.85rem;line-height:1.5;}' +
      '.live-wysiwyg-nav-dialog-actions{display:flex;gap:8px;justify-content:flex-end;}' +
      '.live-wysiwyg-nav-dialog-actions button{' +
        'border:1px solid var(--md-default-fg-color--lighter,#ccc);border-radius:4px;' +
        'padding:6px 16px;font-size:.8rem;cursor:pointer;transition:background .15s;' +
      '}' +
      '.live-wysiwyg-nav-dialog-primary{' +
        'background:var(--md-accent-fg-color,#007bff);color:#fff;' +
        'border-color:var(--md-accent-fg-color,#007bff)!important;' +
      '}' +
      '.live-wysiwyg-nav-dialog-primary:hover{opacity:.85;}' +
      '.live-wysiwyg-nav-dialog-danger{' +
        'background:#d9534f;color:#fff;border-color:#d43f3a!important;' +
      '}' +
      '.live-wysiwyg-nav-dialog-danger:hover{opacity:.85;}' +

      // --- Toast notification (centered, auto-dismiss) ---
      '.live-wysiwyg-toast{' +
        'position:fixed;top:40%;left:50%;transform:translate(-50%,-50%) scale(.95);z-index:100000;' +
        'display:flex;align-items:center;gap:12px;' +
        'background:var(--md-default-bg-color,#fff);color:var(--md-default-fg-color,#333);' +
        'border:2px solid var(--md-primary-fg-color,#4051b5);border-radius:6px;' +
        'padding:10px 16px;font-size:.8rem;line-height:1.4;' +
        'box-shadow:0 4px 16px rgba(0,0,0,.15);' +
        'opacity:0;' +
        'transition:opacity .3s,transform .3s;' +
        'pointer-events:auto;' +
      '}' +
      '.live-wysiwyg-toast--visible{opacity:1;transform:translate(-50%,-50%) scale(1);}' +
      '.live-wysiwyg-toast-close{' +
        'background:none;border:none;cursor:pointer;font-size:1.1rem;line-height:1;' +
        'color:var(--md-default-fg-color--light,#999);padding:0 0 0 4px;' +
      '}' +
      '.live-wysiwyg-toast-close:hover{color:var(--md-default-fg-color,#333);}' +

      // --- Status overlay / progress bar (transparent over content) ---
      '.live-wysiwyg-nav-status{' +
        'position:absolute;inset:0;z-index:50;' +
        'display:flex;flex-direction:column;align-items:center;justify-content:center;' +
        'padding:2rem;gap:12px;' +
        'background:rgba(0,0,0,.12);' +
        'backdrop-filter:blur(1px);-webkit-backdrop-filter:blur(1px);' +
        'transition:opacity .2s ease;' +
      '}' +
      '.live-wysiwyg-nav-status-icon{' +
        'width:24px;height:24px;border:3px solid rgba(255,255,255,.3);' +
        'border-top-color:rgba(255,255,255,.8);border-radius:50%;' +
        'animation:live-wysiwyg-spin 1s linear infinite;' +
      '}' +
      '@keyframes live-wysiwyg-spin{to{transform:rotate(360deg)}}' +
      '.live-wysiwyg-nav-status-text{font-size:.85rem;color:rgba(255,255,255,.85);text-shadow:0 1px 3px rgba(0,0,0,.4);}' +
      '.live-wysiwyg-nav-progress-bar{' +
        'width:100%;max-width:320px;height:6px;border-radius:3px;' +
        'background:rgba(255,255,255,.2);overflow:hidden;' +
      '}' +
      '.live-wysiwyg-nav-progress-fill{' +
        'height:100%;background:rgba(255,255,255,.7);' +
        'transition:width .3s ease;width:0%;border-radius:3px;' +
      '}' +
      '.live-wysiwyg-nav-progress-indeterminate .live-wysiwyg-nav-progress-fill{' +
        'width:30%!important;animation:live-wysiwyg-indeterminate 1.5s ease-in-out infinite;' +
      '}' +
      '@keyframes live-wysiwyg-indeterminate{' +
        '0%{transform:translateX(-100%)}100%{transform:translateX(400%)}' +
      '}' +
      '.live-wysiwyg-nav-status-detail{font-size:.7rem;color:rgba(255,255,255,.65);text-shadow:0 1px 2px rgba(0,0,0,.3);}' +
      '.live-wysiwyg-nav-check-btn{' +
        'margin-top:8px;padding:4px 14px;border:1px solid rgba(255,255,255,.3);' +
        'border-radius:4px;font-size:.7rem;cursor:pointer;' +
        'background:rgba(255,255,255,.15);color:rgba(255,255,255,.85);' +
        'text-shadow:0 1px 2px rgba(0,0,0,.3);transition:opacity .15s;' +
      '}' +
      '.live-wysiwyg-nav-check-btn:hover{background:rgba(255,255,255,.25);}' +
      '.live-wysiwyg-nav-check-btn:disabled{opacity:.35;cursor:default;}' +

      // --- Settings gear dropdown ---
      '.live-wysiwyg-nav-settings-dropdown{' +
        'position:fixed;z-index:99995;background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);border-radius:6px;' +
        'box-shadow:0 4px 16px rgba(0,0,0,.15);padding:12px 14px;min-width:220px;' +
        'max-height:80vh;overflow-y:auto;' +
        'font-size:.75rem;color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-nav-settings-dropdown label,' +
      '.live-wysiwyg-nav-dialog-content label{' +
        'display:flex;align-items:center;gap:6px;padding:4px 0;cursor:pointer;' +
      '}' +
      '.live-wysiwyg-nav-settings-dropdown input[type="text"],' +
      '.live-wysiwyg-nav-settings-dropdown input[type="number"],' +
      '.live-wysiwyg-nav-dialog-content input[type="text"],' +
      '.live-wysiwyg-nav-dialog-content input[type="number"]{' +
        'width:100%;padding:3px 6px;border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
        'border-radius:3px;font-size:.75rem;box-sizing:border-box;' +
        'background:var(--md-default-bg-color,#fff);color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-nav-settings-row{padding:4px 0;display:flex;flex-direction:column;gap:2px;}' +
      '.live-wysiwyg-nav-settings-row span{font-weight:600;font-size:.7rem;}' +
      '.live-wysiwyg-nav-settings-row.live-wysiwyg-nav-settings-inline{' +
        'flex-direction:row;align-items:center;gap:8px;' +
      '}' +
      '.live-wysiwyg-nav-settings-row.live-wysiwyg-nav-settings-inline input[type="text"]{' +
        'flex:1;min-width:0;' +
      '}' +
      '.live-wysiwyg-nav-settings-row.live-wysiwyg-nav-settings-inline input[type="number"]{' +
        'width:80px;flex:0 0 auto;' +
      '}' +
      '.live-wysiwyg-nav-settings-checkbox-group{' +
        'flex-direction:row;flex-wrap:wrap;gap:10px;align-items:center;' +
      '}' +
      '.live-wysiwyg-nav-settings-btn-row{' +
        'display:flex;gap:4px;margin-top:4px;' +
      '}' +
      '.live-wysiwyg-nav-settings-btn-row .live-wysiwyg-nav-settings-normalize-btn{' +
        'flex:1;margin-top:0;' +
      '}' +
      '.live-wysiwyg-nav-settings-divider{' +
        'border:none;border-top:1px solid var(--md-default-fg-color--lightest,#ddd);margin:6px 0;' +
      '}' +
      '.live-wysiwyg-nav-settings-normalize-btn{' +
        'width:100%;padding:5px 10px;margin-top:4px;' +
        'background:var(--md-accent-fg-color,#007bff);color:#fff;border:none;' +
        'border-radius:3px;cursor:pointer;font-size:.7rem;transition:opacity .15s;' +
      '}' +
      '.live-wysiwyg-nav-settings-normalize-btn:hover{opacity:.85;}' +
      '.live-wysiwyg-nav-settings-normalize-btn:disabled{opacity:.4;cursor:default;}' +

      // --- Caution / warning icons ---
      '.live-wysiwyg-nav-empty-folder-caution{cursor:pointer;margin-left:4px;font-size:.75rem;opacity:.8;}' +
      '.live-wysiwyg-nav-empty-folder-caution:hover{opacity:1;color:var(--live-wysiwyg-caution-hover);}' +
      '.live-wysiwyg-nav-collapsed-caution{color:var(--live-wysiwyg-caution);font-size:.7rem;margin-left:2px;flex-shrink:0;}' +
      '.md-nav__item--active>.md-nav__link>.live-wysiwyg-nav-collapsed-caution{display:none;}' +
      '.live-wysiwyg-nav-caution{' +
        'cursor:pointer;color:var(--live-wysiwyg-caution);font-size:.7rem;margin-left:2px;flex-shrink:0;' +
        'transition:color .15s;' +
      '}' +
      '.live-wysiwyg-nav-caution:hover{color:var(--live-wysiwyg-caution-hover);}' +
      '.live-wysiwyg-nav-caution-item{' +
        'outline:1.5px solid var(--live-wysiwyg-caution);outline-offset:-1px;border-radius:3px;' +
      '}' +
      '.live-wysiwyg-nav-warning{' +
        'cursor:pointer;color:var(--live-wysiwyg-caution);font-size:.7rem;margin-left:2px;flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-nav-warning:hover{color:var(--live-wysiwyg-caution-hover);}' +
      '.live-wysiwyg-nav-tip-icon{' +
        'cursor:pointer;color:var(--md-accent-fg-color,#007bff);font-size:.65rem;' +
        'margin-left:4px;flex-shrink:0;opacity:.7;transition:opacity .15s;' +
      '}' +
      '.live-wysiwyg-nav-tip-icon:hover{opacity:1;}' +
      '.live-wysiwyg-nav-info{' +
        'cursor:pointer;color:var(--md-accent-fg-color,#007bff);font-size:.65rem;' +
        'margin-left:2px;flex-shrink:0;opacity:.7;transition:opacity .15s,color .15s;' +
      '}' +
      '.live-wysiwyg-nav-info:hover{opacity:1;color:var(--md-accent-fg-color,#007bff);}' +
      '.live-wysiwyg-nav-caution-item .live-wysiwyg-nav-info{display:none;}' +

      // --- WYSIWYG submenu (Content button dropdown) ---
      '.live-wysiwyg-page-submenu{' +
        'position:absolute;z-index:99995;background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);border-radius:6px;' +
        'box-shadow:0 4px 16px rgba(0,0,0,.15);min-width:200px;padding:4px 0;' +
      '}' +
      '.live-wysiwyg-page-submenu button{' +
        'display:block;width:calc(100% - 8px);margin:1px 4px;text-align:left;padding:5px 10px;' +
        'border:1px solid transparent;border-radius:3px;' +
        'background:none;cursor:pointer;font-size:.75rem;' +
        'color:var(--md-default-fg-color,#333);transition:background .1s,border-color .1s;' +
      '}' +
      '.live-wysiwyg-page-submenu button:hover{' +
        'background:var(--md-accent-fg-color--transparent,#cce5ff);' +
        'border-color:var(--md-accent-fg-color,#007bff);' +
      '}' +
      '.live-wysiwyg-page-submenu-arrow{' +
        'display:inline-block;transition:transform .2s;margin-left:4px;font-size:.6rem;' +
      '}' +
      '.live-wysiwyg-page-submenu-arrow--open{transform:rotate(90deg);}' +

      // --- Popup (reusable for warnings, caution info, etc.) ---
      '.live-wysiwyg-nav-popup{' +
        'position:absolute;z-index:99996;background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);border-radius:6px;' +
        'box-shadow:0 4px 16px rgba(0,0,0,.15);padding:12px 14px;max-width:300px;' +
        'font-size:.75rem;color:var(--md-default-fg-color,#333);line-height:1.5;' +
      '}' +
      '.live-wysiwyg-nav-popup button{' +
        'padding:4px 10px;border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
        'border-radius:3px;font-size:.7rem;cursor:pointer;background:var(--md-default-bg-color,#fff);' +
        'color:var(--md-default-fg-color,#333);transition:background .15s;margin-right:4px;' +
      '}' +
      '.live-wysiwyg-nav-popup button:hover{background:var(--md-default-bg-color--light,#f7f7f7);color:var(--md-default-fg-color,#333);}' +
      '.live-wysiwyg-nav-popup .live-wysiwyg-nav-popup-primary{' +
        'background:var(--md-accent-fg-color,#007bff);color:#fff;' +
        'border-color:var(--md-accent-fg-color,#007bff);' +
      '}' +
      '.live-wysiwyg-nav-popup .live-wysiwyg-nav-popup-primary:hover{opacity:.85;}' +
      '.live-wysiwyg-nav-popup .live-wysiwyg-nav-popup-primary:disabled{opacity:.4;cursor:default;}' +

      // --- Early-inject focus overlay (starts opaque to hide page reload) ---
      '.live-wysiwyg-early-overlay{' +
        'position:fixed;inset:0;z-index:99989;' +
        'background:rgba(0,0,0,1);' +
        'display:flex;align-items:center;justify-content:center;flex-direction:column;gap:12px;' +
        'transition:opacity .4s ease;' +
      '}' +

      // --- Full-screen transition overlay (shown before navigation) ---
      '.live-wysiwyg-nav-transition-overlay{' +
        'position:fixed;inset:0;z-index:99990;' +
        'background:rgba(0,0,0,.18);' +
        'display:flex;align-items:center;justify-content:center;flex-direction:column;gap:12px;' +
        'animation:live-wysiwyg-transition-fade .6s ease;' +
        'transition:background .3s ease,opacity .6s ease-out;' +
      '}' +
      '@keyframes live-wysiwyg-transition-fade{from{opacity:0}to{opacity:1}}' +
      '.live-wysiwyg-nav-transition-spinner{' +
        'width:24px;height:24px;border:3px solid rgba(255,255,255,.3);' +
        'border-top-color:rgba(255,255,255,.8);border-radius:50%;' +
        'animation:live-wysiwyg-spin 1s linear infinite;' +
      '}' +
      '.live-wysiwyg-nav-transition-text{' +
        'font-size:.85rem;color:rgba(255,255,255,.85);' +
        'text-shadow:0 1px 3px rgba(0,0,0,.4);' +
      '}' +

      // --- Dead link panel (overlays the TOC) ---
      '.live-wysiwyg-dead-link-panel{' +
        'position:fixed;z-index:99993;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:2px solid var(--live-wysiwyg-caution);' +
        'border-radius:6px;box-shadow:0 2px 12px rgba(0,0,0,.1);' +
        'display:flex;flex-direction:column;' +
        'font-size:.7rem;overflow:hidden;' +
      '}' +
      '.live-wysiwyg-dead-link-panel-header{' +
        'display:flex;align-items:center;justify-content:space-between;' +
        'padding:.6rem .6rem .4rem;font-weight:700;' +
        'color:var(--md-default-fg-color,#333);' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#eee);' +
      '}' +
      '.live-wysiwyg-dead-link-panel-close{' +
        'background:none;border:none;cursor:pointer;font-size:1rem;line-height:1;' +
        'color:var(--md-default-fg-color--light,#999);padding:0 2px;' +
      '}' +
      '.live-wysiwyg-dead-link-panel-close:hover{color:var(--md-default-fg-color,#333);}' +
      '.live-wysiwyg-dead-link-panel-list{' +
        'flex:1;overflow-y:auto;padding:.3rem 0;' +
        'scrollbar-width:thin;' +
        'scrollbar-color:var(--md-default-fg-color--lighter,#ccc) transparent;' +
      '}' +
      '.live-wysiwyg-dead-link-entry{' +
        'display:flex;align-items:baseline;gap:4px;' +
        'padding:3px .6rem;cursor:pointer;' +
        'transition:background .1s;' +
      '}' +
      '.live-wysiwyg-dead-link-entry:hover{' +
        'background:var(--md-default-bg-color--light,#f7f7f7);' +
      '}' +
      '.live-wysiwyg-dead-link-entry-text{' +
        'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
        'color:var(--md-typeset-a-color,#d9534f);' +
      '}' +
      '.live-wysiwyg-dead-link-entry-label{' +
        'flex-shrink:0;font-size:.6rem;padding:1px 4px;border-radius:3px;' +
        'background:var(--md-default-fg-color--lightest,#eee);' +
        'color:var(--md-default-fg-color--light,#777);' +
      '}' +
      '.live-wysiwyg-dead-link-entry-resolve{' +
        'flex-shrink:0;background:none;border:none;cursor:pointer;' +
        'font-size:.65rem;line-height:1;padding:0 2px;' +
        'color:var(--md-default-fg-color--lighter,#bbb);transition:color .15s;' +
      '}' +
      '.live-wysiwyg-dead-link-entry-resolve:hover{color:var(--md-default-fg-color,#333);}' +
      '.live-wysiwyg-dead-link-panel-actions{' +
        'padding:.5rem .6rem;display:flex;gap:6px;' +
        'border-top:1px solid var(--md-default-fg-color--lightest,#eee);' +
      '}' +
      '.live-wysiwyg-dead-link-panel-actions button{' +
        'padding:3px 8px;border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
        'border-radius:3px;font-size:.65rem;cursor:pointer;' +
        'background:var(--md-default-bg-color,#fff);' +
        'color:var(--md-default-fg-color,#333);transition:background .15s;' +
      '}' +
      '.live-wysiwyg-dead-link-panel-actions button:hover{' +
        'background:var(--md-default-bg-color--light,#f7f7f7);' +
      '}' +

      // --- Dead link analysis wizard ---
      '.live-wysiwyg-dead-link-wizard-row{' +
        'display:flex;align-items:center;gap:8px;' +
        'padding:6px 0;border-bottom:1px solid var(--md-default-fg-color--lightest,#eee);' +
        'font-size:.8rem;transition:opacity .15s;' +
      '}' +
      '.live-wysiwyg-dead-link-wizard-row:last-child{border-bottom:none;}' +
      '.live-wysiwyg-dead-link-wizard-badge{' +
        'flex-shrink:0;min-width:32px;text-align:center;' +
        'padding:2px 6px;border-radius:3px;font-size:.7rem;font-weight:600;' +
        'background:var(--md-default-fg-color--lightest,#eee);' +
        'color:var(--md-default-fg-color--light,#666);' +
      '}' +
      '.live-wysiwyg-dead-link-wizard-desc{' +
        'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
        'color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-dead-link-wizard-toggle{' +
        'flex-shrink:0;padding:3px 10px;border:1px solid var(--md-default-fg-color--lighter,#ccc);' +
        'border-radius:3px;font-size:.7rem;cursor:pointer;' +
        'background:var(--md-default-bg-color,#fff);' +
        'color:var(--md-default-fg-color,#333);transition:all .15s;' +
      '}' +
      '.live-wysiwyg-dead-link-wizard-toggle:hover{' +
        'background:var(--md-default-bg-color--light,#f7f7f7);' +
      '}' +
      '.live-wysiwyg-dead-link-wizard-excluded{opacity:.45;}' +
      '.live-wysiwyg-dead-link-wizard-excluded .live-wysiwyg-dead-link-wizard-desc{' +
        'text-decoration:line-through;' +
      '}' +
      '.live-wysiwyg-dead-link-wizard-excluded .live-wysiwyg-dead-link-wizard-toggle{' +
        'background:#d9534f;color:#fff;border-color:#d9534f;' +
      '}' +
      '.live-wysiwyg-dead-link-wizard-other{' +
        'color:var(--md-default-fg-color--light,#888);font-style:italic;' +
      '}' +

      // --- Hidden (headless) pages in nav ---
      '.live-wysiwyg-nav-hidden-cb{' +
        'appearance:none;-webkit-appearance:none;width:13px;height:13px;' +
        'border:2px solid var(--md-default-fg-color--lighter,#bbb);border-radius:3px;' +
        'cursor:pointer;position:relative;flex-shrink:0;margin-right:4px;vertical-align:middle;' +
        'transition:background-color .15s,border-color .15s;' +
      '}' +
      '.live-wysiwyg-nav-hidden-cb:checked{' +
        'background-color:var(--md-accent-fg-color,#7c4dff);' +
        'border-color:var(--md-accent-fg-color,#7c4dff);' +
      '}' +
      '.live-wysiwyg-nav-hidden-cb:checked::after{' +
        'content:"";position:absolute;left:2px;top:0px;width:4px;height:7px;' +
        'border:solid #fff;border-width:0 2px 2px 0;transform:rotate(45deg);' +
      '}' +
      '.live-wysiwyg-nav-hidden-page{' +
        'border-left:2px solid var(--md-default-fg-color--lighter,#bbb);' +
      '}' +
      '.live-wysiwyg-nav-hidden-page>.md-nav__link{' +
        'opacity:.6;' +
      '}' +
      '.live-wysiwyg-nav-hidden-page>.md-nav__link:hover{opacity:.85;}' +
      '.live-wysiwyg-nav-hidden-page--current{' +
        'border-left-color:var(--md-accent-fg-color,#7c4dff);' +
      '}' +
      '.live-wysiwyg-nav-hidden-page--current>.md-nav__link{opacity:1;}' +
      '.live-wysiwyg-nav-hidden-info{' +
        'display:inline-flex;align-items:center;justify-content:center;' +
        'margin-left:4px;flex-shrink:0;font-size:.55rem;' +
        'color:var(--md-default-fg-color--lighter,#aaa);cursor:help;' +
        'transition:color .15s;' +
      '}' +
      '.live-wysiwyg-nav-hidden-info:hover{color:var(--md-accent-fg-color,#7c4dff);}' +

      '.live-wysiwyg-nav-asset-item{' +
        'border-left:2px solid var(--md-default-fg-color--lightest,#ddd);' +
      '}' +
      '.live-wysiwyg-nav-asset-link{' +
        'display:flex;align-items:center;gap:4px;' +
        'opacity:.55;font-size:.75rem;cursor:default;' +
        'padding:2px 6px;line-height:1.3;' +
      '}' +
      '.live-wysiwyg-nav-asset-link:hover{opacity:.8;}' +
      '.live-wysiwyg-nav-asset-icon{flex-shrink:0;font-size:.7rem;}' +
      '.live-wysiwyg-nav-asset-ext{' +
        'flex-shrink:0;font-size:.6rem;opacity:.7;' +
        'background:var(--md-default-fg-color--lightest,#eee);' +
        'border-radius:2px;padding:0 3px;margin-left:auto;' +
      '}' +
      '.live-wysiwyg-nav-item--renamed .live-wysiwyg-nav-asset-link{' +
        'opacity:.75;font-style:italic;' +
      '}' +

      '';
  }

  function buildFocusToc(editableArea, tocListEl) {
    if (!tocListEl) return;
    var html = '';
    if (wysiwygEditor && wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
      var mdVal = wysiwygEditor.markdownArea.value;
      var mdLines = mdVal.split('\n');
      var inFence = false;
      var idx = 0;
      for (var li = 0; li < mdLines.length; li++) {
        if (/^(`{3,}|~{3,})/.test(mdLines[li])) { inFence = !inFence; continue; }
        if (inFence) continue;
        var hMatch = mdLines[li].match(/^(#{1,6})\s+(.*)/);
        if (!hMatch) continue;
        var level = hMatch[1].length;
        var text = hMatch[2].replace(/\s*#*\s*$/, '').trim();
        if (!text) continue;
        var paddingLeft = 0.6 + (level - 1) * 0.6;
        html += '<li class="md-nav__item">' +
          '<a class="md-nav__link" data-focus-toc-idx="' + idx + '" style="padding-left:' + paddingLeft + 'rem" title="' + text.replace(/"/g, '&quot;') + '">' +
          '<span class="md-ellipsis">' + text.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</span>' +
          '</a></li>';
        idx++;
      }
    } else if (editableArea) {
      var headings = editableArea.querySelectorAll('h1, h2, h3, h4, h5, h6');
      for (var i = 0; i < headings.length; i++) {
        var h = headings[i];
        var level = parseInt(h.tagName.charAt(1), 10);
        var text = h.textContent.replace(/¶/g, '').trim();
        if (!text) continue;
        var paddingLeft = 0.6 + (level - 1) * 0.6;
        html += '<li class="md-nav__item">' +
          '<a class="md-nav__link" data-focus-toc-idx="' + i + '" style="padding-left:' + paddingLeft + 'rem" title="' + text.replace(/"/g, '&quot;') + '">' +
          '<span class="md-ellipsis">' + text.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</span>' +
          '</a></li>';
      }
    }
    tocListEl.innerHTML = html;
  }

  function _setTocActiveByIdx(tocListEl, activeIdx) {
    var links = tocListEl.querySelectorAll('.md-nav__link');
    for (var j = 0; j < links.length; j++) {
      var idx = parseInt(links[j].getAttribute('data-focus-toc-idx'), 10);
      if (idx === activeIdx) {
        links[j].classList.add('md-nav__link--active');
        var tocContainer = tocListEl.closest('.live-wysiwyg-focus-toc');
        if (tocContainer) {
          var linkTop = links[j].offsetTop;
          var tocHeight = tocContainer.clientHeight;
          var tocScroll = tocContainer.scrollTop;
          if (linkTop < tocScroll || linkTop > tocScroll + tocHeight - 30) {
            tocContainer.scrollTop = Math.max(0, linkTop - tocHeight / 3);
          }
        }
      } else {
        links[j].classList.remove('md-nav__link--active');
      }
    }
  }

  function _updateFocusTocActive(scrollContainer, editableArea, tocListEl) {
    if (!scrollContainer || !editableArea || !tocListEl) return;
    if (wysiwygEditor && wysiwygEditor.currentMode === 'markdown') {
      _updateFocusTocActiveMarkdown(tocListEl);
      return;
    }
    var headings = editableArea.querySelectorAll('h1, h2, h3, h4, h5, h6');
    if (!headings.length) return;
    var containerRect = scrollContainer.getBoundingClientRect();
    var threshold = containerRect.height * 0.15 + 5;
    var activeIdx = -1;
    for (var i = 0; i < headings.length; i++) {
      var relativeTop = headings[i].getBoundingClientRect().top - containerRect.top;
      if (relativeTop <= threshold) {
        activeIdx = i;
      } else {
        break;
      }
    }
    if (activeIdx < 0 && headings.length > 0) activeIdx = 0;
    _setTocActiveByIdx(tocListEl, activeIdx);
  }

  function _updateFocusTocActiveMarkdown(tocListEl) {
    if (!tocListEl || !wysiwygEditor || !wysiwygEditor.markdownArea) return;
    var ma = wysiwygEditor.markdownArea;
    var cursorPos = ma.selectionStart;
    var mdLines = ma.value.split('\n');
    var inFence = false;
    var activeIdx = -1;
    var idx = 0;
    var charPos = 0;
    for (var li = 0; li < mdLines.length; li++) {
      var lineStart = charPos;
      charPos += mdLines[li].length + 1;
      if (/^(`{3,}|~{3,})/.test(mdLines[li])) { inFence = !inFence; continue; }
      if (inFence) continue;
      var hMatch = mdLines[li].match(/^(#{1,6})\s+(.*)/);
      if (!hMatch) continue;
      var text = hMatch[2].replace(/\s*#*\s*$/, '').trim();
      if (!text) continue;
      if (lineStart <= cursorPos) {
        activeIdx = idx;
      }
      idx++;
    }
    if (activeIdx < 0 && idx > 0) activeIdx = 0;
    _setTocActiveByIdx(tocListEl, activeIdx);
  }

  function _updateFocusHeaderHeadings(scrollContainer, editableArea, titleEl) {
    if (!scrollContainer || !editableArea || !titleEl) return;
    var headings = editableArea.querySelectorAll('h1, h2, h3, h4, h5, h6');
    if (!headings.length) {
      titleEl.classList.remove('live-wysiwyg-focus-header-title--active');
      return;
    }
    var containerRect = scrollContainer.getBoundingClientRect();
    var h1Text = '';
    var h2Text = '';
    for (var i = 0; i < headings.length; i++) {
      var h = headings[i];
      var relTop = h.getBoundingClientRect().top - containerRect.top;
      if (relTop > 20) break;
      var level = parseInt(h.tagName.charAt(1), 10);
      var text = h.textContent.replace(/¶/g, '').trim();
      if (level === 1) {
        h1Text = text;
        h2Text = '';
      } else if (level === 2) {
        h2Text = text;
      }
    }
    var topicEl = titleEl.querySelector('.live-wysiwyg-focus-header-topic+.live-wysiwyg-focus-header-topic span');
    if (topicEl) {
      var display = h2Text || h1Text || '';
      topicEl.textContent = display;
    }
    if (h2Text || h1Text) {
      titleEl.classList.add('live-wysiwyg-focus-header-title--active');
    } else {
      titleEl.classList.remove('live-wysiwyg-focus-header-title--active');
    }
  }

  function _captureEditorSelection() {
    if (!wysiwygEditor) return null;
    var mode = wysiwygEditor.currentMode || 'wysiwyg';
    if (mode === 'markdown' && wysiwygEditor.markdownArea) {
      var ma = wysiwygEditor.markdownArea;
      var sc = wysiwygEditor.markdownEditorContainer;
      return {
        mode: 'markdown',
        selectionStart: ma.selectionStart,
        selectionEnd: ma.selectionEnd,
        scrollTop: sc ? sc.scrollTop : 0
      };
    }
    var ea = wysiwygEditor.editableArea;
    if (!ea) return null;
    var sel = window.getSelection();
    var rangeData = null;
    if (sel && sel.rangeCount > 0) {
      var range = sel.getRangeAt(0);
      if (ea.contains(range.commonAncestorContainer)) {
        rangeData = {
          startContainer: range.startContainer,
          startOffset: range.startOffset,
          endContainer: range.endContainer,
          endOffset: range.endOffset
        };
      }
    }
    var scrollContainer = isFocusModeActive
      ? (document.querySelector('.live-wysiwyg-focus-main'))
      : ea;
    return {
      mode: 'wysiwyg',
      rangeData: rangeData,
      semantic: captureSemanticSelection(ea),
      scrollTop: scrollContainer ? scrollContainer.scrollTop : 0
    };
  }

  function _restoreEditorSelection(saved, scrollContainer) {
    if (!saved || !wysiwygEditor) return;
    if (saved.mode === 'markdown' && wysiwygEditor.markdownArea) {
      var ma = wysiwygEditor.markdownArea;
      var sc = wysiwygEditor.markdownEditorContainer;
      ma.setSelectionRange(saved.selectionStart, saved.selectionEnd);
      if (sc) sc.scrollTop = saved.scrollTop;
      return;
    }
    var ea = wysiwygEditor.editableArea;
    if (!ea) return;
    var restored = false;
    if (saved.rangeData) {
      try {
        var rd = saved.rangeData;
        if (ea.contains(rd.startContainer) && ea.contains(rd.endContainer)) {
          var sel = window.getSelection();
          var range = document.createRange();
          range.setStart(rd.startContainer, rd.startOffset);
          range.setEnd(rd.endContainer, rd.endOffset);
          sel.removeAllRanges();
          sel.addRange(range);
          restored = true;
        }
      } catch (e) { /* node moved or offset invalid */ }
    }
    if (!restored && saved.semantic) {
      restored = restoreSelectionFromSemantic(ea, saved.semantic);
    }
    var sc2 = scrollContainer || ea;
    if (sc2) sc2.scrollTop = saved.scrollTop;
  }

  function enterFocusMode() {
    if (isFocusModeActive || !wysiwygEditor) return;

    var savedSelection = _captureEditorSelection();

    isFocusModeActive = true;
    _installFocusModeGuard();

    var styleEl = document.getElementById(FOCUS_MODE_STYLE_ID);
    if (!styleEl) {
      styleEl = document.createElement('style');
      styleEl.id = FOCUS_MODE_STYLE_ID;
      styleEl.textContent = _getFocusModeCSS();
      document.head.appendChild(styleEl);
    }

    _focusSavedBodyOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    var overlay = document.createElement('div');
    overlay.className = 'live-wysiwyg-focus-overlay';
    if (_getSetting('live_wysiwyg_focus_toolbar') !== '0') {
      overlay.classList.add('live-wysiwyg-focus-toolbar-open');
    }
    if (_getSetting('live_wysiwyg_focus_nav') === '0') {
      overlay.classList.add('live-wysiwyg-focus-nav-collapsed');
    }
    if (_getSetting('live_wysiwyg_focus_toc') === '0') {
      overlay.classList.add('live-wysiwyg-focus-toc-collapsed');
    }
    _focusOverlay = overlay;

    var themeColors = _detectThemeColors();
    for (var varName in themeColors) {
      if (themeColors.hasOwnProperty(varName)) {
        overlay.style.setProperty(varName, themeColors[varName]);
      }
    }

    // --- Header (styled like md-header md-header--shadow) ---
    var header = document.createElement('div');
    header.className = 'live-wysiwyg-focus-header';

    var headerLeft = document.createElement('div');
    headerLeft.className = 'live-wysiwyg-focus-header-left';

    var drawerToggle = document.createElement('button');
    drawerToggle.type = 'button';
    drawerToggle.className = 'live-wysiwyg-focus-drawer-toggle';
    drawerToggle.title = 'Toggle toolbar';
    drawerToggle.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z" fill="currentColor"/></svg>';
    drawerToggle.addEventListener('click', function () {
      var isOpen = overlay.classList.toggle('live-wysiwyg-focus-toolbar-open');
      _setSetting('live_wysiwyg_focus_toolbar', isOpen ? '1' : '0');
      _updateToolbarHeight(overlay, drawer);
    });
    var navToggle = document.createElement('button');
    navToggle.type = 'button';
    navToggle.className = 'live-wysiwyg-focus-nav-toggle';
    navToggle.title = 'Toggle navigation';
    navToggle.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z" fill="currentColor"/></svg>';
    navToggle.addEventListener('click', function () {
      var isCollapsed = overlay.classList.toggle('live-wysiwyg-focus-nav-collapsed');
      _setSetting('live_wysiwyg_focus_nav', isCollapsed ? '0' : '1');
    });
    var tocToggle = document.createElement('button');
    tocToggle.type = 'button';
    tocToggle.className = 'live-wysiwyg-focus-toc-toggle';
    tocToggle.title = 'Toggle table of contents';
    tocToggle.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z" fill="currentColor"/></svg>';
    tocToggle.addEventListener('click', function () {
      var isCollapsed = overlay.classList.toggle('live-wysiwyg-focus-toc-collapsed');
      _setSetting('live_wysiwyg_focus_toc', isCollapsed ? '0' : '1');
    });
    headerLeft.appendChild(navToggle);
    headerLeft.appendChild(drawerToggle);
    headerLeft.appendChild(tocToggle);
    header.appendChild(headerLeft);

    var titleDiv = document.createElement('div');
    titleDiv.className = 'live-wysiwyg-focus-header-title';
    var ellipsis = document.createElement('div');
    ellipsis.className = 'live-wysiwyg-focus-header-ellipsis';

    var topic1 = document.createElement('div');
    topic1.className = 'live-wysiwyg-focus-header-topic';
    var topic1Span = document.createElement('span');
    topic1Span.className = 'md-ellipsis';
    var siteTitle = document.title ? document.title.split(' - ').pop().trim() : 'Focus Mode';
    topic1Span.textContent = siteTitle;
    topic1.appendChild(topic1Span);

    var topic2 = document.createElement('div');
    topic2.className = 'live-wysiwyg-focus-header-topic';
    var topic2Span = document.createElement('span');
    topic2Span.className = 'md-ellipsis';
    topic2Span.textContent = '';
    topic2.appendChild(topic2Span);

    ellipsis.appendChild(topic1);
    ellipsis.appendChild(topic2);
    titleDiv.appendChild(ellipsis);
    header.appendChild(titleDiv);

    var paletteForm = document.querySelector('form.md-header__option[data-md-component="palette"]');
    if (paletteForm) {
      var paletteBtn = document.createElement('button');
      paletteBtn.type = 'button';
      paletteBtn.className = 'live-wysiwyg-focus-palette';
      function _updatePaletteBtn() {
        var visibleLabel = paletteForm.querySelector('label:not([hidden])');
        if (visibleLabel) {
          paletteBtn.innerHTML = visibleLabel.innerHTML;
          paletteBtn.title = visibleLabel.title || 'Toggle color scheme';
        }
      }
      _updatePaletteBtn();
      paletteBtn.addEventListener('click', function () {
        var visibleLabel = paletteForm.querySelector('label:not([hidden])');
        if (visibleLabel) visibleLabel.click();
        setTimeout(_updatePaletteBtn, 100);
      });
      header.appendChild(paletteBtn);
    }

    var closeBtn = document.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'live-wysiwyg-focus-close';
    closeBtn.title = 'Exit Focus Mode';
    closeBtn.innerHTML = '&#x2715;';
    closeBtn.addEventListener('click', function () {
      exitFocusMode();
    });
    header.appendChild(closeBtn);

    overlay.appendChild(header);

    // --- Collapsible toolbar drawer ---
    var drawer = document.createElement('div');
    drawer.className = 'live-wysiwyg-focus-toolbar-drawer';

    var drawerControls = document.createElement('div');
    drawerControls.className = 'live-wysiwyg-focus-drawer-controls';

    var modeToggle = document.createElement('div');
    modeToggle.className = 'live-wysiwyg-focus-mode-toggle';
    var wysBtn = document.createElement('button');
    wysBtn.type = 'button';
    wysBtn.textContent = 'WYSIWYG';
    var mdBtn = document.createElement('button');
    mdBtn.type = 'button';
    mdBtn.textContent = 'Markdown';
    var currentMode = wysiwygEditor.currentMode || 'wysiwyg';
    if (currentMode === 'wysiwyg') {
      wysBtn.classList.add('active');
    } else {
      mdBtn.classList.add('active');
      overlay.classList.add('focus-mode-markdown');
    }
    var toolbarWrap;

    var _focusTocList = null;

    function syncModeToggle(mode) {
      if (mode === 'wysiwyg') {
        wysBtn.classList.add('active');
        mdBtn.classList.remove('active');
        if (toolbarWrap) toolbarWrap.classList.remove('focus-markdown-mode');
        overlay.classList.remove('focus-mode-markdown');
      } else {
        mdBtn.classList.add('active');
        wysBtn.classList.remove('active');
        if (toolbarWrap) toolbarWrap.classList.add('focus-markdown-mode');
        overlay.classList.add('focus-mode-markdown');
      }
      if (_focusTocList && wysiwygEditor) {
        buildFocusToc(wysiwygEditor.editableArea, _focusTocList);
      }
      _attachOrDetachMdInputHandler(mode);
    }

    function _attachOrDetachMdInputHandler(mode) {
      var ma = wysiwygEditor && wysiwygEditor.markdownArea;
      var mc = wysiwygEditor && wysiwygEditor.markdownEditorContainer;
      if (mode === 'markdown' && ma && _focusTocList) {
        if (!_focusMdInputHandler) {
          _focusMdInputHandler = function () {
            clearTimeout(_focusTocDebounceTimer);
            _focusTocDebounceTimer = setTimeout(function () {
              if (wysiwygEditor && _focusTocList) {
                buildFocusToc(wysiwygEditor.editableArea, _focusTocList);
                _updateFocusTocActiveMarkdown(_focusTocList);
              }
            }, 300);
          };
        }
        if (!_focusMdCursorHandler) {
          _focusMdCursorHandler = function () {
            if (_focusTocList) _updateFocusTocActiveMarkdown(_focusTocList);
          };
        }
        ma.addEventListener('input', _focusMdInputHandler);
        ma.addEventListener('click', _focusMdCursorHandler);
        ma.addEventListener('keyup', _focusMdCursorHandler);
        if (mc) mc.addEventListener('scroll', _focusMdCursorHandler);
        _updateFocusTocActiveMarkdown(_focusTocList);
      } else if (ma) {
        if (_focusMdInputHandler) ma.removeEventListener('input', _focusMdInputHandler);
        if (_focusMdCursorHandler) {
          ma.removeEventListener('click', _focusMdCursorHandler);
          ma.removeEventListener('keyup', _focusMdCursorHandler);
          if (mc) mc.removeEventListener('scroll', _focusMdCursorHandler);
        }
      }
    }

    wysBtn.addEventListener('click', function () {
      if (wysiwygEditor && wysiwygEditor.currentMode !== 'wysiwyg') {
        wysiwygEditor.switchToMode('wysiwyg');
        syncModeToggle('wysiwyg');
        requestAnimationFrame(function () {
          scrollToCenterCursor(wysiwygEditor.editableArea, false);
        });
      }
    });
    mdBtn.addEventListener('click', function () {
      if (wysiwygEditor && wysiwygEditor.currentMode !== 'markdown') {
        wysiwygEditor.switchToMode('markdown');
        syncModeToggle('markdown');
        requestAnimationFrame(function () {
          if (wysiwygEditor.markdownArea) {
            scrollToCenterCursor(wysiwygEditor.markdownArea, true, wysiwygEditor.markdownArea.selectionStart, wysiwygEditor.markdownEditorContainer);
          }
        });
      }
    });
    modeToggle.appendChild(wysBtn);
    modeToggle.appendChild(mdBtn);
    drawerControls.appendChild(modeToggle);

    if (_isMaterialThemeDetected()) {
      var contentBtn = document.createElement('button');
      contentBtn.type = 'button';
      contentBtn.className = 'live-wysiwyg-focus-content-btn';
      contentBtn.title = 'Page Management';
      contentBtn.innerHTML = 'Content <span class="live-wysiwyg-page-submenu-arrow">\u25B6</span>';
      contentBtn.addEventListener('click', function () {
        var existing = document.querySelector('.live-wysiwyg-page-submenu');
        if (existing) {
          existing.parentNode.removeChild(existing);
          var arrow = contentBtn.querySelector('.live-wysiwyg-page-submenu-arrow');
          if (arrow) arrow.classList.remove('live-wysiwyg-page-submenu-arrow--open');
        } else {
          var arrow = contentBtn.querySelector('.live-wysiwyg-page-submenu-arrow');
          if (arrow) arrow.classList.add('live-wysiwyg-page-submenu-arrow--open');
          _createPageSubmenu(contentBtn);
        }
      });
      drawerControls.appendChild(contentBtn);
    }

    function _updateSaveDiscardVisibility(sBtn, dBtn) {
      var show = wysiwygEditor && wysiwygEditor._isDocDirty && wysiwygEditor._isDocDirty();
      if (show) {
        sBtn.classList.add('visible');
        dBtn.classList.add('visible');
      } else {
        sBtn.classList.remove('visible');
        dBtn.classList.remove('visible');
      }
    }

    var saveBtn = document.createElement('button');
    saveBtn.type = 'button';
    saveBtn.className = 'live-wysiwyg-focus-save-btn';
    saveBtn.textContent = 'Save';
    saveBtn.addEventListener('click', function () {
      _doFocusModeSave();
    });
    drawerControls.appendChild(saveBtn);

    var discardBtn = document.createElement('button');
    discardBtn.type = 'button';
    discardBtn.className = 'live-wysiwyg-focus-discard-btn';
    discardBtn.textContent = 'Discard';
    discardBtn.addEventListener('click', function () {
      if (!wysiwygEditor || !(wysiwygEditor._isDocDirty && wysiwygEditor._isDocDirty())) return;
      _showNavDialog(
        'Discard all changes to the current document?',
        [
          { text: 'Cancel', value: 'cancel' },
          { text: 'Discard', value: 'discard', className: 'live-wysiwyg-nav-dialog-danger' }
        ]
      ).then(function (result) {
        if (result === 'discard') {
          var currentSrc = _getCurrentSrcPath();
          if (currentSrc && wysiwygEditor) {
            _wsGetContents(currentSrc).then(function (md) {
              if (wysiwygEditor._loadContent) wysiwygEditor._loadContent(md);
              if (wysiwygEditor._resetPristineContent) wysiwygEditor._resetPristineContent(md);
              _refreshFocusToc();
              _updateSaveDiscardVisibility(saveBtn, discardBtn);
            });
          }
        }
      });
    });
    drawerControls.appendChild(discardBtn);

    var settingsBtn = document.createElement('button');
    settingsBtn.type = 'button';
    settingsBtn.className = 'live-wysiwyg-focus-settings-btn';
    settingsBtn.title = 'Settings';
    settingsBtn.textContent = '\u2699';
    settingsBtn.addEventListener('click', function () {
      var existing = document.querySelector('.live-wysiwyg-focus-settings-dropdown');
      if (existing) {
        existing.parentNode.removeChild(existing);
        return;
      }
      _createSettingsDropdown(settingsBtn);
    });
    drawerControls.appendChild(settingsBtn);

    drawer.appendChild(drawerControls);

    toolbarWrap = document.createElement('div');
    toolbarWrap.className = 'live-wysiwyg-focus-drawer-toolbar-wrap';
    if (currentMode === 'markdown') {
      toolbarWrap.classList.add('focus-markdown-mode');
    }

    if (wysiwygEditor.toolbar) {
      _focusOriginalToolbarParent = wysiwygEditor.toolbar.parentNode;
      toolbarWrap.appendChild(wysiwygEditor.toolbar);
      wysiwygEditor.toolbar.style.display = '';
    }
    drawer.appendChild(toolbarWrap);
    overlay.appendChild(drawer);

    // --- Main area: 3-column grid like md-main__inner md-grid ---
    var mainArea = document.createElement('div');
    mainArea.className = 'live-wysiwyg-focus-main';

    var grid = document.createElement('div');
    grid.className = 'live-wysiwyg-focus-grid';

    var sidebarLeft = document.createElement('div');
    sidebarLeft.className = 'live-wysiwyg-focus-sidebar-left';
    _validateNavStorageSchema();
    if (typeof liveWysiwygNavData !== 'undefined' && liveWysiwygNavData.length) {
      _assignUids(liveWysiwygNavData);
      _attachFrontmatterToNavData(liveWysiwygNavData);
      _applyStoredWarningsToNavData();
    }
    _buildNavMenu(sidebarLeft);

    _precomputeHiddenPages().then(function () {
      return _precomputeAssetFiles();
    }).then(function () {
      if (typeof liveWysiwygNavData !== 'undefined' && liveWysiwygNavData.length) {
        _assignUids(liveWysiwygNavData);
        _attachFrontmatterToNavData(liveWysiwygNavData);
      }
      return _preComputationContentScan();
    }).then(function () {
      return _prefetchMkdocsYml();
    }).then(function () {
      _seedNavTopWarnings();
      _buildNavMenu(sidebarLeft);
      if (_navSnapshots.length === 0 && typeof liveWysiwygNavData !== 'undefined' && liveWysiwygNavData.length) {
        _navSnapshots = [_takeNavSnapshot()];
        _navSnapshotIndex = 0;
      }
      setTimeout(function () { _resumePipeline(); }, 500);
    });

    var contentArea = document.createElement('div');
    contentArea.className = 'live-wysiwyg-focus-content';

    if (wysiwygEditor.editorWrapper) {
      var contentAreaEl = wysiwygEditor.editorWrapper.querySelector('.md-editor-content-area');
      if (contentAreaEl) {
        _focusSavedContentHeight = contentAreaEl.style.height;
        contentAreaEl.style.height = 'auto';
      }
      contentArea.appendChild(wysiwygEditor.editorWrapper);
    }

    // --- TOC (right sidebar, styled like md-sidebar--secondary) ---
    var tocPanel = document.createElement('div');
    tocPanel.className = 'live-wysiwyg-focus-toc';
    var tocNav = document.createElement('nav');
    tocNav.className = 'md-nav md-nav--secondary';
    tocNav.setAttribute('aria-label', 'Table of contents');
    var tocTitle = document.createElement('label');
    tocTitle.className = 'md-nav__title';
    tocTitle.textContent = 'Table of contents';
    var tocList = document.createElement('ul');
    tocList.className = 'md-nav__list';
    tocList.setAttribute('data-md-scrollfix', '');

    tocNav.appendChild(tocTitle);
    tocNav.appendChild(tocList);
    tocPanel.appendChild(tocNav);

    grid.appendChild(sidebarLeft);
    grid.appendChild(contentArea);
    grid.appendChild(tocPanel);
    mainArea.appendChild(grid);
    overlay.appendChild(mainArea);

    document.body.appendChild(overlay);
    _updateToolbarHeight(overlay, drawer);

    _focusTocList = tocList;
    buildFocusToc(wysiwygEditor.editableArea, tocList);
    _attachOrDetachMdInputHandler(currentMode);

    // --- TOC click-to-scroll ---
    tocList.addEventListener('click', function (e) {
      var link = e.target.closest('.md-nav__link');
      if (!link) return;
      e.preventDefault();
      var idx = parseInt(link.getAttribute('data-focus-toc-idx'), 10);
      if (isNaN(idx) || !wysiwygEditor) return;

      if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
        var headingText = link.textContent.trim();
        var ma = wysiwygEditor.markdownArea;
        var mdVal = ma.value;
        var headingRe = /^(#{1,6})\s+(.*)$/gm;
        var match;
        var mdIdx = 0;
        while ((match = headingRe.exec(mdVal)) !== null) {
          var matchText = match[2].replace(/\s*#*\s*$/, '').trim();
          if (mdIdx === idx || matchText === headingText) {
            ma.focus();
            var textStart = match.index + match[1].length + 1;
            ma.setSelectionRange(textStart, match.index + match[0].length);
            var sc = wysiwygEditor.markdownEditorContainer;
            if (sc) {
              var lineHeight = parseInt(window.getComputedStyle(ma).lineHeight, 10) || 20;
              var linesAbove = mdVal.substring(0, match.index).split('\n').length - 1;
              var target = Math.max(0, linesAbove * lineHeight - sc.clientHeight * 0.25);
              _smoothScrollTo(sc, target, 350);
            }
            break;
          }
          mdIdx++;
        }
        return;
      }

      if (!wysiwygEditor.editableArea) return;
      var headings = wysiwygEditor.editableArea.querySelectorAll('h1, h2, h3, h4, h5, h6');
      if (idx < headings.length) {
        var heading = headings[idx];
        var headingRect = heading.getBoundingClientRect();
        var mainRect = mainArea.getBoundingClientRect();
        var targetScroll = Math.max(0, mainArea.scrollTop + (headingRect.top - mainRect.top) - mainArea.clientHeight * 0.15);
        _smoothScrollTo(mainArea, targetScroll, 350);
        var sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(heading);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    });

    // --- Live TOC updates via MutationObserver ---
    _focusTocObserver = new MutationObserver(function () {
      clearTimeout(_focusTocDebounceTimer);
      _focusTocDebounceTimer = setTimeout(function () {
        if (wysiwygEditor && wysiwygEditor.editableArea) {
          buildFocusToc(wysiwygEditor.editableArea, tocList);
          _updateFocusTocActive(mainArea, wysiwygEditor.editableArea, tocList);
        }
      }, 300);
    });
    if (wysiwygEditor.editableArea) {
      _focusTocObserver.observe(wysiwygEditor.editableArea, {
        childList: true,
        characterData: true,
        subtree: true
      });
    }

    // --- Scroll: active heading tracking + dynamic header H1/H2 ---
    _focusContentScrollHandler = function () {
      if (wysiwygEditor && wysiwygEditor.editableArea) {
        _updateFocusTocActive(mainArea, wysiwygEditor.editableArea, tocList);
        _updateFocusHeaderHeadings(mainArea, wysiwygEditor.editableArea, titleDiv);
      }
    };
    mainArea.addEventListener('scroll', _focusContentScrollHandler);

    var focusModeBtn = wysiwygEditor.toolbar && wysiwygEditor.toolbar.querySelector('.live-wysiwyg-focus-btn');
    if (focusModeBtn) focusModeBtn.classList.add('active');

    _updateFocusTocActive(mainArea, wysiwygEditor.editableArea, tocList);
    _updateFocusHeaderHeadings(mainArea, wysiwygEditor.editableArea, titleDiv);

    _restoreEditorSelection(savedSelection, mainArea);

    if (window.__liveWysiwygEarlyOverlay) {
      var earlyOv = window.__liveWysiwygEarlyOverlay;
      window.__liveWysiwygEarlyOverlay = null;
      _fadeOutOverlay(earlyOv);
    }

    var cursorSetting = _getSetting('live_wysiwyg_nav_edit_cursor');
    if (cursorSetting) {
      try {
        var cursorData = JSON.parse(cursorSetting);
        _restoreEditorSelection(cursorData, mainArea);
      } catch (e) { /* parse error */ }
      _deleteSetting('live_wysiwyg_nav_edit_cursor');
    }

    _checkDeadLinksForCurrentPage();

    _updateSaveDiscardVisibility(saveBtn, discardBtn);
    var _dirtyCheckHandler = function () {
      _updateSaveDiscardVisibility(saveBtn, discardBtn);
    };
    if (wysiwygEditor.editableArea) {
      wysiwygEditor.editableArea.addEventListener('input', _dirtyCheckHandler);
    }
    if (wysiwygEditor.markdownArea) {
      wysiwygEditor.markdownArea.addEventListener('input', _dirtyCheckHandler);
    }
    overlay._dirtyCheckHandler = _dirtyCheckHandler;
    overlay._saveBtn = saveBtn;
    overlay._discardBtn = discardBtn;
    overlay._updateSaveDiscard = function () { _updateSaveDiscardVisibility(saveBtn, discardBtn); };

    if (_getSetting('live_wysiwyg_migration_normalize')) {
      _deleteSetting('live_wysiwyg_migration_normalize');
      _setSetting('live_wysiwyg_migration_adjust_weight', '1');
      setTimeout(function () { _autoNormalizeAfterMigration(); }, 600);
    } else if (_getSetting('live_wysiwyg_migration_adjust_weight')) {
      _deleteSetting('live_wysiwyg_migration_adjust_weight');
      setTimeout(function () {
        var adjusted = _autoAdjustDefaultPageWeight();
        if (!adjusted) {
          _showMigrationResultIfPending();
          _showPostSaveMessages();
        }
      }, 600);
    } else {
      _showMigrationResultIfPending();
      _showPostSaveMessages();
    }
  }

  function _showMigrationResultIfPending() {
    var result = _getSetting('live_wysiwyg_migration_result');
    if (!result) return;
    _deleteSetting('live_wysiwyg_migration_result');
    if (result === 'warnings') {
      _queuePostSaveMessage('warning', 'Migration completed with warnings.');
    } else {
      _queuePostSaveMessage('success', 'Migration completed successfully.');
    }
  }

  function _autoNormalizeAfterMigration() {
    if (typeof liveWysiwygNavData === 'undefined' || !liveWysiwygNavData.length) {
      _wsRedirectSuppressActive = false;
      return;
    }
    if (!_navHiddenPagesPrecomputed) {
      setTimeout(_autoNormalizeAfterMigration, 200);
      return;
    }
    _installReloadGuard();
    _wsRedirectSuppressActive = false;
    _enterNavEditModeAsync().then(function (ready) {
      if (!ready) { _removeReloadGuard(); return; }
      _applyNormalizeWeightsToNavData(liveWysiwygNavData);
      _adjustDefaultPageWeightSilent();
      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge',
        text: 'Normalize all weights (post-migration)'
      });
      _commitNavSnapshot();
      _executeNavBatchSave();
    });
  }

  function _adjustDefaultPageWeightSilent() {
    var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
    if (!nwCfg.enabled) return;
    var defWeight = nwCfg.default_page_weight !== undefined ? nwCfg.default_page_weight : 1000;
    var maxW = 0;
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        var it = items[i];
        if (it.weight != null && it.weight > maxW) maxW = it.weight;
        if (it.children) walk(it.children);
        if (it.index_meta && it.index_meta.weight != null && it.index_meta.weight > maxW) maxW = it.index_meta.weight;
      }
    })(liveWysiwygNavData);
    if (maxW <= defWeight) return;
    var suggested = Math.ceil((maxW + 500) / 1000) * 1000;
    _virtualMkdocsYml = _replaceDefaultPageWeight(_virtualMkdocsYml || '', suggested);
    if (_virtualOriginalMkdocsYml != null) {
      _virtualOriginalMkdocsYml = _replaceDefaultPageWeight(_virtualOriginalMkdocsYml, suggested);
    }
    liveWysiwygNavWeightConfig.default_page_weight = suggested;
    _removeNavTopWarning('weight-exceeds-default');
  }

  function _autoAdjustDefaultPageWeight() {
    _wsRedirectSuppressActive = false;
    if (typeof liveWysiwygNavData === 'undefined' || !liveWysiwygNavData.length) return false;
    var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
    if (!nwCfg.enabled) return false;
    var defWeight = nwCfg.default_page_weight !== undefined ? nwCfg.default_page_weight : 1000;
    var maxW = 0;
    (function walk(items) {
      for (var i = 0; i < items.length; i++) {
        var it = items[i];
        if (it.weight != null && it.weight > maxW) maxW = it.weight;
        if (it.children) walk(it.children);
        if (it.index_meta && it.index_meta.weight != null && it.index_meta.weight > maxW) maxW = it.index_meta.weight;
      }
    })(liveWysiwygNavData);
    if (maxW <= defWeight) return false;
    var suggested = Math.ceil((maxW + 500) / 1000) * 1000;
    _applyDefaultPageWeight(suggested);
    return true;
  }

  function exitFocusMode() {
    if (!isFocusModeActive) return;

    _removeFocusModeGuard();

    if (_navEditMode) _exitNavEditMode(false);
    _navSidebarEl = null;

    var savedSelection = _captureEditorSelection();

    isFocusModeActive = false;

    if (_focusTocObserver) {
      _focusTocObserver.disconnect();
      _focusTocObserver = null;
    }

    clearTimeout(_focusTocDebounceTimer);
    _focusTocDebounceTimer = null;

    if (_focusMdInputHandler && wysiwygEditor && wysiwygEditor.markdownArea) {
      wysiwygEditor.markdownArea.removeEventListener('input', _focusMdInputHandler);
      _focusMdInputHandler = null;
    }

    if (wysiwygEditor) {
      if (wysiwygEditor.toolbar && _focusOriginalToolbarParent) {
        _focusOriginalToolbarParent.insertBefore(wysiwygEditor.toolbar, _focusOriginalToolbarParent.firstChild);
      }
      if (wysiwygEditor.editorWrapper && wysiwygContainer) {
        wysiwygContainer.appendChild(wysiwygEditor.editorWrapper);
        var contentAreaEl = wysiwygEditor.editorWrapper.querySelector('.md-editor-content-area');
        if (contentAreaEl) {
          contentAreaEl.style.height = _focusSavedContentHeight || '';
        }
      }
      var focusModeBtn = wysiwygEditor.toolbar && wysiwygEditor.toolbar.querySelector('.live-wysiwyg-focus-btn');
      if (focusModeBtn) focusModeBtn.classList.remove('active');
    }
    _focusOriginalToolbarParent = null;

    var settingsDd = document.querySelector('.live-wysiwyg-focus-settings-dropdown');
    if (settingsDd && settingsDd.parentNode) settingsDd.parentNode.removeChild(settingsDd);

    if (_focusOverlay && _focusOverlay.parentNode) {
      if (_focusOverlay._dirtyCheckHandler) {
        if (wysiwygEditor && wysiwygEditor.editableArea)
          wysiwygEditor.editableArea.removeEventListener('input', _focusOverlay._dirtyCheckHandler);
        if (wysiwygEditor && wysiwygEditor.markdownArea)
          wysiwygEditor.markdownArea.removeEventListener('input', _focusOverlay._dirtyCheckHandler);
      }
      if (_focusContentScrollHandler) {
        var mainEl = _focusOverlay.querySelector('.live-wysiwyg-focus-main');
        if (mainEl) mainEl.removeEventListener('scroll', _focusContentScrollHandler);
      }
      _focusOverlay.parentNode.removeChild(_focusOverlay);
    }
    _focusOverlay = null;
    _focusContentScrollHandler = null;
    _focusHeadingScrollHandler = null;

    document.body.style.overflow = _focusSavedBodyOverflow;
    _focusSavedBodyOverflow = '';

    var styleEl = document.getElementById(FOCUS_MODE_STYLE_ID);
    if (styleEl && styleEl.parentNode) styleEl.parentNode.removeChild(styleEl);

    _restoreEditorSelection(savedSelection, null);
  }

  (function _attachFullscreenAutoEnter() {
    var events = ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'];
    function onFullscreenChange() {
      var fsEl = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
      if (!fsEl) return;
      if (isFocusModeActive) return;
      if (!wysiwygEditor) return;
      var edEnabled = isEditorEnabled();
      var editorEnabled = edEnabled !== false;
      if (!editorEnabled) return;
      var textarea = document.querySelector('.live-edit-source');
      if (!textarea || textarea.classList.contains('live-edit-hidden')) {
        enterFocusMode();
      }
    }
    for (var i = 0; i < events.length; i++) {
      document.addEventListener(events[i], onFullscreenChange);
    }
  })();

  function isInReadMode() {
    if (wysiwygEditor) return false;
    var textarea = document.querySelector('.live-edit-source');
    if (!textarea) return true;
    return textarea.classList.contains('live-edit-hidden') || textarea.offsetParent === null;
  }

  function isSelectionInEditForm(sel) {
    if (!sel || sel.rangeCount === 0) return false;
    var range = sel.getRangeAt(0);
    var container = range.commonAncestorContainer;
    var node = container.nodeType === 3 ? container.parentNode : container;
    if (!node) return false;
    return !!(node.closest && (
      node.closest('.live-edit-wysiwyg-wrapper') ||
      node.closest('.live-edit-source') ||
      node.closest('.live-edit-controls')
    ));
  }

  var CONTEXT_LEN = 120;

  function visibleTextContent(el) {
    var result = '';
    (function walk(node) {
      if (node.nodeType === 3) {
        result += node.textContent;
      } else if (node.nodeType === 1) {
        if (node.nodeName === 'SCRIPT' || node.nodeName === 'STYLE') return;
        for (var c = node.firstChild; c; c = c.nextSibling) walk(c);
      }
    })(el);
    return result;
  }

  function getSelectionContext(range) {
    var root = range.commonAncestorContainer;
    if (root.nodeType === 3) root = root.parentNode;
    while (root && root !== document.body) {
      var r = root.getAttribute && root.getAttribute('role');
      if (r === 'main' || root.tagName === 'ARTICLE' || (root.classList && root.classList.contains('md-content'))) break;
      root = root.parentNode;
    }
    if (!root) root = range.commonAncestorContainer.nodeType === 3 ? range.commonAncestorContainer.parentNode : range.commonAncestorContainer;
    var fullText = visibleTextContent(root);
    var preRange = document.createRange();
    preRange.selectNodeContents(root);
    preRange.setEnd(range.startContainer, range.startOffset);
    var startOffset = preRange.toString().length;
    var postRange = document.createRange();
    postRange.selectNodeContents(root);
    postRange.setStart(range.endContainer, range.endOffset);
    var endOffset = fullText.length - postRange.toString().length;
    var contextBefore = fullText.substring(Math.max(0, startOffset - CONTEXT_LEN), startOffset);
    var contextAfter = fullText.substring(endOffset, Math.min(fullText.length, endOffset + CONTEXT_LEN));
    return { contextBefore: contextBefore, contextAfter: contextAfter };
  }

  function rangeToTextWithImgAlt(range) {
    var frag = range.cloneContents();
    var result = '';
    (function walk(node) {
      if (node.nodeType === 3) {
        result += node.textContent;
      } else if (node.nodeName === 'SCRIPT' || node.nodeName === 'STYLE') {
        return;
      } else if (node.nodeName === 'IMG' && node.alt) {
        result += node.alt;
      } else {
        for (var c = node.firstChild; c; c = c.nextSibling) walk(c);
      }
    })(frag);
    return result;
  }

  function storeSelectionIfReadMode(sel) {
    if (!isInReadMode()) return;
    if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return;
    if (isSelectionInEditForm(sel)) return;
    var range = sel.getRangeAt(0);
    var selectedText = range.toString();
    if (range.startContainer.nodeType !== 3 || range.endContainer.nodeType !== 3) {
      var richText = rangeToTextWithImgAlt(range);
      if (richText.length > selectedText.length) selectedText = richText;
    }
    if (!selectedText || selectedText.length === 0) return;
    var ctx = getSelectionContext(range);
    var articleEl = document.querySelector('[role="main"] article')
      || document.querySelector('article.md-typeset')
      || document.querySelector('.md-content');
    var pm = articleEl ? buildPseudoMarkdown(articleEl) : null;
    pendingReadModeSelection = {
      selectedText: selectedText,
      contextBefore: ctx.contextBefore,
      contextAfter: ctx.contextAfter,
      pseudoMarkdown: pm
    };
  }

  var selectionEditPopup = null;
  var selectionEditPopupHideTimer = null;

  function findEditModeTrigger() {
    var controls = document.querySelector('.live-edit-controls');
    if (!controls) return null;
    var candidates = controls.querySelectorAll('button, a');
    for (var i = 0; i < candidates.length; i++) {
      var el = candidates[i];
      if (el.closest && el.closest('.live-edit-wysiwyg-wrapper')) continue;
      if (el.closest && el.closest('.live-wysiwyg-selection-edit-popup')) continue;
      var text = (el.textContent || '').trim();
      if (text.indexOf('Editor') >= 0) continue;
      if (text.indexOf('Edit') >= 0) return el;
      if (el.getAttribute && (el.getAttribute('title') || '').indexOf('Edit') >= 0) return el;
    }
    return null;
  }

  function getPagePathFromDOM() {
    var scripts = document.getElementsByTagName('script');
    for (var i = scripts.length - 1; i >= 0; i--) {
      var m = (scripts[i].textContent || '').match(/page_path\s*=\s*['"]([^'"]+)['"]/);
      if (m) return m[1];
    }
    return null;
  }

  var _pendingEditTriggerObserver = null;
  function clickEditTriggerOrDefer() {
    cancelPendingEditTrigger();
    var trigger = findEditModeTrigger();
    if (trigger) {
      trigger.click();
      return;
    }
    var path = getPagePathFromDOM();
    if (path) {
      window.dispatchEvent(new CustomEvent('live-edit-request-edit', { detail: { path: path } }));
      return;
    }
    _pendingEditTriggerObserver = new MutationObserver(function () {
      var t = findEditModeTrigger();
      if (t) {
        cancelPendingEditTrigger();
        t.click();
      } else {
        var p = getPagePathFromDOM();
        if (p) {
          cancelPendingEditTrigger();
          window.dispatchEvent(new CustomEvent('live-edit-request-edit', { detail: { path: p } }));
        }
      }
    });
    _pendingEditTriggerObserver.observe(document.body, { childList: true, subtree: true });
    setTimeout(function () { cancelPendingEditTrigger(); }, 15000);
  }
  function cancelPendingEditTrigger() {
    if (_pendingEditTriggerObserver) {
      _pendingEditTriggerObserver.disconnect();
      _pendingEditTriggerObserver = null;
    }
  }

  function ensureSelectionEditPopup() {
    if (selectionEditPopup) return;
    selectionEditPopup = document.createElement('div');
    selectionEditPopup.className = 'live-wysiwyg-selection-edit-popup';
    selectionEditPopup.innerHTML = '<button type="button" class="live-wysiwyg-selection-edit-btn" title="Edit selection">Edit</button>';
    selectionEditPopup.style.cssText = 'position:fixed;z-index:99999;padding:4px 8px;background:#333;color:#fff;border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,0.2);font-size:12px;font-family:inherit;opacity:0;transition:opacity 0.15s;pointer-events:none;visibility:hidden;';
    var btn = selectionEditPopup.querySelector('button');
    btn.style.cssText = 'background:transparent;border:none;color:inherit;cursor:pointer;padding:0 4px;font-size:inherit;';
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      storeSelectionIfReadMode(window.getSelection());
      hideSelectionEditPopup();
      clickEditTriggerOrDefer();
    });
    document.body.appendChild(selectionEditPopup);
  }

  function showSelectionEditPopup(rect) {
    ensureSelectionEditPopup();
    if (selectionEditPopupHideTimer) {
      clearTimeout(selectionEditPopupHideTimer);
      selectionEditPopupHideTimer = null;
    }
    var popup = selectionEditPopup;
    var popupRect = popup.getBoundingClientRect();
    var top = rect.top - popupRect.height - 6;
    if (top < 8) top = rect.bottom + 6;
    var left = rect.left + (rect.width / 2) - (popup.offsetWidth / 2);
    if (left < 8) left = 8;
    if (left + popup.offsetWidth > window.innerWidth - 8) left = window.innerWidth - popup.offsetWidth - 8;
    popup.style.left = left + 'px';
    popup.style.top = top + 'px';
    popup.style.opacity = '1';
    popup.style.pointerEvents = 'auto';
    popup.style.visibility = 'visible';
  }

  function hideSelectionEditPopup() {
    if (!selectionEditPopup) return;
    selectionEditPopup.style.opacity = '0';
    selectionEditPopup.style.pointerEvents = 'none';
    if (selectionEditPopupHideTimer) clearTimeout(selectionEditPopupHideTimer);
    selectionEditPopupHideTimer = setTimeout(function () {
      if (selectionEditPopup) selectionEditPopup.style.visibility = 'hidden';
      selectionEditPopupHideTimer = null;
    }, 150);
  }

  function updateSelectionEditPopup() {
    if (!isInReadMode()) {
      hideSelectionEditPopup();
      return;
    }
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0 || sel.isCollapsed) {
      hideSelectionEditPopup();
      return;
    }
    if (isSelectionInEditForm(sel)) {
      hideSelectionEditPopup();
      return;
    }
    var range = sel.getRangeAt(0);
    var rect = range.getBoundingClientRect();
    if (rect.width < 1 && rect.height < 1) {
      hideSelectionEditPopup();
      return;
    }
    showSelectionEditPopup(rect);
  }

  function captureReadModeSelectionOnChange() {
    document.addEventListener('selectionchange', function () {
      storeSelectionIfReadMode(window.getSelection());
      updateSelectionEditPopup();
    });
    document.addEventListener('mousedown', function (e) {
      storeSelectionIfReadMode(window.getSelection());
      if (selectionEditPopup && selectionEditPopup.contains(e.target)) return;
      hideSelectionEditPopup();
    }, true);
    document.addEventListener('scroll', hideSelectionEditPopup, true);
  }
  captureReadModeSelectionOnChange();

  // ───── Global Keyboard Router (Tier 2) ─────
  // Single document-level capture-phase keydown handler replacing ~10 separate
  // registrations. State flags replace dynamic addEventListener/removeEventListener.
  // See DESIGN-centralized-keyboard.md.
  (function _attachGlobalKeydownRouter() {
    if (document.__liveWysiwygGlobalKeydownRouterAttached) return;
    document.__liveWysiwygGlobalKeydownRouterAttached = true;

    function _handleDocSave(e) {
      if (!wysiwygEditor) return;
      e.preventDefault();
      e.stopPropagation();
      if (isFocusModeActive) {
        _doFocusModeSave();
        return;
      }
      var ea = wysiwygEditor.editableArea;
      var ma = wysiwygEditor.markdownArea;
      var docDirty = wysiwygEditor._isDocDirty && wysiwygEditor._isDocDirty();
      if (docDirty) {
        if (wysiwygEditor._finalizeUpdate) {
          if (wysiwygEditor.currentMode === 'wysiwyg' && ea) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          } else if (wysiwygEditor.currentMode === 'markdown' && ma) {
            wysiwygEditor._finalizeUpdate(ma.value);
          }
        }
        var saveBtn = document.querySelector('.live-edit-save-button');
        if (saveBtn && !saveBtn.classList.contains('live-edit-hidden')) {
          saveBtn.click();
        }
        return;
      }
      if (_navEditMode) {
        _confirmNavSave();
      }
    }

    function _handleToggleMode(e) {
      if (!wysiwygEditor) return;
      e.preventDefault();
      e.stopImmediatePropagation();
      if (isFocusModeActive) {
        var toggle = document.querySelector('.live-wysiwyg-focus-mode-toggle');
        if (toggle) {
          var btns = toggle.querySelectorAll('button');
          for (var i = 0; i < btns.length; i++) {
            if (!btns[i].classList.contains('active')) { btns[i].click(); return; }
          }
        }
        return;
      }
      var newMode = wysiwygEditor.currentMode === 'wysiwyg' ? 'markdown' : 'wysiwyg';
      wysiwygEditor.switchToMode(newMode);
      if (newMode === 'wysiwyg') {
        requestAnimationFrame(function () {
          scrollToCenterCursor(wysiwygEditor.editableArea, false);
        });
      } else if (wysiwygEditor.markdownArea) {
        requestAnimationFrame(function () {
          scrollToCenterCursor(wysiwygEditor.markdownArea, true, wysiwygEditor.markdownArea.selectionStart, wysiwygEditor.markdownEditorContainer);
        });
      }
    }

    function _handlePeriodEdit(e) {
      if (!isInReadMode()) return;
      var tag = (document.activeElement || document.body).tagName;
      if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
      if (document.activeElement && document.activeElement.isContentEditable) return;
      if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable)) return;
      e.preventDefault();
      e.stopPropagation();
      e.stopImmediatePropagation();
      storeSelectionIfReadMode(window.getSelection());
      hideSelectionEditPopup();
      clickEditTriggerOrDefer();
    }

    document.addEventListener('keydown', function _globalKeydownRouter(e) {
      var dialogOpen = !!document.querySelector('.live-wysiwyg-nav-dialog') ||
                       !!document.querySelector('.live-wysiwyg-nav-settings-dropdown');

      if (e.key === 'Escape') {
        if (dialogOpen) return;
        if (_navEditMode) {
          if (_hasAnyNavSelected() || _navKeyboardActiveItem) {
            e.preventDefault(); e.stopImmediatePropagation();
            _clearNavGroup();
            _commitNavSnapshot();
            return;
          }
          e.preventDefault(); e.stopImmediatePropagation();
          _confirmNavDiscard();
          return;
        }
        if (_admonitionDropdownDismiss) {
          _admonitionDropdownDismiss();
          return;
        }
        if (_reviewPopupDismiss) {
          _reviewPopupDismiss();
          return;
        }
      }

      if ((e.metaKey || e.ctrlKey) && e.key === 's') {
        if (_focusModeRebuildPromptOpen) {
          e.preventDefault(); e.stopImmediatePropagation();
          var primary = document.querySelector('.live-wysiwyg-nav-dialog .live-wysiwyg-nav-dialog-primary');
          if (primary) primary.click();
          return;
        }
        if (dialogOpen) return;
        if (_navEditMode) {
          e.preventDefault(); e.stopImmediatePropagation();
          _confirmNavSave();
          return;
        }
        _handleDocSave(e);
        return;
      }

      if ((e.metaKey || e.ctrlKey) && e.key === '.') {
        _handleToggleMode(e);
        return;
      }

      if (_navEditMode && !dialogOpen) {
        if (e.key.indexOf('Arrow') === 0 && _navKeyboardActiveItem) {
          var dir = null;
          if (e.key === 'ArrowUp') dir = 'up';
          else if (e.key === 'ArrowDown') dir = 'down';
          else if (e.key === 'ArrowLeft') dir = 'left';
          else if (e.key === 'ArrowRight') dir = 'right';
          if (dir) {
            e.preventDefault();
            _handleArrowClick(_navKeyboardActiveItem, _navKeyboardActiveItem.type || 'page', dir, e.shiftKey);
          }
          return;
        }
        if (e.key === 'Enter' && _navKeyboardActiveItem) {
          var _enterEl = document.activeElement;
          var _enterInContent = _enterEl && (_enterEl.tagName === 'TEXTAREA' || _enterEl.tagName === 'INPUT' || _enterEl.isContentEditable);
          if (!_enterInContent) {
            e.preventDefault(); e.stopImmediatePropagation();
            _confirmNavSave();
            return;
          }
        }
      }

      if ((e.metaKey || e.ctrlKey) && (e.key === 'z' || e.key === 'y')) {
        var _undoEl = document.activeElement;
        var _undoInContent = _undoEl && (_undoEl.tagName === 'TEXTAREA' || _undoEl.tagName === 'INPUT' || _undoEl.isContentEditable);
        if (_undoInContent) {
          if (e.key === 'z' && !e.shiftKey) {
            e.preventDefault(); e.stopImmediatePropagation(); _contentUndo(); return;
          }
          if (e.key === 'y' || (e.key === 'z' && e.shiftKey)) {
            e.preventDefault(); e.stopImmediatePropagation(); _contentRedo(); return;
          }
        } else if (!dialogOpen) {
          if (_navEditMode) {
            if (e.key === 'z' && !e.shiftKey) {
              e.preventDefault(); e.stopImmediatePropagation(); _navUndo(); return;
            }
            if (e.key === 'y' || (e.key === 'z' && e.shiftKey)) {
              e.preventDefault(); e.stopImmediatePropagation(); _navRedo(); return;
            }
          } else {
            if (e.key === 'z' && !e.shiftKey && _navSnapshotIndex > 0) {
              e.preventDefault(); e.stopImmediatePropagation(); _navUndo(); return;
            }
            if ((e.key === 'y' || (e.key === 'z' && e.shiftKey)) && _navSnapshotIndex < _navSnapshots.length - 1) {
              e.preventDefault(); e.stopImmediatePropagation(); _navRedo(); return;
            }
          }
        }
      }

      if (e.key === '.') {
        _handlePeriodEdit(e);
      }
    }, true);
  })();

  function getControlsElement(textarea) {
    var controls = textarea ? textarea.closest('.live-edit-controls') : null;
    if (controls) return controls;
    return document.querySelector('.live-edit-controls');
  }

  function getButtonLabel(isWysiwygActive) {
    var text = isWysiwygActive ? 'Disable Editor' : 'Enable Editor';
    if (typeof liveWysiwygIconDataUrl !== 'undefined' && liveWysiwygIconDataUrl) {
      return '<img src="' + liveWysiwygIconDataUrl + '" alt="" class="live-wysiwyg-btn-icon" aria-hidden="true" style="display:inline;width:1.2em;height:1.2em;vertical-align:middle;margin-right:.25em"> ' + text;
    }
    return text;
  }

  function updateToggleButton(isWysiwygActive) {
    if (!toggleButton) return;
    if (typeof liveWysiwygIconDataUrl !== 'undefined' && liveWysiwygIconDataUrl) {
      toggleButton.innerHTML = getButtonLabel(isWysiwygActive);
    } else {
      toggleButton.textContent = getButtonLabel(isWysiwygActive);
    }
  }

  function _ensureThemeOverrides() {
    _detectThemeColors();
    if (document.getElementById('live-wysiwyg-theme-overrides')) return;
    var s = document.createElement('style');
    s.id = 'live-wysiwyg-theme-overrides';
    s.textContent =
      '.live-edit-source{' +
        'font-family:var(--md-code-font-family,monospace)!important;' +
        'color:var(--md-default-fg-color,#333)!important;' +
        'background:var(--md-default-bg-color,#fff)!important;' +
        'border-color:var(--md-default-fg-color--lightest,#ccc)!important;' +
      '}' +
      'button.live-edit-button{' +
        'background:rgba(255,255,255,0.12)!important;' +
        'border:1px solid rgba(255,255,255,0.2)!important;' +
        'color:var(--md-primary-bg-color,#fff)!important;' +
        'transition:background .2s;' +
      '}' +
      'button.live-edit-button:hover{' +
        'background:rgba(255,255,255,0.25)!important;' +
      '}' +
      'button.live-edit-save-button{' +
        'background:#5cb85c!important;border-color:#4cae4c!important;color:#fff!important;' +
      '}' +
      'button.live-edit-save-button:hover{' +
        'background:#4cae4c!important;' +
      '}' +
      'button.live-edit-cancel-button{' +
        'background:#d9534f!important;border-color:#d43f3a!important;color:#fff!important;' +
      '}' +
      'button.live-edit-cancel-button:hover{' +
        'background:#d43f3a!important;' +
      '}' +
      'div.live-edit-controls{' +
        'background:linear-gradient(to bottom,var(--md-primary-fg-color,#fff2dc),var(--md-footer-bg-color,#f0c36d))!important;' +
        'border-color:var(--md-primary-fg-color--dark,#f0c36d)!important;' +
        'color:var(--md-primary-bg-color,inherit)!important;' +
      '}' +
      '.live-edit-label{' +
        'color:var(--md-primary-bg-color,inherit)!important;' +
      '}' +
      '.live-edit-info-modal{' +
        'background-color:var(--md-default-bg-color--light,#fff2dc)!important;' +
        'border-color:var(--md-default-fg-color--lightest,#f0c36d)!important;' +
      '}';
    document.head.appendChild(s);
  }

  function ensureToggleButton(textarea, isWysiwygActive) {
    if (toggleButton && toggleButton.parentNode) return;
    _ensureThemeOverrides();
    var controls = getControlsElement(textarea);
    if (!controls) return;
    var label = controls.querySelector('.live-edit-label');
    toggleButton = document.createElement('button');
    toggleButton.type = 'button';
    toggleButton.className = 'live-edit-button';
    if (typeof liveWysiwygIconDataUrl !== 'undefined' && liveWysiwygIconDataUrl) {
      toggleButton.innerHTML = getButtonLabel(isWysiwygActive);
    } else {
      toggleButton.textContent = getButtonLabel(isWysiwygActive);
    }
    toggleButton.title = isWysiwygActive ? 'Switch to plain textarea' : 'Switch to WYSIWYG editor';
    toggleButton.addEventListener('click', function () {
      if (wysiwygEditor) {
        setEditorState(false, wysiwygEditor.currentMode);
        destroyWysiwyg(textarea, false, true);
        updateToggleButton(false);
      } else {
        setEditorState(true, getEditorMode());
        replaceTextareaWithWysiwyg(textarea);
        updateToggleButton(true);
      }
    });
    controls.insertBefore(toggleButton, label ? label.nextSibling : controls.firstChild);
  }

  function removeToggleButton() {
    if (toggleButton && toggleButton.parentNode) {
      toggleButton.parentNode.removeChild(toggleButton);
      toggleButton = null;
    }
  }

  function startBodyObserver() {
    if (bodyObserver) return;
    function checkAndHandle() {
      if (observeForTextarea()) {
        stopBodyObserver();
      } else if (_getSetting('live_wysiwyg_autolaunch') === '1' && !window.__liveWysiwygEarlyOverlay) {
        _autoClickEditButton();
      }
    }
    bodyObserver = new MutationObserver(function (mutations) {
      for (var i = 0; i < mutations.length; i++) {
        var m = mutations[i];
        if (m.type === 'childList' && m.addedNodes.length) {
          checkAndHandle();
          return;
        }
        if (m.type === 'attributes' && m.attributeName === 'class') {
          var el = m.target;
          if (el.classList && el.classList.contains('live-edit-source') && !el.classList.contains('live-edit-hidden')) {
            checkAndHandle();
            return;
          }
        }
      }
    });
    bodyObserver.observe(document.body, { childList: true, subtree: true });
    var hiddenTextarea = document.querySelector('.live-edit-source.live-edit-hidden');
    if (hiddenTextarea) {
      bodyObserver.observe(hiddenTextarea, { attributes: true, attributeFilter: ['class'] });
    }
    checkAndHandle();
  }

  function stopBodyObserver() {
    if (bodyObserver) {
      bodyObserver.disconnect();
      bodyObserver = null;
    }
  }

  function destroyWysiwyg(textarea, leavingEditMode, userRequestedDisable) {
    if (isFocusModeActive) {
      exitFocusMode();
    }
    var cursorState = null;
    var contentToRestore = null;
    if (textarea && wysiwygEditor) {
      var ed = wysiwygEditor;
      contentToRestore = ed.getValue();
      if (contentToRestore && !contentToRestore.endsWith('\n')) contentToRestore += '\n';
      if (!leavingEditMode) {
        if (ed.currentMode === 'markdown') {
          textarea.value = contentToRestore;
          cursorState = {
            start: ed.markdownArea.selectionStart,
            end: ed.markdownArea.selectionEnd,
            scrollTop: ed.markdownEditorContainer ? ed.markdownEditorContainer.scrollTop : 0
          };
        } else {
          injectMarkerAtCaretInEditable(ed.editableArea);
          var md = ed.getValue();
          var markerIdx = md.indexOf(CURSOR_MARKER);
          if (markerIdx >= 0) {
            cursorState = {
              start: markerIdx,
              end: markerIdx,
              scrollTop: ed.editableArea ? ed.editableArea.scrollTop : 0
            };
            ed.editableArea.innerHTML = ed.editableArea.innerHTML.replace(CURSOR_MARKER_RE, '');
          }
        }
      }
    }
    if (cancelObserver) {
      cancelObserver.disconnect();
      cancelObserver = null;
    }
    var lastMode = wysiwygEditor ? wysiwygEditor.currentMode : null;
    if (wysiwygEditor) {
      try {
        wysiwygEditor.destroy();
      } catch (e) {
        console.warn('live-wysiwyg: error destroying editor', e);
      }
      wysiwygEditor = null;
    }
    if (wysiwygContainer && wysiwygContainer.parentNode) {
      wysiwygContainer.parentNode.removeChild(wysiwygContainer);
      wysiwygContainer = null;
    }
    var widthStyle = document.getElementById('live-wysiwyg-width-overrides');
    if (widthStyle && widthStyle.parentNode) widthStyle.parentNode.removeChild(widthStyle);
    if (leavingEditMode) {
      if (lastMode) {
        setEditorState(true, lastMode);
      }
      pendingReadModeSelection = null;
      removeToggleButton();
      startBodyObserver();
    }
    if (textarea) {
      if (contentToRestore) {
        textarea.value = contentToRestore;
      }
      textarea.style.display = '';
      textarea.removeAttribute('data-live-wysiwyg-replaced');
      if (cursorState) {
        textarea.selectionStart = Math.min(cursorState.start, textarea.value.length);
        textarea.selectionEnd = Math.min(cursorState.end, textarea.value.length);
        scrollToCenterCursor(textarea, true, textarea.selectionStart);
      }
      if (leavingEditMode) {
        return;
      }
      if (userRequestedDisable) {
        ensureToggleButton(textarea, false);
        updateToggleButton(false);
      } else {
        var edEnabled = isEditorEnabled();
        var shouldReload = edEnabled !== false;
        if (shouldReload) {
          setupReplacementObserver(textarea);
        } else {
          ensureToggleButton(textarea, false);
          updateToggleButton(false);
        }
      }
    }
  }

  function setupReplacementObserver(textarea) {
    if (!textarea || !textarea.parentNode) return;
    if (cancelObserver) cancelObserver.disconnect();
    cancelObserver = new MutationObserver(function () {
      if (!textarea.parentNode) return;
      if (!textarea.classList.contains('live-edit-hidden') && !textarea.dataset.liveWysiwygReplaced) {
        var edEnabled = isEditorEnabled();
        if (edEnabled === false) return;
        cancelObserver.disconnect();
        cancelObserver = null;
        replaceTextareaWithWysiwyg(textarea);
      }
    });
    cancelObserver.observe(textarea, { attributes: true, attributeFilter: ['class'] });
  }

  function replaceTextareaWithWysiwyg(textarea) {
    if (textarea.dataset.liveWysiwygReplaced) return;
    textarea.dataset.liveWysiwygReplaced = 'true';

    if (cancelObserver) {
      cancelObserver.disconnect();
      cancelObserver = null;
    }

    const initialValue = textarea.value || '';
    var _pristineContent = initialValue;
    var savedCursor = {
      start: textarea.selectionStart,
      end: textarea.selectionEnd,
      scrollTop: textarea.scrollTop
    };

    var _upstreamSaveBtn = document.querySelector('.live-edit-save-button');
    var _upstreamCancelBtn = document.querySelector('.live-edit-cancel-button');
    if (_upstreamSaveBtn) _upstreamSaveBtn.classList.add('live-edit-hidden');
    if (_upstreamCancelBtn) _upstreamCancelBtn.classList.add('live-edit-hidden');

    wysiwygContainer = document.createElement('div');
    wysiwygContainer.id = 'live-edit-wysiwyg-container';
    wysiwygContainer.className = 'live-edit-wysiwyg-wrapper';
    wysiwygContainer.style.cssText = 'min-height: 50vh; margin: 5px 0;';

    textarea.parentNode.insertBefore(wysiwygContainer, textarea);
    textarea.style.display = 'none';

    _ensureThemeOverrides();

    var widthStyle = document.getElementById('live-wysiwyg-width-overrides');
    if (!widthStyle) {
      widthStyle = document.createElement('style');
      widthStyle.id = 'live-wysiwyg-width-overrides';
      widthStyle.textContent =
        '.live-edit-controls.live-edit-editing .live-edit-source{margin-left:-10px!important;margin-right:-10px!important;padding-left:1px!important;padding-right:1px!important;width:calc(100% + 20px)!important}' +
        '.live-edit-controls.live-edit-editing .live-edit-wysiwyg-wrapper{margin-left:-10px!important;margin-right:-10px!important;width:calc(100% + 20px)!important}' +
        '.live-edit-controls.live-edit-editing .live-edit-wysiwyg-wrapper .md-wysiwyg-editor-wrapper{border-left:none!important;border-right:none!important;border-radius:0!important}';
      document.head.appendChild(widthStyle);
    }

    var preferredMode = getEditorMode();
    try {
      wysiwygEditor = new MarkdownWYSIWYG('live-edit-wysiwyg-container', {
        initialValue: initialValue,
        initialMode: preferredMode,
        showToolbar: true,
        onUpdate: function (markdownContent) {
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor._liveWysiwygLinkData) {
            markdownContent = postprocessMarkdownLinks(markdownContent, wysiwygEditor._liveWysiwygLinkData);
          }
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor._liveWysiwygListMarkerData) {
            markdownContent = postprocessListMarkers(markdownContent, wysiwygEditor._liveWysiwygListMarkerData);
          }
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor._liveWysiwygTableSepData) {
            markdownContent = postprocessTableSeparators(markdownContent, wysiwygEditor._liveWysiwygTableSepData);
          }
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor._liveWysiwygCodeBlockData) {
            markdownContent = postprocessCodeBlocks(markdownContent, wysiwygEditor._liveWysiwygCodeBlockData);
          }
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor._liveWysiwygHrData) {
            markdownContent = postprocessHorizontalRules(markdownContent, wysiwygEditor._liveWysiwygHrData);
          }
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor._liveWysiwygInlineCodeData) {
            markdownContent = postprocessInlineCode(markdownContent, wysiwygEditor._liveWysiwygInlineCodeData);
          }
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor._liveWysiwygLinkData) {
            markdownContent = dryDuplicateInlineLinks(markdownContent, wysiwygEditor._liveWysiwygLinkData);
            markdownContent = collapseRedundantReferenceToShortcut(markdownContent);
            markdownContent = removeUnusedRefDefs(markdownContent);
            markdownContent = renumberRefDefs(markdownContent);
          }
          if (markdownContent) {
            markdownContent = stripCursorSpanHtml(markdownContent).replace(CURSOR_MARKER_RE, '').replace(CURSOR_MARKER_END_RE, '').replace(CURSOR_UNICODE_RE, '');
            if (!markdownContent.endsWith('\n')) {
              markdownContent = markdownContent + '\n';
            }
          }
          textarea.value = markdownContent;
          if (_pristineContent !== null && !isFocusModeActive) {
            var changed = markdownContent !== _pristineContent;
            if (_upstreamSaveBtn) {
              if (changed) _upstreamSaveBtn.classList.remove('live-edit-hidden');
              else _upstreamSaveBtn.classList.add('live-edit-hidden');
            }
            if (_upstreamCancelBtn) {
              if (changed) _upstreamCancelBtn.classList.remove('live-edit-hidden');
              else _upstreamCancelBtn.classList.add('live-edit-hidden');
            }
          }
          if (isFocusModeActive && _focusOverlay && _focusOverlay._updateSaveDiscard) {
            _focusOverlay._updateSaveDiscard();
          }
        },
      });
    } catch (e) {
      console.error('live-wysiwyg: failed to init editor', e);
      textarea.style.display = '';
      if (wysiwygContainer && wysiwygContainer.parentNode) {
        wysiwygContainer.parentNode.removeChild(wysiwygContainer);
      }
      wysiwygEditor = null;
      wysiwygContainer = null;
      textarea.removeAttribute('data-live-wysiwyg-replaced');
      return;
    }

    wysiwygEditor._resetPristineContent = function (newMarkdown) {
      _pristineContent = newMarkdown;
      if (_upstreamSaveBtn) _upstreamSaveBtn.classList.add('live-edit-hidden');
      if (_upstreamCancelBtn) _upstreamCancelBtn.classList.add('live-edit-hidden');
    };

    wysiwygEditor._isDocDirty = function () {
      if (_pristineContent === null) return false;
      return textarea.value !== _pristineContent;
    };

    if (wysiwygEditor._attachLinkChainHandler) wysiwygEditor._attachLinkChainHandler();

    wysiwygEditor._loadContent = function (markdown) {
      textarea.value = markdown;
      _pristineContent = markdown;
      if (_upstreamSaveBtn) _upstreamSaveBtn.classList.add('live-edit-hidden');
      if (_upstreamCancelBtn) _upstreamCancelBtn.classList.add('live-edit-hidden');
      var parsed = parseFrontmatter(markdown);
      wysiwygEditor._liveWysiwygFrontmatter = parsed.frontmatter;
      if (wysiwygEditor.currentMode === 'wysiwyg') {
        var html = wysiwygEditor._markdownToHtml(parsed.body);
        if (wysiwygEditor.editableArea) {
          wysiwygEditor.editableArea.innerHTML = html;
          wysiwygEditor._pushToUndoStack(html);
        }
      } else if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
        wysiwygEditor.markdownArea.value = markdown;
        if (wysiwygEditor._updateMarkdownLineNumbers) wysiwygEditor._updateMarkdownLineNumbers();
        wysiwygEditor.markdownArea.scrollTop = 0;
        if (wysiwygEditor.markdownEditorContainer) wysiwygEditor.markdownEditorContainer.scrollTop = 0;
      }
      _historyReset(markdown);
    };

    wysiwygEditor._historyApplyContent = function (markdown) {
      textarea.value = markdown;
      var parsed = parseFrontmatter(markdown);
      wysiwygEditor._liveWysiwygFrontmatter = parsed.frontmatter;
      if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
        var html = wysiwygEditor._markdownToHtml(parsed.body);
        wysiwygEditor.editableArea.innerHTML = html;
      } else if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
        wysiwygEditor.markdownArea.value = markdown;
        if (wysiwygEditor._updateMarkdownLineNumbers) wysiwygEditor._updateMarkdownLineNumbers();
      }
      if (_pristineContent !== null && !isFocusModeActive) {
        var changed = markdown !== _pristineContent;
        if (_upstreamSaveBtn) {
          if (changed) _upstreamSaveBtn.classList.remove('live-edit-hidden');
          else _upstreamSaveBtn.classList.add('live-edit-hidden');
        }
        if (_upstreamCancelBtn) {
          if (changed) _upstreamCancelBtn.classList.remove('live-edit-hidden');
          else _upstreamCancelBtn.classList.add('live-edit-hidden');
        }
      }
      if (isFocusModeActive && _focusOverlay && _focusOverlay._updateSaveDiscard) {
        _focusOverlay._updateSaveDiscard();
      }
    };

    _historyReset(initialValue);

    (function attachHistoryListeners() {
      var ea = wysiwygEditor.editableArea;
      var ma = wysiwygEditor.markdownArea;
      if (ea && !ea.dataset.liveWysiwygHistoryAttached) {
        ea.dataset.liveWysiwygHistoryAttached = '1';
        ea.addEventListener('input', function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var immediate = false;
          if (e.inputType === 'insertText' && e.data) {
            if (/[\s.,;:!?\-=+(){}[\]<>\/\\|@#$%^&*~`"']/.test(e.data)) immediate = true;
          } else if (e.inputType === 'insertParagraph' || e.inputType === 'insertLineBreak') {
            immediate = true;
          } else if (e.inputType === 'insertFromPaste' || e.inputType === 'insertFromDrop') {
            immediate = true;
          } else if (e.inputType && e.inputType.indexOf('format') === 0) {
            immediate = true;
          } else if (e.inputType && e.inputType.indexOf('delete') === 0) {
            immediate = true;
          }
          _scheduleHistoryCapture(immediate);
        });
      }
      if (ma && !ma.dataset.liveWysiwygHistoryAttached) {
        ma.dataset.liveWysiwygHistoryAttached = '1';
        ma.addEventListener('input', function () {
          if (wysiwygEditor.currentMode !== 'markdown') return;
          _scheduleHistoryCapture(false);
        });
        ma.addEventListener('keydown', function (e) {
          if (wysiwygEditor.currentMode !== 'markdown') return;
          if (e.key === ' ' || e.key === 'Enter' || /^[.,;:!?\-=+(){}[\]<>\/\\|@#$%^&*~`"']$/.test(e.key)) {
            _scheduleHistoryCapture(true);
          }
        });
      }
    })();

    (function () {
      var ma = wysiwygEditor.markdownArea;
      if (ma && !ma.dataset.liveWysiwygBlurAttached) {
        ma.dataset.liveWysiwygBlurAttached = '1';
        ma.addEventListener('blur', function () {
          capturedMarkdownSelection = { start: ma.selectionStart, end: ma.selectionEnd };
        });
      }
    })();

    (function attachNavTitleSync() {
      var ma = wysiwygEditor.markdownArea;
      if (!ma || ma.dataset.liveWysiwygNavTitleSync) return;
      ma.dataset.liveWysiwygNavTitleSync = '1';
      var renderTimer = null;
      var snapshotTimer = null;
      var lastTitle = '';
      ma.addEventListener('input', function () {
        clearTimeout(renderTimer);
        clearTimeout(snapshotTimer);
        renderTimer = setTimeout(function () {
          var parsed = parseFrontmatter(ma.value);
          if (!parsed.frontmatter) return;
          var titleMatch = parsed.frontmatter.match(/^title:\s*(.+)$/m);
          var title = titleMatch ? titleMatch[1].replace(/^['"]|['"]$/g, '').trim() : '';
          if (title && title !== lastTitle) {
            lastTitle = title;
            var navItem = _findNavItemByPath(_getCurrentSrcPath());
            if (navItem) { navItem.title = title; _renderNavFromSnapshot(); }
            _refreshFocusTitle(title);
          }
        }, 100);
        snapshotTimer = setTimeout(function () {
          var parsed = parseFrontmatter(ma.value);
          if (!parsed.frontmatter) return;
          var titleMatch = parsed.frontmatter.match(/^title:\s*(.+)$/m);
          var title = titleMatch ? titleMatch[1].replace(/^['"]|['"]$/g, '').trim() : '';
          if (title) {
            var navItem = _findNavItemByPath(_getCurrentSrcPath());
            if (navItem && navItem.title === title) _commitNavSnapshot();
          }
        }, 1000);
      });
    })();

    (function attachNavWeightSync() {
      var ma = wysiwygEditor.markdownArea;
      if (!ma || ma.dataset.liveWysiwygNavWeightSync) return;
      ma.dataset.liveWysiwygNavWeightSync = '1';
      var renderTimer = null;
      var snapshotTimer = null;
      var lastWeight = null;
      ma.addEventListener('input', function () {
        clearTimeout(renderTimer);
        clearTimeout(snapshotTimer);
        renderTimer = setTimeout(function () {
          if (typeof liveWysiwygNavData === 'undefined') return;
          var parsed = parseFrontmatter(ma.value);
          if (!parsed.frontmatter) return;
          var weightMatch = parsed.frontmatter.match(/^weight:\s*(-?\d+(?:\.\d+)?)$/m);
          if (!weightMatch) return;
          var w = parseFloat(weightMatch[1]);
          if (isNaN(w) || w === lastWeight) return;
          lastWeight = w;
          var srcPath = _getCurrentSrcPath();
          if (!srcPath) return;
          var navItem = _findNavItemByPath(srcPath);
          if (!navItem) {
            navItem = _findSectionByIndexPath(liveWysiwygNavData, srcPath);
          }
          if (navItem) { _setItemWeight(navItem, w); _renderNavFromSnapshot(); }
        }, 300);
        snapshotTimer = setTimeout(function () {
          if (typeof liveWysiwygNavData === 'undefined') return;
          var parsed = parseFrontmatter(ma.value);
          if (!parsed.frontmatter) return;
          var weightMatch = parsed.frontmatter.match(/^weight:\s*(-?\d+(?:\.\d+)?)$/m);
          if (!weightMatch) return;
          var w = parseFloat(weightMatch[1]);
          if (isNaN(w)) return;
          var srcPath = _getCurrentSrcPath();
          if (!srcPath) return;
          var navItem = _findNavItemByPath(srcPath);
          if (!navItem) navItem = _findSectionByIndexPath(liveWysiwygNavData, srcPath);
          if (navItem) _commitNavSnapshot();
        }, 1000);
      });
    })();

    (function () {
      var linkBtn = wysiwygEditor.toolbar && wysiwygEditor.toolbar.querySelector('.md-toolbar-button-link');
      if (linkBtn && !linkBtn.dataset.liveWysiwygLinkMousedownAttached) {
        linkBtn.dataset.liveWysiwygLinkMousedownAttached = '1';
        linkBtn.addEventListener('mousedown', function () {
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
            var ea = wysiwygEditor.editableArea;
            if (document.activeElement === ea) {
              var sel = window.getSelection();
              if (sel && sel.rangeCount > 0 && ea.contains(sel.getRangeAt(0).commonAncestorContainer)) {
                wysiwygEditor.savedRangeInfo = sel.getRangeAt(0).cloneRange();
              }
            }
          } else if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
            var ma = wysiwygEditor.markdownArea;
            if (document.activeElement === ma) {
              wysiwygEditor.savedRangeInfo = { start: ma.selectionStart, end: ma.selectionEnd };
            }
          }
        });
      }
    })();

    (function () {
      var imgBtn = wysiwygEditor.toolbar && wysiwygEditor.toolbar.querySelector('.md-toolbar-button-image');
      if (imgBtn && !imgBtn.dataset.liveWysiwygImageMousedownAttached) {
        imgBtn.dataset.liveWysiwygImageMousedownAttached = '1';
        imgBtn.addEventListener('mousedown', function () {
          if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
            var ea = wysiwygEditor.editableArea;
            if (document.activeElement === ea) {
              var sel = window.getSelection();
              if (sel && sel.rangeCount > 0 && ea.contains(sel.getRangeAt(0).commonAncestorContainer)) {
                wysiwygEditor.savedRangeInfo = sel.getRangeAt(0).cloneRange();
              }
            }
          } else if (wysiwygEditor.currentMode === 'markdown' && wysiwygEditor.markdownArea) {
            var ma = wysiwygEditor.markdownArea;
            if (document.activeElement === ma) {
              wysiwygEditor.savedRangeInfo = { start: ma.selectionStart, end: ma.selectionEnd };
            }
          }
        });
      }
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygAdmonitionTitleMousedownAttached) {
        ea.dataset.liveWysiwygAdmonitionTitleMousedownAttached = '1';
        ea.addEventListener('mousedown', function () {
          var sel = window.getSelection();
          if (!sel || !sel.rangeCount) return;
          var titleEl = findTitleFromNode(sel.anchorNode, ea);
          if (titleEl) restoreEmptyAdmonitionTitle(titleEl);
        });
      }
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygChecklistInputAttached) {
        ea.dataset.liveWysiwygChecklistInputAttached = '1';
        ea.addEventListener('input', function () {
          ensureChecklistNewItems(ea);
          fixMalformedNestedLists(ea);
        });
      }
    })();

    var _ekh = {};

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
      _ekh.checklistBackspace = function (e) {
          if (e.key !== 'Backspace') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var range = sel.getRangeAt(0);
          var node = range.startContainer;
          var offset = range.startOffset;

          var li = node;
          while (li && li !== ea) {
            if (li.nodeName === 'LI') break;
            li = li.parentNode;
          }
          if (!li || li.nodeName !== 'LI') return;
          var cb = li.querySelector('input[type="checkbox"]');
          if (!cb) return;

          var posFirst = getFirstContentPosition(li);
          if (!posFirst) return;
          var firstRange = document.createRange();
          firstRange.setStart(posFirst.node, posFirst.offset);
          firstRange.collapse(true);
          var cmp = range.compareBoundaryPoints(Range.START_TO_START, firstRange);
          if (cmp > 0) return;
          var text = (li.textContent || '').replace(/[​‌‍﻿]/g, '').replace(/[\s ]/g, '');
          var isEmpty = text.length === 0;

          e.preventDefault();
          if (isEmpty) {
            var list = li.parentNode;
            var prevLi = li.previousElementSibling;
            var nextLi = li.nextElementSibling;
            list.removeChild(li);
            if (list.childNodes.length === 0 && list.parentNode && list.parentNode.nodeName === 'LI') {
              list.parentNode.removeChild(list);
            }
            var newRange = document.createRange();
            if (prevLi && prevLi.nodeName === 'LI') {
              newRange.selectNodeContents(prevLi);
              newRange.collapse(false);
            } else if (nextLi && nextLi.nodeName === 'LI') {
              var nextPos = getFirstContentPosition(nextLi);
              if (nextPos) {
                newRange.setStart(nextPos.node, nextPos.offset);
                newRange.collapse(true);
              } else {
                newRange.selectNodeContents(nextLi);
                newRange.collapse(true);
              }
            } else {
              var p = document.createElement('p');
              p.innerHTML = '<br>';
              if (list.nextSibling) {
                list.parentNode.insertBefore(p, list.nextSibling);
              } else {
                list.parentNode.appendChild(p);
              }
              list.parentNode.removeChild(list);
              newRange.setStart(p, 0);
              newRange.collapse(true);
            }
            sel.removeAllRanges();
            sel.addRange(newRange);
          } else {
            removeCheckboxFromLi(li);
          }
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
      };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygChecklistCursorNormAttached) {
        ea.dataset.liveWysiwygChecklistCursorNormAttached = '1';
        function normalizeChecklistCursor() {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var range = sel.getRangeAt(0);
          var node = range.startContainer;
          if (node.nodeType === 3) node = node.parentNode;
          var li = node;
          while (li && li !== ea) {
            if (li.nodeName === 'LI') break;
            li = li.parentNode;
          }
          if (!li || li.nodeName !== 'LI') return;
          var cb = getDirectCheckboxOfLi(li);
          if (!cb) return;
          var pos = getFirstContentPosition(li);
          if (!pos) return;
          var firstRange = document.createRange();
          firstRange.setStart(pos.node, pos.offset);
          firstRange.collapse(true);
          var cmp = range.compareBoundaryPoints(Range.START_TO_START, firstRange);
          if (cmp >= 0) return;
          var newRange = document.createRange();
          newRange.setStart(pos.node, pos.offset);
          newRange.collapse(true);
          sel.removeAllRanges();
          sel.addRange(newRange);
        }
        ea.addEventListener('mouseup', function () {
          setTimeout(normalizeChecklistCursor, 0);
        });
        ea.addEventListener('focus', function () {
          setTimeout(normalizeChecklistCursor, 0);
        });
        _ekh.checklistCursorNorm = function (e) {
          if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') setTimeout(normalizeChecklistCursor, 0);
        };
      }
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
      _ekh.checklistArrow = function (e) {
          if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var range = sel.getRangeAt(0);
          var node = range.startContainer;
          if (node.nodeType === 3) node = node.parentNode;
          var block = node;
          while (block && block !== ea) {
            if (block.nodeName === 'LI' || block.nodeName === 'P' || (block.nodeName.match && block.nodeName.match(/^H[1-6]$/))) break;
            block = block.parentNode;
          }
          if (!block || block === ea) return;
          if (e.key === 'ArrowLeft') {
            var atStart = false;
            var prevBlock = null;
            var cameFromParent = false;
            if (block.nodeName === 'LI') {
              var cb = getDirectCheckboxOfLi(block);
              if (!cb) return;
              var pos = getFirstContentPosition(block);
              if (!pos) return;
              var firstRange = document.createRange();
              firstRange.setStart(pos.node, pos.offset);
              firstRange.collapse(true);
              var cmp = range.compareBoundaryPoints(Range.START_TO_START, firstRange);
              if (cmp !== 0) return;
              atStart = true;
              var prev = block.previousElementSibling;
              if (!prev && block.parentNode && (block.parentNode.nodeName === 'UL' || block.parentNode.nodeName === 'OL')) {
                var listParent = block.parentNode.parentNode;
                if (listParent && listParent.nodeName === 'LI') {
                  prev = listParent;
                  cameFromParent = true;
                } else {
                  prev = block.parentNode.previousElementSibling;
                }
              }
              prevBlock = prev;
              if (prev && (prev.nodeName === 'UL' || prev.nodeName === 'OL') && prev.lastElementChild && prev.lastElementChild.nodeName === 'LI') prevBlock = prev.lastElementChild;
            } else if (block.nodeName === 'P' || (block.nodeName.match && block.nodeName.match(/^H[1-6]$/))) {
              var startRange = document.createRange();
              startRange.selectNodeContents(block);
              startRange.collapse(true);
              atStart = range.compareBoundaryPoints(Range.START_TO_START, startRange) === 0;
              if (!atStart) return;
              prevBlock = block.previousElementSibling;
            }
            if (atStart && prevBlock && (prevBlock.nodeName === 'LI' || prevBlock.nodeName === 'P' || (prevBlock.nodeName.match && prevBlock.nodeName.match(/^H[1-6]$/)))) {
              e.preventDefault();
              var newRange = document.createRange();
              if (prevBlock.nodeName === 'LI' && prevBlock.querySelector('ul, ol')) {
                if (cameFromParent) {
                  var lastPos = getLastContentPositionBeforeNestedList(prevBlock);
                  if (lastPos) {
                    newRange.setStart(lastPos.node, lastPos.offset);
                    newRange.collapse(true);
                  } else {
                    newRange.selectNodeContents(prevBlock);
                    newRange.collapse(false);
                  }
                } else {
                  var leaf = getLastLeafLi(prevBlock);
                  newRange.selectNodeContents(leaf);
                  newRange.collapse(false);
                }
              } else {
                newRange.selectNodeContents(prevBlock);
                newRange.collapse(false);
              }
              sel.removeAllRanges();
              sel.addRange(newRange);
            }
          } else {
            var endRange = document.createRange();
            endRange.selectNodeContents(block);
            endRange.collapse(false);
            var atEnd = range.compareBoundaryPoints(Range.START_TO_END, endRange) === 0;
            var lastBeforeNested = block.nodeName === 'LI' ? getLastContentPositionBeforeNestedList(block) : null;
            var atEndOfDirectContent = lastBeforeNested && (function() {
              var r = document.createRange();
              r.setStart(lastBeforeNested.node, lastBeforeNested.offset);
              r.collapse(true);
              return range.compareBoundaryPoints(Range.START_TO_END, r) === 0;
            })();
            if (!atEnd && !atEndOfDirectContent) return;
            var nextLi = null;
            if (atEndOfDirectContent && block.nodeName === 'LI') {
              var nested = null;
            for (var c = block.firstChild; c; c = c.nextSibling) {
              if (c.nodeName === 'UL' || c.nodeName === 'OL') { nested = c; break; }
            }
              if (nested && nested.firstElementChild && nested.firstElementChild.nodeName === 'LI') nextLi = nested.firstElementChild;
            }
            if (!nextLi && atEnd) {
              var next = block.nextElementSibling;
              if (!next && block.parentNode && (block.parentNode.nodeName === 'UL' || block.parentNode.nodeName === 'OL')) next = block.parentNode.parentNode ? block.parentNode.parentNode.nextElementSibling : null;
              if (next && next.nodeName === 'LI') nextLi = next;
              else if (next && (next.nodeName === 'UL' || next.nodeName === 'OL') && next.firstElementChild && next.firstElementChild.nodeName === 'LI') nextLi = next.firstElementChild;
            }
            if (nextLi) {
              var nextPos = getFirstContentPosition(nextLi);
              if (nextPos) {
                e.preventDefault();
                var newRange = document.createRange();
                newRange.setStart(nextPos.node, nextPos.offset);
                newRange.collapse(true);
                sel.removeAllRanges();
                sel.addRange(newRange);
              }
            }
          }
      };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygPasteAttached) {
        ea.dataset.liveWysiwygPasteAttached = '1';
        var urlRe = /^https?:\/\/\S+$/;
        ea.addEventListener('paste', function (e) {
          var sel = window.getSelection();
          if (!sel || sel.isCollapsed || !sel.rangeCount) return;
          var pasted = (e.clipboardData || window.clipboardData).getData('text');
          if (!pasted || !urlRe.test(pasted.trim())) return;
          _flushHistoryCapture();
          e.preventDefault();
          var url = pasted.trim();
          document.execCommand('createLink', false, url);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        }, true);
      }
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygImagePasteAttached) {
        ea.dataset.liveWysiwygImagePasteAttached = '1';
        var imgExtRe = /\.(png|jpe?g|gif|svg|webp|bmp|ico|avif|tiff?)(\?[^\s]*)?$/i;
        ea.addEventListener('paste', function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var pasted = (e.clipboardData || window.clipboardData).getData('text');
          if (!pasted) return;
          _flushHistoryCapture();
          var url = pasted.trim();
          if (!imgExtRe.test(url)) return;

          var range = sel.getRangeAt(0);
          var node = range.startContainer;
          if (node.nodeType === Node.TEXT_NODE) node = node.parentNode;
          var block = node;
          var blockTags = { P: 1, DIV: 1 };
          while (block && block !== ea && !blockTags[block.nodeName]) {
            block = block.parentNode;
          }
          if (!block || block === ea) return;
          var blockText = (block.textContent || '').replace(/[\u200B\u00A0\s]/g, '');
          if (blockText.length > 0) return;

          e.preventDefault();
          e.stopImmediatePropagation();

          var pathPart = url.split('?')[0];
          var fileName = pathPart.split('/').pop() || '';
          var altText = fileName.replace(/\.[^.]+$/, '').replace(/[-_]/g, ' ');

          var resolved = resolveImageSrc(url);
          var origSrc = (resolved !== url) ? url : null;
          var relConverted = _tryConvertToRelativeImageUrl(url);
          if (relConverted !== null) {
            origSrc = relConverted;
            resolved = resolveImageSrc(relConverted);
          }

          var img = document.createElement('img');
          img.src = resolved;
          img.alt = altText;
          if (origSrc) img.setAttribute('data-orig-src', origSrc);

          img.setAttribute('data-size-syntax', _getSetting('live_wysiwyg_image_attr_syntax') === '0' ? 'html' : 'attr');

          block.innerHTML = '';
          block.appendChild(img);

          var pAfter = document.createElement('p');
          pAfter.innerHTML = '\u200B';
          block.parentNode.insertBefore(pAfter, block.nextSibling);

          var newRange = document.createRange();
          newRange.setStart(pAfter, pAfter.childNodes.length > 0 ? 1 : 0);
          newRange.collapse(true);
          sel.removeAllRanges();
          sel.addRange(newRange);

          if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
          if (typeof enhanceImages === 'function') enhanceImages(ea);
        }, true);
      }
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygInlineCodeAttached) {
        ea.dataset.liveWysiwygInlineCodeAttached = '1';
        var pendingBacktick = null;

        function clearPending() { pendingBacktick = null; }

        ea.addEventListener('blur', clearPending);
        _ekh.inlineCodeClear = function (e) {
          if (e.key === 'Escape' || e.key === 'Enter' ||
              e.key.indexOf('Arrow') === 0 ||
              e.key === 'Home' || e.key === 'End' ||
              e.key === 'PageUp' || e.key === 'PageDown') {
            clearPending();
          }
        };

        function doConvert(anchorNode, openingIdx, closingIdx, sel, isDouble) {
          var text = anchorNode.textContent;
          var inner, literal;
          if (isDouble) {
            inner = text.substring(openingIdx + 3, closingIdx - 2);
            literal = '`` ' + inner + ' ``';
          } else {
            inner = text.substring(openingIdx + 1, closingIdx);
            literal = '`' + inner + '`';
          }
          if (inner.length === 0) return false;
          if (inner.charAt(0) === ' ' || inner.charAt(inner.length - 1) === ' ') return false;

          var before = text.substring(0, openingIdx);
          var after = text.substring(closingIdx + 1);

          var codeEl = document.createElement('code');
          codeEl.textContent = inner;
          codeEl.setAttribute('data-md-literal', literal);

          var parentNode = anchorNode.parentNode;
          var afterNode = document.createTextNode('\u200B' + after);

          if (before) {
            anchorNode.textContent = before;
            parentNode.insertBefore(codeEl, anchorNode.nextSibling);
            parentNode.insertBefore(afterNode, codeEl.nextSibling);
          } else {
            parentNode.insertBefore(codeEl, anchorNode);
            parentNode.insertBefore(afterNode, codeEl.nextSibling);
            parentNode.removeChild(anchorNode);
          }

          var range = document.createRange();
          range.setStart(afterNode, 1);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);

          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
          return true;
        }

        ea.addEventListener('input', function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          if (e.inputType !== 'insertText' || e.data !== '`') return;

          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var anchorNode = sel.anchorNode;
          var anchorOffset = sel.anchorOffset;
          if (!anchorNode || anchorNode.nodeType !== 3) return;

          var anc = anchorNode.parentNode;
          while (anc && anc !== ea) {
            var tag = anc.nodeName;
            if (tag === 'PRE' || tag === 'CODE') return;
            anc = anc.parentNode;
          }

          var text = anchorNode.textContent;
          var closingIdx = anchorOffset - 1;
          if (closingIdx < 0 || text.charAt(closingIdx) !== '`') return;
          if (closingIdx > 0 && text.charAt(closingIdx - 1) === '`') {
            if (pendingBacktick && pendingBacktick.node === anchorNode && pendingBacktick.offset === closingIdx - 1) {
              pendingBacktick = { node: anchorNode, offset: closingIdx - 1, isDouble: true };
              return;
            }
            if (pendingBacktick && pendingBacktick.isDouble && pendingBacktick.node === anchorNode &&
                text.substring(pendingBacktick.offset, pendingBacktick.offset + 3) === '`` ' &&
                closingIdx >= pendingBacktick.offset + 6 && text.substring(closingIdx - 2, closingIdx + 1) === ' ``') {
              var openingIdx = pendingBacktick.offset;
              clearPending();
              if (doConvert(anchorNode, openingIdx, closingIdx, sel, true)) return;
              return;
            }
            clearPending();
            return;
          }

          if (pendingBacktick && pendingBacktick.isDouble && pendingBacktick.node === anchorNode) return;

          if (pendingBacktick && pendingBacktick.node === anchorNode && !pendingBacktick.isDouble) {
            var pIdx = pendingBacktick.offset;
            if (pIdx >= 0 && pIdx < closingIdx && text.charAt(pIdx) === '`') {
              clearPending();
              if (doConvert(anchorNode, pIdx, closingIdx, sel)) return;
              return;
            }
          }

          pendingBacktick = { node: anchorNode, offset: closingIdx };
        });
      }
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygTripleBacktickAttached) {
        ea.dataset.liveWysiwygTripleBacktickAttached = '1';
        ea.addEventListener('input', function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          if (e.inputType !== 'insertText' || e.data !== '`') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var anchorNode = sel.anchorNode;
          var anchorOffset = sel.anchorOffset;
          if (!anchorNode || anchorNode.nodeType !== 3) return;
          var anc = anchorNode.parentNode;
          while (anc && anc !== ea) {
            if (anc.nodeName === 'PRE' || anc.nodeName === 'CODE') return;
            anc = anc.parentNode;
          }
          var text = anchorNode.textContent;
          if (anchorOffset < 3) return;
          var segment = text.substring(anchorOffset - 3, anchorOffset);
          if (segment !== '```') return;
          var lineStart = text.lastIndexOf('\n', anchorOffset - 3) + 1;
          var beforeInLine = text.substring(lineStart, anchorOffset - 3);
          if (beforeInLine.trim().length > 0) return;
          e.preventDefault && e.preventDefault();
          var parentBlock = anchorNode.parentNode;
          while (parentBlock && parentBlock !== ea && parentBlock.parentNode !== ea) {
            parentBlock = parentBlock.parentNode;
          }
          if (!parentBlock || parentBlock === ea) parentBlock = anchorNode.parentNode;
          var insertParent = ea;
          var targetBlock = parentBlock;
          var anc = anchorNode.parentNode;
          while (anc && anc !== ea) {
            var inLi = anc.nodeName === 'LI' && anc.parentNode && (anc.parentNode.nodeName === 'UL' || anc.parentNode.nodeName === 'OL');
            if ((anc.classList && anc.classList.contains('admonition')) || anc.nodeName === 'BLOCKQUOTE' || inLi) {
              insertParent = anc;
              var inner = anchorNode.parentNode;
              while (inner && inner !== anc && inner.parentNode !== anc) {
                inner = inner.parentNode;
              }
              if (inner && inner !== anc && inner.parentNode === anc) {
                targetBlock = inner;
              }
              break;
            }
            anc = anc.parentNode;
          }
          var pre = document.createElement('pre');
          pre.setAttribute('data-md-literal', '```');
          var code = document.createElement('code');
          code.textContent = '\n';
          pre.appendChild(code);
          if (targetBlock && targetBlock.parentNode === insertParent) {
            insertParent.insertBefore(pre, targetBlock);
            insertParent.removeChild(targetBlock);
          } else {
            ea.appendChild(pre);
          }
          enhanceCodeBlocks(ea);
          enhanceBasicPreBlocks(ea);
          populateRawHtmlBlocks(ea);
          enhanceAdmonitions(ea);
          enhanceImages(ea);
          requestAnimationFrame(function () {
            var codeEl = pre.querySelector('code') || pre;
            var textNode = codeEl.firstChild;
            if (!textNode || textNode.nodeType !== 3) {
              textNode = document.createTextNode('\n');
              codeEl.appendChild(textNode);
            }
            var range = document.createRange();
            range.setStart(textNode, 0);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            ea.focus();
          });
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        }, true);
      }

    (function emojiShortcodeSupport() {
      var EMOJI_MAP = (typeof liveWysiwygEmojiMap !== "undefined" ? liveWysiwygEmojiMap : {});
      var shortcodeRe = /:([a-z0-9_+-]+):/g;
      var EMOJI_KEYS = Object.keys(EMOJI_MAP);
      var MAX_SUGGESTIONS = 8;

      function getTextBeforeCursor(sel, ea) {
        if (!sel || !sel.rangeCount) return { text: "", node: null, offset: 0 };
        var r = sel.getRangeAt(0);
        var node = r.startContainer;
        var offset = r.startOffset;
        if (node.nodeType === 3) {
          return { text: node.textContent.substring(0, offset), node: node, offset: offset };
        }
        return { text: "", node: null, offset: 0 };
      }

      function replaceRangeWithEmoji(node, startOffset, endOffset, emoji, shortcode) {
        if (!node || node.nodeType !== 3) return false;
        var text = node.textContent;
        var before = text.substring(0, startOffset);
        var after = text.substring(endOffset);
        if (!shortcode) {
          node.textContent = before + emoji + after;
          return true;
        }
        var parent = node.parentNode;
        if (!parent) return false;
        var el;
        if (typeof window.liveWysiwygEmojiToImgHtml === "function") {
          var tmp = document.createElement("div");
          tmp.innerHTML = window.liveWysiwygEmojiToImgHtml(shortcode, emoji);
          el = tmp.firstChild;
        } else {
          el = document.createElement("span");
          el.setAttribute("data-emoji-shortcode", shortcode);
          el.textContent = emoji;
        }
        var beforeNode = document.createTextNode(before);
        var afterNode = document.createTextNode(after);
        parent.insertBefore(afterNode, node.nextSibling);
        parent.insertBefore(el, afterNode);
        parent.insertBefore(beforeNode, node);
        parent.removeChild(node);
        return el;
      }

      function fuzzyMatch(needle, haystack) {
        var n = needle.toLowerCase();
        var h = haystack.toLowerCase();
        var j = 0;
        for (var i = 0; i < n.length; i++) {
          j = h.indexOf(n[i], j);
          if (j === -1) return false;
          j++;
        }
        return true;
      }
      function showEmojiAutocomplete(ea, prefix, anchorRect, onSelect) {
        var limit = prefix.length === 0 ? EMOJI_KEYS.length : MAX_SUGGESTIONS;
        var matches = EMOJI_KEYS.filter(function (k) {
          return prefix.length === 0 || k.indexOf(prefix) >= 0 || fuzzyMatch(prefix, k);
        }).sort(function (a, b) {
          if (prefix.length === 0) return 0;
          var aPrefix = a.indexOf(prefix) === 0 ? 0 : (a.indexOf(prefix) >= 0 ? 100 : 200);
          var bPrefix = b.indexOf(prefix) === 0 ? 0 : (b.indexOf(prefix) >= 0 ? 100 : 200);
          if (aPrefix !== bPrefix) return aPrefix - bPrefix;
          return (a.indexOf(prefix) >= 0 ? a.indexOf(prefix) : 999) - (b.indexOf(prefix) >= 0 ? b.indexOf(prefix) : 999);
        }).slice(0, limit);
        if (matches.length === 0 && prefix.length === 0) return null;
        var pop = document.createElement("div");
        pop.className = "live-wysiwyg-emoji-autocomplete";
        pop.style.cssText = "position:fixed;z-index:99999;background:var(--md-default-bg-color, #fff);border:1px solid var(--md-default-fg-color--lighter, #ccc);border-radius:6px;box-shadow:var(--md-shadow-z2, 0 4px 12px rgba(0,0,0,0.15));max-height:" + (matches.length > 12 ? "320px" : "240px") + ";overflow-y:auto;font-family:inherit;font-size:14px;";
        if (matches.length === 0) {
          var noMatchRow = document.createElement("div");
          noMatchRow.className = "live-wysiwyg-emoji-no-matches";
          noMatchRow.style.cssText = "padding:6px 12px;color:var(--md-default-fg-color--lighter, #999);";
          noMatchRow.textContent = "No matches";
          pop.appendChild(noMatchRow);
        }
        matches.forEach(function (key, i) {
          var row = document.createElement("div");
          row.className = "live-wysiwyg-emoji-item" + (i === 0 ? " live-wysiwyg-emoji-selected" : "");
          row.style.cssText = "padding:6px 12px;cursor:pointer;display:flex;align-items:center;gap:8px;white-space:nowrap;";
          if (i === 0) row.style.background = "var(--md-accent-fg-color--transparent, #e3f2fd)";
          row.dataset.key = key;
          row.innerHTML = "<span style=\"font-size:1.2em\">" + EMOJI_MAP[key] + "</span><span style=\"color:var(--md-default-fg-color--light, #666)\">:" + key + ":</span>";
          row.addEventListener("mouseenter", function () {
            pop.querySelectorAll(".live-wysiwyg-emoji-selected").forEach(function (el) { el.classList.remove("live-wysiwyg-emoji-selected"); el.style.background = ""; });
            row.classList.add("live-wysiwyg-emoji-selected");
            row.style.background = "var(--md-accent-fg-color--transparent, #e3f2fd)";
          });
          row.addEventListener("click", function (e) {
            e.preventDefault();
            if (pop._closeHandler) document.removeEventListener("mousedown", pop._closeHandler);
            onSelect(key);
            if (pop.parentNode) pop.parentNode.removeChild(pop);
          });
          pop.appendChild(row);
        });
        document.body.appendChild(pop);
        var rect = anchorRect || { left: 0, bottom: 20 };
        pop.style.left = rect.left + "px";
        pop.style.top = (rect.bottom + 4) + "px";
        var closeHandler = function (e) {
          if (pop.parentNode && !pop.contains(e.target)) {
            pop.parentNode.removeChild(pop);
            document.removeEventListener("mousedown", closeHandler);
          }
        };
        setTimeout(function () { document.addEventListener("mousedown", closeHandler); }, 0);
        pop._closeHandler = closeHandler;
        return { pop: pop, matches: matches, onSelect: onSelect };
      }

      function attachEmojiSupport(ea) {
        if (!ea || ea.dataset.liveWysiwygEmojiAttached) return;
        ea.dataset.liveWysiwygEmojiAttached = "1";
        var autocompleteState = null;

        ea.addEventListener("input", function (e) {
          if (wysiwygEditor.currentMode !== "wysiwyg") return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var anc = sel.anchorNode;
          if (anc.nodeType === 3) anc = anc.parentNode;
          while (anc && anc !== ea) {
            if (anc.nodeName === "PRE" || anc.nodeName === "CODE") return;
            anc = anc.parentNode;
          }
          var info = getTextBeforeCursor(sel, ea);
          var text = info.text;
          var node = sel.anchorNode;
          var offset = sel.anchorOffset;
          if (node.nodeType !== 3) return;

          var lastColon = text.lastIndexOf(":");
          if (lastColon >= 0 && !(text.charAt(lastColon + 1) === '/' && text.charAt(lastColon + 2) === '/')) {
            var openColon = lastColon > 0 ? text.lastIndexOf(":", lastColon - 1) : -1;
            if (openColon >= 0 && text.charAt(openColon + 1) === '/' && text.charAt(openColon + 2) === '/') openColon = -1;
            var between = openColon >= 0 ? text.substring(openColon + 1, lastColon) : text.substring(lastColon + 1);
            if (e.inputType === "insertText" && e.data === ":") {
              var shortcode = between;
              if (shortcode.indexOf(" ") < 0 && shortcode.indexOf(":") < 0) {
                var emoji = EMOJI_MAP[shortcode];
                if (emoji) {
                  e.preventDefault();
                  var start = openColon >= 0 ? openColon : lastColon;
                  var repl = replaceRangeWithEmoji(node, start, offset, emoji, ":" + shortcode + ":");
                  ea.focus();
                  sel.removeAllRanges();
                  var range = document.createRange();
                  if (repl && repl.nodeType) {
                    range.setStartAfter(repl);
                    range.collapse(true);
                  } else {
                    range.setStart(node, start + emoji.length);
                    range.collapse(true);
                  }
                  sel.addRange(range);
                  if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
                  if (autocompleteState && autocompleteState.pop.parentNode) {
                    autocompleteState.pop.parentNode.removeChild(autocompleteState.pop);
                  }
                  autocompleteState = null;
                  return;
                }
              }
            }
            if (between.length >= 2 && /^[a-z0-9_+-]+$/i.test(between)) {
              var r = node.getBoundingClientRect ? node.getBoundingClientRect() : ea.getBoundingClientRect();
              var range = sel.getRangeAt(0);
              try {
                var cr = range.getBoundingClientRect();
                if (cr) r = cr;
              } catch (err) {}
              var anchorRect = { left: r.left, bottom: r.bottom };
              if (autocompleteState && autocompleteState.pop.parentNode) {
                autocompleteState.pop.parentNode.removeChild(autocompleteState.pop);
              }
              autocompleteState = showEmojiAutocomplete(ea, between, anchorRect, function (key) {
                var emoji = EMOJI_MAP[key];
                if (emoji) {
                  var repl = replaceRangeWithEmoji(node, lastColon, offset, emoji, ":" + key + ":");
                  ea.focus();
                  sel.removeAllRanges();
                  var range = document.createRange();
                  if (repl && repl.nodeType) {
                    range.setStartAfter(repl);
                    range.collapse(true);
                  } else {
                    range.setStart(node, lastColon + emoji.length);
                    range.collapse(true);
                  }
                  sel.addRange(range);
                }
                if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
                autocompleteState = null;
              });
            } else if (autocompleteState && autocompleteState.pop.parentNode) {
              autocompleteState.pop.parentNode.removeChild(autocompleteState.pop);
              autocompleteState = null;
            }
          }
        }, true);

        _ekh.emojiKey = function (e) {
          if ((e.ctrlKey || e.metaKey) && e.key === " ") {
            e.preventDefault();
            if (wysiwygEditor.currentMode !== "wysiwyg") return;
            var anc = ea.querySelector("*") || ea;
            var sel = window.getSelection();
            if (!sel || !sel.rangeCount) return;
            var anc2 = sel.anchorNode;
            if (anc2 && anc2.nodeType === 3) anc2 = anc2.parentNode;
            while (anc2 && anc2 !== ea) {
              if (anc2.nodeName === "PRE" || anc2.nodeName === "CODE") return;
              anc2 = anc2.parentNode;
            }
            var r = ea.getBoundingClientRect();
            try {
              var cr = sel.getRangeAt(0).getBoundingClientRect();
              if (cr) r = cr;
            } catch (err) {}
            var anchorRect = { left: r.left, bottom: r.bottom };
            if (autocompleteState && autocompleteState.pop.parentNode) {
              autocompleteState.pop.parentNode.removeChild(autocompleteState.pop);
            }
            var savedRange = sel.getRangeAt(0).cloneRange();
            var beforeCursor = getTextBeforeCursor(sel, ea);
            var removeColonOnly = beforeCursor.text.endsWith(" :") && beforeCursor.node && beforeCursor.node.nodeType === 3 && beforeCursor.offset >= 1;
            var state = showEmojiAutocomplete(ea, "", anchorRect, function (key) {
              var emoji = EMOJI_MAP[key];
              if (emoji) {
                var node = beforeCursor.node;
                var insertEnd = beforeCursor.offset;
                if (removeColonOnly && replaceRangeWithEmoji(node, beforeCursor.offset - 1, beforeCursor.offset, emoji)) {
                  insertEnd = beforeCursor.offset - 1 + emoji.length;
                } else {
                  sel.removeAllRanges();
                  sel.addRange(savedRange);
                  var el;
                  if (typeof window.liveWysiwygEmojiToImgHtml === "function") {
                    var tmp = document.createElement("div");
                    tmp.innerHTML = window.liveWysiwygEmojiToImgHtml(":" + key + ":", emoji);
                    el = tmp.firstChild;
                  } else {
                    el = document.createElement("span");
                    el.setAttribute("data-emoji-shortcode", ":" + key + ":");
                    el.textContent = emoji;
                  }
                  savedRange.deleteContents();
                  savedRange.insertNode(el);
                  var r = document.createRange();
                  r.setStartAfter(el);
                  r.collapse(true);
                  node = el.parentNode;
                  insertEnd = Array.prototype.indexOf.call(node.childNodes, el) + 1;
                }
                ea.focus();
                sel.removeAllRanges();
                var range = document.createRange();
                range.setStart(node, insertEnd);
                range.collapse(true);
                sel.addRange(range);
              }
              if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
              autocompleteState = null;
            });
            if (state) {
              state.ea = ea;
              state.anchorRect = anchorRect;
              state.filterPrefix = "";
              state.openedByCtrlSpace = true;
            }
            autocompleteState = state;
            return;
          }
          if (!autocompleteState || !autocompleteState.pop.parentNode) return;
          if (autocompleteState.openedByCtrlSpace && (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey || e.key === "Backspace")) {
            e.preventDefault();
            if (e.key === "Backspace") {
              autocompleteState.filterPrefix = autocompleteState.filterPrefix.slice(0, -1);
              if (autocompleteState.filterPrefix.length === 0) {
                if (autocompleteState.pop._closeHandler) document.removeEventListener("mousedown", autocompleteState.pop._closeHandler);
                if (autocompleteState.pop.parentNode) autocompleteState.pop.parentNode.removeChild(autocompleteState.pop);
                autocompleteState = null;
                return;
              }
            } else {
              autocompleteState.filterPrefix += e.key;
            }
            if (autocompleteState.pop._closeHandler) document.removeEventListener("mousedown", autocompleteState.pop._closeHandler);
            if (autocompleteState.pop.parentNode) autocompleteState.pop.parentNode.removeChild(autocompleteState.pop);
            var newState = showEmojiAutocomplete(autocompleteState.ea, autocompleteState.filterPrefix, autocompleteState.anchorRect, autocompleteState.onSelect);
            if (newState) {
              autocompleteState.pop = newState.pop;
              autocompleteState.matches = newState.matches;
              setTimeout(function () { document.addEventListener("mousedown", autocompleteState.pop._closeHandler); }, 0);
            } else {
              autocompleteState = null;
            }
            return;
          }
          if (e.key === "Escape") {
            e.preventDefault();
            if (autocompleteState.pop._closeHandler) document.removeEventListener("mousedown", autocompleteState.pop._closeHandler);
            if (autocompleteState.pop.parentNode) autocompleteState.pop.parentNode.removeChild(autocompleteState.pop);
            autocompleteState = null;
            return;
          }
          if (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Enter" || e.key === "Tab") {
            var sel = autocompleteState.pop.querySelector(".live-wysiwyg-emoji-selected");
            var items = autocompleteState.pop.querySelectorAll(".live-wysiwyg-emoji-item");
            var idx = Array.prototype.indexOf.call(items, sel);
            if (e.key === "ArrowDown" && idx < items.length - 1) {
              e.preventDefault();
              sel.classList.remove("live-wysiwyg-emoji-selected");
              sel.style.background = "";
              var next = items[idx + 1];
              next.classList.add("live-wysiwyg-emoji-selected");
              next.style.background = "#e3f2fd";
              next.scrollIntoView({ block: "nearest", behavior: "smooth" });
              return;
            }
            if (e.key === "ArrowUp" && idx > 0) {
              e.preventDefault();
              sel.classList.remove("live-wysiwyg-emoji-selected");
              sel.style.background = "";
              var prev = items[idx - 1];
              prev.classList.add("live-wysiwyg-emoji-selected");
              prev.style.background = "#e3f2fd";
              prev.scrollIntoView({ block: "nearest", behavior: "smooth" });
              return;
            }
            if ((e.key === "Enter" || e.key === "Tab") && sel) {
              e.preventDefault();
              e.stopPropagation();
              var key = sel.dataset.key;
              var pop = autocompleteState.pop;
              var onSelectCb = autocompleteState.onSelect;
              if (pop._closeHandler) document.removeEventListener("mousedown", pop._closeHandler);
              if (pop.parentNode) pop.parentNode.removeChild(pop);
              autocompleteState = null;
              if (key && onSelectCb) onSelectCb(key);
            }
          }
        };
      }

      var ea = wysiwygEditor.editableArea;
      if (ea) attachEmojiSupport(ea);
    })();

    })();

    (function markdownAutoConversions() {
      var ea = wysiwygEditor.editableArea;
      if (!ea || ea.dataset.liveWysiwygMdAutoAttached) return;
      ea.dataset.liveWysiwygMdAutoAttached = '1';

      function isInsidePreOrCode(node) {
        var anc = node.nodeType === 3 ? node.parentNode : node;
        while (anc && anc !== ea) {
          if (anc.nodeName === 'PRE' || anc.nodeName === 'CODE') return true;
          anc = anc.parentNode;
        }
        return false;
      }

      function getContainingBlock(node) {
        var cur = node.nodeType === 3 ? node.parentNode : node;
        while (cur) {
          if (cur === ea) return ea;
          var tag = cur.nodeName;
          if (tag === 'P' || tag === 'DIV' || tag === 'LI' || /^H[1-6]$/.test(tag)) return cur;
          cur = cur.parentNode;
        }
        return null;
      }

      function isFirstTextInBlock(textNode, block) {
        var walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, null, false);
        var n = walker.nextNode();
        while (n && n !== textNode && !n.textContent.replace(/[\u200B\u200C\u200D\uFEFF]/g, '')) {
          n = walker.nextNode();
        }
        return n === textNode;
      }

      function placeCursorIn(node, sel, atZws) {
        var target = node;
        if (target.nodeType !== 3) {
          target = node.firstChild;
          if (!target || target.nodeType !== 3) {
            target = document.createTextNode('\u200B');
            node.insertBefore(target, node.firstChild);
          }
        }
        var pos = atZws && target.textContent.charAt(0) === '\u200B' ? 1 : 0;
        var range = document.createRange();
        range.setStart(target, pos);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }

      function placeCursorAtEnd(node, sel) {
        var target = node.nodeType === 3 ? node : node.firstChild;
        if (!target || target.nodeType !== 3) return;
        var range = document.createRange();
        range.setStart(target, target.textContent.length);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }

      function placeCursorAfter(el, sel) {
        var afterNode = document.createTextNode('\u200B');
        if (el.nextSibling) {
          el.parentNode.insertBefore(afterNode, el.nextSibling);
        } else {
          el.parentNode.appendChild(afterNode);
        }
        var range = document.createRange();
        range.setStart(afterNode, 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }

      // ── Block-level conversions (triggered on space) ──

      var ZWS_RE = /[\u200B\u200C\u200D\uFEFF]/g;

      function isInvisible(ch) {
        return ch === '\u200B' || ch === '\u200C' || ch === '\u200D' || ch === '\uFEFF';
      }

      function countPrefixLen(raw, patternLen) {
        var consumed = 0;
        for (var i = 0; i < raw.length && consumed < patternLen; i++) {
          if (!isInvisible(raw.charAt(i))) consumed++;
        }
        return i;
      }

      function handleBlockConversions(anchorNode, anchorOffset, sel, spaceAlreadyInserted) {
        var block = getContainingBlock(anchorNode);
        if (!block) return false;
        var tag = block.nodeName;
        if (tag !== 'P' && tag !== 'DIV' && block !== ea) return false;
        if (!isFirstTextInBlock(anchorNode, block)) return false;

        var raw = anchorNode.textContent.substring(0, anchorOffset);
        var beforeCursor = raw.replace(ZWS_RE, '');

        var hm, olm, adMatch;
        var ADMONITION_TYPE_IDS = ['note', 'warning', 'danger', 'tip', 'hint', 'important', 'caution', 'error', 'attention', 'abstract', 'info', 'success', 'question', 'failure', 'bug', 'example', 'quote'];
        if (spaceAlreadyInserted) {
          hm = beforeCursor.match(/^(#{1,6}) $/);
          if (hm) return doHeading(anchorNode, block, hm[1].length, countPrefixLen(raw, hm[0].length), sel, hm[0]);
          if (beforeCursor === '> ') return doBlockquote(anchorNode, block, countPrefixLen(raw, 2), sel, '> ');
          if (/^!!!\s+details\s$/i.test(beforeCursor)) {
            return doAdmonition(anchorNode, block, countPrefixLen(raw, beforeCursor.length), sel, true, beforeCursor, 'note', true);
          }
          adMatch = beforeCursor.match(/^(!!!|\?\?\?\+?)\s+(\w+)\s$/);
          if (adMatch && ADMONITION_TYPE_IDS.indexOf(adMatch[2].toLowerCase()) >= 0) {
            return doAdmonition(anchorNode, block, countPrefixLen(raw, adMatch[0].length), sel, adMatch[1].indexOf('?') >= 0, beforeCursor, adMatch[2].toLowerCase());
          }
          adMatch = beforeCursor.match(/^(!!!|\?\?\?\+?)\s$/);
          if (adMatch) return doAdmonition(anchorNode, block, countPrefixLen(raw, adMatch[0].length), sel, adMatch[1].indexOf('?') >= 0, beforeCursor, 'note');
          if (beforeCursor === '- ' || beforeCursor === '* ') return doList(anchorNode, block, countPrefixLen(raw, 2), sel, 'ul', beforeCursor);
          if (beforeCursor === '- [ ] ' || beforeCursor === '* [ ] ' || beforeCursor === '+ [ ] ') return doList(anchorNode, block, countPrefixLen(raw, 6), sel, 'ul', beforeCursor, true, false);
          if (/^[-*+] \[[xX]\] $/.test(beforeCursor)) return doList(anchorNode, block, countPrefixLen(raw, 6), sel, 'ul', beforeCursor, true, true);
          olm = beforeCursor.match(/^(\d+)\. $/);
          if (olm) return doList(anchorNode, block, countPrefixLen(raw, olm[0].length), sel, 'ol', olm[0]);
        } else {
          hm = beforeCursor.match(/^(#{1,6})$/);
          if (hm) return doHeading(anchorNode, block, hm[1].length, countPrefixLen(raw, hm[0].length), sel, hm[0] + ' ');
          if (beforeCursor === '>') return doBlockquote(anchorNode, block, countPrefixLen(raw, 1), sel, '> ');
          if (/^!!!\s+details$/i.test(beforeCursor)) {
            return doAdmonition(anchorNode, block, countPrefixLen(raw, beforeCursor.length), sel, true, beforeCursor + ' ', 'note', true);
          }
          adMatch = beforeCursor.match(/^(!!!|\?\?\?\+?)\s+(\w+)$/);
          if (adMatch && ADMONITION_TYPE_IDS.indexOf(adMatch[2].toLowerCase()) >= 0) {
            return doAdmonition(anchorNode, block, countPrefixLen(raw, adMatch[0].length), sel, adMatch[1].indexOf('?') >= 0, beforeCursor + ' ', adMatch[2].toLowerCase());
          }
          adMatch = beforeCursor.match(/^(!!!|\?\?\?\+?)$/);
          if (adMatch) return doAdmonition(anchorNode, block, countPrefixLen(raw, adMatch[0].length), sel, adMatch[1].indexOf('?') >= 0, adMatch[1] + ' ', 'note');
          if (beforeCursor === '-' || beforeCursor === '*') return doList(anchorNode, block, countPrefixLen(raw, 1), sel, 'ul', beforeCursor + ' ');
          if (beforeCursor === '- [ ]' || beforeCursor === '* [ ]' || beforeCursor === '+ [ ]') return doList(anchorNode, block, countPrefixLen(raw, 5), sel, 'ul', beforeCursor + ' ', true, false);
          if (/^[-*+] \[[xX]\]$/.test(beforeCursor)) return doList(anchorNode, block, countPrefixLen(raw, 5), sel, 'ul', beforeCursor + ' ', true, true);
          olm = beforeCursor.match(/^(\d+)\.$/);
          if (olm) return doList(anchorNode, block, countPrefixLen(raw, olm[0].length), sel, 'ol', olm[0] + ' ');
        }
        return false;
      }

      function stripPrefix(textNode, prefixLen) {
        var rest = textNode.textContent.substring(prefixLen);
        textNode.textContent = rest.replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '') ? rest : '\u200B';
      }

      function doHeading(textNode, block, level, prefixLen, sel, literal) {
        stripPrefix(textNode, prefixLen);
        var h = document.createElement('H' + level);
        if (literal) h.setAttribute('data-md-literal', literal);
        if (block === ea) {
          h.textContent = textNode.textContent;
          ea.replaceChild(h, textNode);
        } else {
          while (block.firstChild) h.appendChild(block.firstChild);
          block.parentNode.replaceChild(h, block);
        }
        placeCursorIn(h, sel, true);
        return true;
      }

      function doBlockquote(textNode, block, prefixLen, sel, literal) {
        stripPrefix(textNode, prefixLen);
        var bq = document.createElement('blockquote');
        if (literal) bq.setAttribute('data-md-literal', literal);
        var p = document.createElement('p');
        if (block === ea) {
          p.textContent = textNode.textContent;
          bq.appendChild(p);
          ea.replaceChild(bq, textNode);
        } else {
          while (block.firstChild) p.appendChild(block.firstChild);
          bq.appendChild(p);
          block.parentNode.replaceChild(bq, block);
        }
        placeCursorIn(p, sel, true);
        return true;
      }

      function doAdmonition(textNode, block, prefixLen, sel, collapsible, literal, type, detailsTag) {
        stripPrefix(textNode, prefixLen);
        type = type || 'note';
        if (detailsTag) { collapsible = true; type = 'note'; }
        var title = type.charAt(0).toUpperCase() + type.slice(1);
        var bodyP = document.createElement('p');
        bodyP.textContent = '\u200B';

        var el;
        if (collapsible) {
          el = document.createElement('details');
          if (!detailsTag) el.setAttribute('open', '');
          el.className = type;
          el.setAttribute('contenteditable', 'true');
          if (detailsTag) {
            el.setAttribute('data-details-tag', '1');
            el.setAttribute('data-default-collapsed', '1');
          }
          var summary = document.createElement('summary');
          summary.textContent = detailsTag ? 'Details' : title;
          el.appendChild(summary);
          el.appendChild(bodyP);
        } else {
          el = document.createElement('div');
          el.className = 'admonition ' + type;
          el.setAttribute('contenteditable', 'true');
          var titleP = document.createElement('p');
          titleP.className = 'admonition-title';
          titleP.textContent = title;
          el.appendChild(titleP);
          el.appendChild(bodyP);
        }
        if (literal) el.setAttribute('data-md-literal', literal);
        if (block === ea) {
          ea.replaceChild(el, textNode);
        } else {
          block.parentNode.replaceChild(el, block);
        }
        enhanceAdmonitions(ea);
        placeCursorIn(bodyP, sel, true);
        return true;
      }

      function doList(textNode, block, prefixLen, sel, listType, literal, isChecklist, checklistChecked) {
        stripPrefix(textNode, prefixLen);
        if (block === ea) {
          var p = document.createElement('p');
          p.textContent = textNode.textContent;
          ea.replaceChild(p, textNode);
          block = p;
        }
        placeCursorIn(block, sel, true);
        document.execCommand(listType === 'ul' ? 'insertUnorderedList' : 'insertOrderedList', false, null);
        var node = (sel.anchorNode && sel.anchorNode.nodeType === 3) ? sel.anchorNode.parentNode : sel.anchorNode;
        var list = node && (node.closest ? node.closest('ul, ol') : (function (n) { while (n && n !== ea) { if (n.nodeName === 'UL' || n.nodeName === 'OL') return n; n = n.parentNode; } return null; })(node));
        if (list && literal) list.setAttribute('data-md-literal', literal);
        if (list && isChecklist) {
          var firstLi = list.querySelector('li');
          if (firstLi && !getDirectCheckboxOfLi(firstLi)) {
            var cb = createInteractiveCheckbox(!!checklistChecked);
            firstLi.insertBefore(cb, firstLi.firstChild);
            var space = document.createTextNode(' ');
            firstLi.insertBefore(space, cb.nextSibling);
            var pos = getPositionAfterCheckboxSpaces(firstLi);
            if (pos) {
              var range = document.createRange();
              range.setStart(pos.node, pos.offset);
              range.collapse(true);
              sel.removeAllRanges();
              sel.addRange(range);
            } else {
              placeCursorIn(firstLi, sel, true);
            }
          }
        }
        return true;
      }

      // ── Convert single-item empty list to checklist on [ ] or [x] ──

      function handleListToChecklist(anchorNode, anchorOffset, sel) {
        var node = anchorNode.nodeType === 3 ? anchorNode.parentNode : anchorNode;
        var li = null;
        while (node && node !== ea) {
          if (node.nodeName === 'LI') { li = node; break; }
          node = node.parentNode;
        }
        if (!li) return false;
        var list = li.parentNode;
        if (!list || list.nodeName !== 'UL' || list.childNodes.length !== 1) return false;
        if (getDirectCheckboxOfLi(li)) return false;
        var text = (li.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
        var isChecked = false;
        var literal = null;
        var marker = (list.getAttribute('data-md-literal') || '- ').replace(/\s*$/, '');
        if (text === '[ ] ') { literal = marker + ' [ ] '; }
        else if (text === '[x] ' || text === '[X] ') { literal = marker + ' [x] '; isChecked = true; }
        else return false;
        while (li.firstChild) li.removeChild(li.firstChild);
        var cb = createInteractiveCheckbox(isChecked);
        li.appendChild(cb);
        var spaceAndZws = document.createTextNode(' \u200B');
        li.appendChild(spaceAndZws);
        if (literal) list.setAttribute('data-md-literal', literal);
        var range = document.createRange();
        range.setStart(spaceAndZws, 2);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        return true;
      }

      // ── Horizontal rule (---, ***, ___) ──

      function handleHorizontalRule(anchorNode, anchorOffset, sel, ch) {
        if (ch !== '-' && ch !== '*' && ch !== '_') return false;
        var text = anchorNode.textContent;
        if (anchorOffset < 3) return false;
        var seg = text.substring(anchorOffset - 3, anchorOffset);
        if (seg !== '---' && seg !== '***' && seg !== '___') return false;

        var lineStart = text.lastIndexOf('\n', anchorOffset - 3) + 1;
        if (text.substring(lineStart, anchorOffset - 3).replace(ZWS_RE, '').trim()) return false;

        var block = getContainingBlock(anchorNode);
        if (!block || (block.nodeName !== 'P' && block.nodeName !== 'DIV' && block !== ea)) return false;
        var clean = block.textContent.replace(/[\u200B\u200C\u200D\uFEFF]/g, '').trim();
        if (clean !== '---' && clean !== '***' && clean !== '___') return false;

        var container = block === ea ? ea : block.parentNode;
        var toRemove = block === ea ? anchorNode : block;
        var hr = document.createElement('hr');
        hr.setAttribute('data-md-literal', clean);
        container.insertBefore(hr, toRemove);
        container.removeChild(toRemove);

        var pAfter = document.createElement('p');
        pAfter.innerHTML = '&#8203;';
        container.insertBefore(pAfter, hr.nextSibling);
        placeCursorIn(pAfter, sel, true);
        return true;
      }

      // ── Inline: bold **text**/__text__, italic *text*/_text_ ──

      function handleAsteriskOrUnderscore(anchorNode, anchorOffset, sel, ch) {
        var text = anchorNode.textContent;
        var before = text.substring(0, anchorOffset);
        var double = ch + ch;
        var single = ch;

        if (before.length >= 5 && before.slice(-2) === double) {
          var inner = before.slice(0, -2);
          var openIdx = inner.lastIndexOf(double);
          if (openIdx >= 0) {
            var content = inner.substring(openIdx + 2);
            if (content.length > 0 && content.charAt(0) !== ' ' && content.charAt(content.length - 1) !== ' ') {
              return doInlineWrap(anchorNode, openIdx, anchorOffset, content, 'strong', sel, double + content + double);
            }
          }
        }

        if (before.length >= 3 && before.slice(-1) === single && (before.length < 2 || before.charAt(before.length - 2) !== single)) {
          var inner = before.slice(0, -1);
          for (var i = inner.length - 1; i >= 0; i--) {
            if (inner.charAt(i) === single) {
              if (i > 0 && inner.charAt(i - 1) === single) { i--; continue; }
              if (i < inner.length - 1 && inner.charAt(i + 1) === single) continue;
              var content = inner.substring(i + 1);
              if (content.length > 0 && content.charAt(0) !== ' ' && content.charAt(content.length - 1) !== ' ') {
                return doInlineWrap(anchorNode, i, anchorOffset, content, 'em', sel, single + content + single);
              }
              break;
            }
          }
        }
        return false;
      }

      // ── Inline: strikethrough ~~text~~ ──

      function handleTilde(anchorNode, anchorOffset, sel) {
        var text = anchorNode.textContent;
        var before = text.substring(0, anchorOffset);
        if (before.length >= 5 && before.slice(-2) === '~~') {
          var inner = before.slice(0, -2);
          var openIdx = inner.lastIndexOf('~~');
          if (openIdx >= 0) {
            var content = inner.substring(openIdx + 2);
            if (content.length > 0 && content.charAt(0) !== ' ' && content.charAt(content.length - 1) !== ' ') {
              return doInlineWrap(anchorNode, openIdx, anchorOffset, content, 'del', sel, '~~' + content + '~~');
            }
          }
        }
        return false;
      }

      // ── Inline: markdown link [text](url) ──

      function _skipBacktickSpanLeft(str, pos) {
        var run = 1;
        while (pos > 0 && str.charAt(pos - 1) === '`') { pos--; run++; }
        pos--;
        while (pos >= 0) {
          if (str.charAt(pos) === '`') {
            var oRun = 1;
            while (pos > 0 && str.charAt(pos - 1) === '`') { pos--; oRun++; }
            if (oRun >= run) return pos;
            pos--;
          } else { pos--; }
        }
        return pos;
      }

      function handleCloseParen(anchorNode, anchorOffset, sel) {
        var text = anchorNode.textContent;
        var before = text.substring(0, anchorOffset);
        if (before.length < 5) return false;
        if (before.charAt(before.length - 1) !== ')') return false;

        var parenStart = -1;
        var bracketClose = -1;
        var pd = 0;
        for (var pi = before.length - 1; pi >= 0; pi--) {
          var pc = before.charAt(pi);
          if (pc === '`') { pi = _skipBacktickSpanLeft(before, pi); continue; }
          if (pc === ')') pd++;
          else if (pc === '(') {
            pd--;
            if (pd === 0) { parenStart = pi; break; }
          }
        }
        if (parenStart < 1 || before.charAt(parenStart - 1) !== ']') return false;
        bracketClose = parenStart - 1;

        var url = before.substring(parenStart + 1, before.length - 1);
        if (!url || /\s/.test(url)) return false;

        var depth = 0;
        var bracketOpen = -1;
        for (var bi = bracketClose - 1; bi >= 0; bi--) {
          var bch = before.charAt(bi);
          if (bch === '`') { bi = _skipBacktickSpanLeft(before, bi); continue; }
          if (bch === ']') depth++;
          else if (bch === '[') {
            if (depth === 0) { bracketOpen = bi; break; }
            depth--;
          }
        }
        if (bracketOpen < 0) return false;

        var linkText = before.substring(bracketOpen + 1, bracketClose);
        if (!linkText) return false;

        var isImage = bracketOpen > 0 && before.charAt(bracketOpen - 1) === '!';
        var startIdx = isImage ? bracketOpen - 1 : bracketOpen;
        var beforeLink = text.substring(0, startIdx);
        var afterLink = text.substring(anchorOffset);
        var fullLiteral = isImage
          ? '![' + linkText + '](' + url + ')'
          : '[' + linkText + '](' + url + ')';

        var parentNode = anchorNode.parentNode;
        var afterNode = document.createTextNode('\u200B' + afterLink);

        if (isImage) {
          var img = document.createElement('img');
          img.src = resolveImageSrc(url);
          img.alt = linkText;
          img.setAttribute('data-orig-src', url);
          img.setAttribute('data-md-literal', fullLiteral);
          img.setAttribute('data-size-syntax', _getSetting('live_wysiwyg_image_attr_syntax') === '0' ? 'html' : 'attr');

          if (beforeLink) {
            anchorNode.textContent = beforeLink;
            parentNode.insertBefore(img, anchorNode.nextSibling);
            parentNode.insertBefore(afterNode, img.nextSibling);
          } else {
            parentNode.insertBefore(img, anchorNode);
            parentNode.insertBefore(afterNode, img.nextSibling);
            parentNode.removeChild(anchorNode);
          }
          enhanceImages(ea);
          var range = document.createRange();
          range.setStart(afterNode, 1);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          return true;
        }

        var a = document.createElement('a');
        a.href = url;
        a.setAttribute('data-md-literal', fullLiteral);
        if (typeof marked !== 'undefined' && marked.parseInline) {
          a.innerHTML = marked.parseInline(linkText);
        } else {
          a.textContent = linkText;
        }

        if (beforeLink) {
          anchorNode.textContent = beforeLink;
          parentNode.insertBefore(a, anchorNode.nextSibling);
          parentNode.insertBefore(afterNode, a.nextSibling);
        } else {
          parentNode.insertBefore(a, anchorNode);
          parentNode.insertBefore(afterNode, a.nextSibling);
          parentNode.removeChild(anchorNode);
        }
        if (a.querySelector('img')) enhanceImages(ea);
        var range = document.createRange();
        range.setStart(afterNode, 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        return true;
      }

      // ── Shared inline DOM helper ──

      function doInlineWrap(textNode, startIdx, endIdx, content, tagName, sel, literal) {
        var text = textNode.textContent;
        var before = text.substring(0, startIdx);
        var after = text.substring(endIdx);

        var el = document.createElement(tagName);
        el.textContent = content;
        if (literal) el.setAttribute('data-md-literal', literal);

        var parentNode = textNode.parentNode;
        var afterNode = document.createTextNode('\u200B' + after);

        if (before) {
          textNode.textContent = before;
          parentNode.insertBefore(el, textNode.nextSibling);
          parentNode.insertBefore(afterNode, el.nextSibling);
        } else {
          parentNode.insertBefore(el, textNode);
          parentNode.insertBefore(afterNode, el.nextSibling);
          parentNode.removeChild(textNode);
        }

        var range = document.createRange();
        range.setStart(afterNode, 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        return true;
      }

      function isEmptyBlock(node) {
        var text = (node.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
        return !text && !node.querySelector('img, table');
      }

      function handleRevertOnBackspace(sel) {
        if (!sel || !sel.isCollapsed || !sel.rangeCount) return false;
        var node = sel.anchorNode;
        if (!node) return false;
        if (node.nodeType === 3) node = node.parentNode;
        if (!ea.contains(node)) return false;

        // Inline element revert: cursor at start, at end, or immediately after (CODE, STRONG, EM, DEL, A)
        var anchorNode = sel.anchorNode;
        var anchorOffset = sel.anchorOffset;
        var inlineEl = null;
        var atRevertPosition = false;
        var INLINE_REVERT_TAGS = { CODE: 1, STRONG: 1, EM: 1, DEL: 1, A: 1, B: 1 };

        var n = anchorNode;
        var anc = n.nodeType === 3 ? n.parentNode : n;
        while (anc && anc !== ea) {
          if (INLINE_REVERT_TAGS[anc.nodeName]) {
            if (anc.nodeName === 'CODE' && anc.parentNode && anc.parentNode.nodeName === 'PRE') break;
            inlineEl = anc;
            var atStart = (n === anc && anchorOffset === 0) || (n.parentNode === anc && anchorOffset === 0);
            var atEnd = (n === anc && anchorOffset === anc.childNodes.length) ||
              (n.parentNode === anc && anchorOffset === (n.textContent || '').length);
            if (atStart || atEnd) atRevertPosition = true;
            break;
          }
          if (anc.nodeName === 'PRE') break;
          anc = anc.parentNode;
        }
        if (!inlineEl && anchorNode && anchorNode.nodeType === 3) {
          var prev = anchorNode.previousSibling;
          if (prev && INLINE_REVERT_TAGS[prev.nodeName] &&
              !(prev.nodeName === 'CODE' && prev.parentNode && prev.parentNode.nodeName === 'PRE')) {
            inlineEl = prev;
            var txt = anchorNode.textContent || '';
            var afterZws = (anchorOffset === 1 && txt.length >= 1 && /[\u200B\u200C\u200D\uFEFF]/.test(txt.charAt(0)));
            if (anchorOffset === 0 || afterZws) atRevertPosition = true;
          }
        }
        if (inlineEl && atRevertPosition) {
          var inlineText = (inlineEl.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
          literal = inlineEl.getAttribute('data-md-literal');
          if (!literal) {
            literal = inlineText;
          }
          var inlineParent = inlineEl.parentNode;
          var newText = document.createTextNode(literal);
          inlineParent.replaceChild(newText, inlineEl);
          var nextTn = newText.nextSibling;
          if (nextTn && nextTn.nodeType === 3) {
            var nextTxt = nextTn.textContent || '';
            var stripped = nextTxt.replace(/^[\u200B\u200C\u200D\uFEFF]+/, '');
            if (stripped !== nextTxt) {
              nextTn.textContent = stripped;
            }
          }
          var range = document.createRange();
          range.setStart(newText, literal.length);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          return true;
        }

        if (isInsidePreOrCode(node)) return false;

        // Checklist revert: cursor in space after checkbox (single-item list)
        var prev = anchorNode && anchorNode.nodeType === 3 ? anchorNode.previousSibling : null;
        if (prev && prev.nodeName === 'INPUT' && prev.type === 'checkbox') {
          var li = anchorNode.parentNode;
          if (li && li.nodeName === 'LI') {
            var list = li.parentNode;
            if (list && list.nodeName === 'UL' && list.childNodes.length === 1) {
              if (isEmptyBlock(li)) {
                literal = list.getAttribute('data-md-literal');
                var parent = list.parentNode;
                var newP = document.createElement('p');
                if (literal) {
                  newP.style.whiteSpace = 'pre-wrap';
                  newP.textContent = literal;
                } else {
                  newP.appendChild(document.createElement('br'));
                }
                parent.replaceChild(newP, list);
                if (literal) placeCursorAtEnd(newP, sel);
                else { var r = document.createRange(); r.setStart(newP, 0); r.collapse(true); sel.removeAllRanges(); sel.addRange(r); }
                return true;
              }
            }
          }
        }

        var block = getContainingBlock(node);
        if (!block) return false;

        var parent, literal, newP;

        if (/^H[1-6]$/.test(block.nodeName)) {
          if (!isEmptyBlock(block)) return false;
          literal = block.getAttribute('data-md-literal');
          newP = document.createElement('p');
          if (literal) {
            newP.style.whiteSpace = 'pre-wrap';
            newP.textContent = literal;
          } else {
            newP.appendChild(document.createElement('br'));
          }
          parent = block.parentNode;
          parent.replaceChild(newP, block);
          if (literal) placeCursorAtEnd(newP, sel);
          else { var r = document.createRange(); r.setStart(newP, 0); r.collapse(true); sel.removeAllRanges(); sel.addRange(r); }
          return true;
        }

        var bq = block.nodeName === 'BLOCKQUOTE' ? block : (block.parentNode && block.parentNode.nodeName === 'BLOCKQUOTE' ? block.parentNode : null);
        if (bq) {
          var children = bq.querySelectorAll('p, div, h1, h2, h3, h4, h5, h6, ul, ol, pre');
          var allEmpty = true;
          for (var i = 0; i < children.length; i++) {
            if (!isEmptyBlock(children[i])) { allEmpty = false; break; }
          }
          if (!allEmpty) return false;
          literal = bq.getAttribute('data-md-literal');
          newP = document.createElement('p');
          if (literal) {
            newP.style.whiteSpace = 'pre-wrap';
            newP.textContent = literal;
          } else {
            newP.appendChild(document.createElement('br'));
          }
          parent = bq.parentNode;
          parent.replaceChild(newP, bq);
          if (literal) placeCursorAtEnd(newP, sel);
          else { var r = document.createRange(); r.setStart(newP, 0); r.collapse(true); sel.removeAllRanges(); sel.addRange(r); }
          return true;
        }

        var ad = block.classList && block.classList.contains('admonition') ? block : null;
        if (!ad && block.parentNode && block.parentNode.classList && block.parentNode.classList.contains('admonition')) ad = block.parentNode;
        if (ad) {
          var titleEl = ad.querySelector('.admonition-title');
          if (titleEl && (block === titleEl || titleEl.contains(node))) return false;
          var bodyBlocks = [];
          for (var j = 0; j < ad.childNodes.length; j++) {
            var c = ad.childNodes[j];
            if (c !== titleEl && (!c.classList || !c.classList.contains('md-admonition-settings-btn'))) bodyBlocks.push(c);
          }
          for (var k = 0; k < bodyBlocks.length; k++) {
            if (!isEmptyBlock(bodyBlocks[k])) return false;
          }
          literal = ad.getAttribute('data-md-literal');
          newP = document.createElement('p');
          if (literal) {
            newP.style.whiteSpace = 'pre-wrap';
            newP.textContent = literal;
          } else {
            newP.appendChild(document.createElement('br'));
          }
          parent = ad.parentNode;
          parent.replaceChild(newP, ad);
          if (literal) placeCursorAtEnd(newP, sel);
          else { var r = document.createRange(); r.setStart(newP, 0); r.collapse(true); sel.removeAllRanges(); sel.addRange(r); }
          return true;
        }

        var detailsEl = block.nodeName === 'DETAILS' && block.querySelector('summary') ? block : null;
        if (!detailsEl && block.parentNode && block.parentNode.nodeName === 'DETAILS') detailsEl = block.parentNode;
        if (detailsEl) {
          var summaryEl = detailsEl.querySelector(':scope > summary');
          if (summaryEl && (block === summaryEl || summaryEl.contains(node))) return false;
          var bodyNodes = [];
          for (var m = 0; m < detailsEl.childNodes.length; m++) {
            if (detailsEl.childNodes[m].nodeName !== 'SUMMARY') bodyNodes.push(detailsEl.childNodes[m]);
          }
          for (var n = 0; n < bodyNodes.length; n++) {
            if (!isEmptyBlock(bodyNodes[n])) return false;
          }
          literal = detailsEl.getAttribute('data-md-literal');
          newP = document.createElement('p');
          if (literal) {
            newP.style.whiteSpace = 'pre-wrap';
            newP.textContent = literal;
          } else {
            newP.appendChild(document.createElement('br'));
          }
          parent = detailsEl.parentNode;
          parent.replaceChild(newP, detailsEl);
          if (literal) placeCursorAtEnd(newP, sel);
          else { var r = document.createRange(); r.setStart(newP, 0); r.collapse(true); sel.removeAllRanges(); sel.addRange(r); }
          return true;
        }

        if (block.nodeName === 'LI') {
          var list = block.parentNode;
          if (!list || (list.nodeName !== 'UL' && list.nodeName !== 'OL')) return false;
          if (list.childNodes.length !== 1) return false;
          if (!isEmptyBlock(block)) return false;
          literal = list.getAttribute('data-md-literal');
          newP = document.createElement('p');
          if (literal) {
            newP.style.whiteSpace = 'pre-wrap';
            newP.textContent = literal;
          } else {
            newP.appendChild(document.createElement('br'));
          }
          parent = list.parentNode;
          parent.replaceChild(newP, list);
          if (literal) placeCursorAtEnd(newP, sel);
          else { var r = document.createRange(); r.setStart(newP, 0); r.collapse(true); sel.removeAllRanges(); sel.addRange(r); }
          return true;
        }

        if (block.nodeName === 'P' && block.previousElementSibling &&
            (isAdmonitionElement(block.previousElementSibling) || block.previousElementSibling.nodeName === 'BLOCKQUOTE')) {
          if (!isEmptyBlock(block)) return false;
          var container = block.previousElementSibling;
          parent = block.parentNode;
          parent.removeChild(block);
          var lastBody = null;
          for (var lbi = container.childNodes.length - 1; lbi >= 0; lbi--) {
            var lbk = container.childNodes[lbi];
            if (lbk.nodeType !== 1) continue;
            if (lbk.classList && (lbk.classList.contains('md-admonition-settings-btn') ||
                lbk.classList.contains('admonition-title'))) continue;
            if (lbk.nodeName === 'SUMMARY') continue;
            lastBody = lbk;
            break;
          }
          if (!lastBody) {
            lastBody = document.createElement('p');
            lastBody.innerHTML = '<br>';
            var settingsBtn = container.querySelector(':scope > .md-admonition-settings-btn');
            if (settingsBtn) container.insertBefore(lastBody, settingsBtn);
            else container.appendChild(lastBody);
          }
          if (lastBody.querySelector && lastBody.querySelector('.md-image-wrapper')) {
            var cursorP = document.createElement('p');
            cursorP.innerHTML = '<br>';
            var _sBtn = container.querySelector(':scope > .md-admonition-settings-btn');
            if (_sBtn) container.insertBefore(cursorP, _sBtn);
            else container.appendChild(cursorP);
            var _r = document.createRange();
            _r.setStart(cursorP, 0);
            _r.collapse(true);
            sel.removeAllRanges();
            sel.addRange(_r);
          } else {
            placeCursorAtEnd(lastBody, sel);
          }
          return true;
        }

        if (block.nodeName === 'P' && block.previousElementSibling && block.previousElementSibling.nodeName === 'HR') {
          if (!isEmptyBlock(block)) return false;
          var hr = block.previousElementSibling;
          literal = hr.getAttribute('data-md-literal');
          parent = hr.parentNode;
          if (literal) {
            newP = document.createElement('p');
            newP.textContent = literal;
            parent.insertBefore(newP, hr);
            parent.removeChild(hr);
            parent.removeChild(block);
            placeCursorAtEnd(newP, sel);
          } else {
            parent.removeChild(hr);
            var r = document.createRange();
            r.setStart(block, 0);
            r.collapse(true);
            sel.removeAllRanges();
            sel.addRange(r);
          }
          return true;
        }

        // Image revert: cursor immediately after an md-image-wrapper
        var imgWrapper = null;
        var ancN = sel.anchorNode;
        var ancO = sel.anchorOffset;
        if (ancN && ancN.nodeType === 1 && ancO > 0) {
          var prevChild = ancN.childNodes[ancO - 1];
          if (prevChild && prevChild.nodeType === 1 && prevChild.classList &&
              prevChild.classList.contains('md-image-wrapper')) {
            imgWrapper = prevChild;
          }
        }
        if (!imgWrapper && ancN && ancN.nodeType === 3) {
          var txtBefore = (ancN.textContent || '').substring(0, ancO).replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
          if (txtBefore.length === 0) {
            var ps = ancN.previousSibling;
            if (ps && ps.nodeType === 1 && ps.classList && ps.classList.contains('md-image-wrapper')) {
              imgWrapper = ps;
            }
          }
        }
        if (imgWrapper) {
          var imgEl = imgWrapper.querySelector('img');
          literal = imgEl ? imgEl.getAttribute('data-md-literal') : null;
          parent = imgWrapper.parentNode;
          if (literal) {
            if (parent !== ea && (parent.nodeName === 'P' || parent.nodeName === 'LI' ||
                parent.nodeName === 'SPAN' || parent.nodeName === 'A' ||
                parent.nodeName === 'STRONG' || parent.nodeName === 'EM')) {
              var litText = document.createTextNode(literal);
              parent.replaceChild(litText, imgWrapper);
              var nextSib = litText.nextSibling;
              if (nextSib && nextSib.nodeType === 3) {
                var sib = nextSib.textContent || '';
                var stripped = sib.replace(/^[\u200B\u200C\u200D\uFEFF]+/, '');
                if (stripped !== sib) nextSib.textContent = stripped;
              }
              var _prefixLen = 0;
              var _pn = litText.previousSibling;
              while (_pn && _pn.nodeType === 3) {
                _prefixLen += (_pn.textContent || '').length;
                _pn = _pn.previousSibling;
              }
              var _targetOff = _prefixLen + literal.length;
              parent.normalize();
              var _merged = parent.firstChild;
              var _off = _targetOff;
              while (_merged) {
                if (_merged.nodeType === 3) {
                  if (_off <= _merged.textContent.length) break;
                  _off -= _merged.textContent.length;
                }
                _merged = _merged.nextSibling;
              }
              if (_merged && _merged.nodeType === 3) {
                var rng = document.createRange();
                rng.setStart(_merged, Math.min(_off, _merged.textContent.length));
                rng.collapse(true);
                sel.removeAllRanges();
                sel.addRange(rng);
              }
            } else {
              newP = document.createElement('p');
              newP.style.whiteSpace = 'pre-wrap';
              newP.textContent = literal;
              parent.replaceChild(newP, imgWrapper);
              placeCursorAtEnd(newP, sel);
            }
          } else {
            parent.removeChild(imgWrapper);
            var parentText = (parent.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
            if (parentText.length === 0 && parent.querySelectorAll('img').length === 0) {
              if (parent !== ea && (parent.nodeName === 'P' || parent.nodeName === 'DIV')) {
                var rP = document.createElement('p');
                rP.innerHTML = '<br>';
                parent.parentNode.replaceChild(rP, parent);
                var r2 = document.createRange();
                r2.setStart(rP, 0);
                r2.collapse(true);
                sel.removeAllRanges();
                sel.addRange(r2);
              } else if (parent === ea) {
                insertPlaceholder(ea);
              }
            }
          }
          return true;
        }

        return false;
      }

      // ── keydown: intercept space for block conversions, backspace for revert ──

      _ekh.mdAuto = function (e) {
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        var sel = window.getSelection();

        if (_activeImageSelection && _activeImageSelection.img &&
            (e.key === 'Delete' || e.key === 'Backspace') && !e.defaultPrevented) {
          e.preventDefault();
          e.stopImmediatePropagation();
          wysiwygEditor.__cursorBeforeInput = captureWysiwygCursor(ea);
          _removeSelectedImage();
          return;
        }

        if (e.key === 'Backspace' && !e.defaultPrevented) {
          if (handleRevertOnBackspace(sel)) {
            e.preventDefault();
            e.stopImmediatePropagation();
            if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
            return;
          }
        }

        if (e.key !== ' ' || e.defaultPrevented) return;
        if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
        var anchorNode = sel.anchorNode;
        var anchorOffset = sel.anchorOffset;
        if (!anchorNode || anchorNode.nodeType !== 3) return;
        if (isInsidePreOrCode(anchorNode)) return;
        var converted = handleBlockConversions(anchorNode, anchorOffset, sel, false);
        if (converted) {
          e.preventDefault();
          if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
        }
      };

      // ── Main input listener ──

      ea.addEventListener('input', function (e) {
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        if (e.inputType !== 'insertText' || !e.data) return;

        var sel = window.getSelection();
        if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
        var anchorNode = sel.anchorNode;
        var anchorOffset = sel.anchorOffset;
        if (!anchorNode || anchorNode.nodeType !== 3) return;
        if (isInsidePreOrCode(anchorNode)) return;

        var ch = e.data;
        var converted = false;

        if (ch === ' ') {
          converted = handleListToChecklist(anchorNode, anchorOffset, sel);
          if (!converted) converted = handleBlockConversions(anchorNode, anchorOffset, sel, true);
        }

        if (!converted && (ch === '-' || ch === '*' || ch === '_')) {
          converted = handleHorizontalRule(anchorNode, anchorOffset, sel, ch);
        }

        if (!converted && (ch === '*' || ch === '_')) {
          converted = handleAsteriskOrUnderscore(anchorNode, anchorOffset, sel, ch);
        }

        if (!converted && ch === '~') {
          converted = handleTilde(anchorNode, anchorOffset, sel);
        }

        if (!converted && ch === ')') {
          converted = handleCloseParen(anchorNode, anchorOffset, sel);
        }

        if (converted && wysiwygEditor._finalizeUpdate) {
          wysiwygEditor._finalizeUpdate(ea.innerHTML);
        }
      });
    })();

    (function patchMarkdownToHtmlShortcodeToEmoji() {
      var FALLBACK = {"white_check_mark":"\u2705","check_mark":"\u2714","heart_eyes":"\ud83d\ude0d","thumbsup":"\ud83d\udc4d","heart":"\u2764","smile":"\ud83d\ude04","fire":"\ud83d\udd25","star":"\u2b50","warning":"\u26a0","x":"\u274c"};
      var EMOJI_MAP = (typeof liveWysiwygEmojiMap !== "undefined" && Object.keys(liveWysiwygEmojiMap || {}).length > 0) ? liveWysiwygEmojiMap : FALLBACK;
      var shortcodeRe = /:([a-z0-9_+-]+):/g;
      var EMOJIONE_CDN = "https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/svg/";
      function emojiToEmojionePath(emoji) {
        var parts = [];
        for (var i = 0; i < emoji.length; ) {
          var cp = emoji.codePointAt(i);
          parts.push(cp.toString(16));
          i += cp > 0xFFFF ? 2 : 1;
        }
        return parts.join("-");
      }
      function emojiToImgHtml(shortcode, emoji) {
        var path = emojiToEmojionePath(emoji);
        return "<img alt=\"" + emoji + "\" class=\"emojione\" src=\"" + EMOJIONE_CDN + path + ".svg\" title=\"" + shortcode + "\" data-emoji-shortcode=\"" + shortcode + "\">";
      }
      if (typeof window !== "undefined") window.liveWysiwygEmojiToImgHtml = emojiToImgHtml;
      function replaceShortcodeInHtml(html) {
        var protectedBlocks = [];
        var ph = "\u0000PB";
        var protectBlock = function (m) {
          var idx = protectedBlocks.length;
          protectedBlocks.push(m);
          return ph + idx + ph;
        };
        var protected_ = html.replace(/<pre[^>]*>[\s\S]*?<\/pre>/gi, protectBlock);
        protected_ = protected_.replace(/<img[^>]*data-emoji-shortcode[^>]*>/gi, protectBlock);
        protected_ = protected_.replace(/<code[^>]*>[\s\S]*?<\/code>/gi, protectBlock);
        protected_ = protected_.replace(shortcodeRe, function (m, key) {
          var em = EMOJI_MAP[key];
          return em ? emojiToImgHtml(":" + key + ":", em) : m;
        });
        for (var i = 0; i < protectedBlocks.length; i++) {
          protected_ = protected_.split(ph + i + ph).join(protectedBlocks[i]);
        }
        return protected_;
      }
      var proto = MarkdownWYSIWYG.prototype;
      var origMarkdownToHtml = proto._markdownToHtml;
      if (!origMarkdownToHtml) return;
      function replaceShortcodeInMarkdown(md) {
        var codeBlocks = [];
        var ph = "\u0000CB";
        var protectBlock = function (m) {
          var idx = codeBlocks.length;
          codeBlocks.push(m);
          return ph + idx + ph;
        };
        var protected_ = md.replace(/\`\`\`[\s\S]*?\`\`\`/g, protectBlock);
        protected_ = protected_.replace(/``(?:[^`]|`(?!`))*``/g, protectBlock);
        protected_ = protected_.replace(/`[^`\n]+`/g, protectBlock);
        // Protect emoji img tags (raw HTML) so shortcode replacement does not run inside
        // attribute values (e.g. title=":white_check_mark:") - that causes recursive nesting.
        protected_ = protected_.replace(/<img[^>]*data-emoji-shortcode[^>]*>/gi, protectBlock);
        protected_ = protected_.replace(shortcodeRe, function (m, key) {
          var em = EMOJI_MAP[key];
          return em ? emojiToImgHtml(":" + key + ":", em) : m;
        });
        for (var i = 0; i < codeBlocks.length; i++) {
          protected_ = protected_.split(ph + i + ph).join(codeBlocks[i]);
        }
        return protected_;
      }
      proto._markdownToHtml = function (markdown) {
        var md = markdown || "";
        var mdWithEmoji = replaceShortcodeInMarkdown(md);
        var html = origMarkdownToHtml.call(this, mdWithEmoji);
        return replaceShortcodeInHtml(html);
      };
    })();

    (function patchMarkdownToHtmlForRawHtml() {
      var proto = MarkdownWYSIWYG.prototype;
      var origMdToHtml = proto._markdownToHtml;
      if (!origMdToHtml) return;
      var spanPattern = new RegExp('<span\\s+data-live-wysiwyg-cursor\\s*></span>', 'g');
      var spanEndPattern = new RegExp('<span\\s+data-live-wysiwyg-cursor-end\\s*></span>', 'g');
      var attrListImgRe = /!\[([^\]]*)\]\(([^)]+)\)\{([^}]+)\}/g;
      var attrListImgRefRe = /!\[([^\]]*)\]\[([^\]]*)\]\{([^}]+)\}/g;
      proto._markdownToHtml = function (markdown) {
        var md = markdown || '';
        md = md.replace(spanPattern, 'LIVEWYSIWYG_CURSOR_9X7K2').replace(spanEndPattern, 'LIVEWYSIWYG_CURSOR_END_9X7K2');
        var mdRefDefs = {};
        md.replace(/^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))/gm, function (m, name, url1, url2) {
          mdRefDefs[name.toLowerCase()] = (url1 || url2 || '').trim();
          return m;
        });
        md = md.replace(attrListImgRefRe, function (m, alt, ref, attrs) {
          var refUrl = mdRefDefs[ref.toLowerCase()];
          if (!refUrl) return m;
          return '![' + alt + '](' + refUrl + '){' + attrs + '}';
        });
        md = md.replace(attrListImgRe, function (m, alt, src, attrs) {
          var wMatch = attrs.match(/\bwidth=(\d+)/);
          var hMatch = attrs.match(/\bheight=(\d+)/);
          var alignMatch = /\balign=middle\b/.test(attrs);
          if (!wMatch && !hMatch && !alignMatch) return m;
          var resolved = resolveImageSrc(src);
          var dataOrig = (resolved !== src) ? ' data-orig-src="' + src.replace(/"/g, '&quot;') + '"' : '';
          var wAttr = wMatch ? ' width="' + wMatch[1] + '"' : '';
          var hAttr = hMatch ? ' height="' + hMatch[1] + '"' : '';
          var explicitH = hMatch ? ' data-attr-height="1"' : '';
          var inlineAttr = alignMatch ? ' data-inline="1" style="vertical-align: middle; display: inline"' : '';
          return '<img src="' + resolved.replace(/"/g, '&quot;') + '" alt="' + alt.replace(/"/g, '&quot;') + '"' + wAttr + hAttr + dataOrig + ' data-size-syntax="attr"' + explicitH + inlineAttr + '>';
        });
        var rawResult = preprocessRawHtml(md);
        this._liveWysiwygRawHtmlData = rawResult;
        return origMdToHtml.call(this, rawResult.markdown);
      };
    })();

    (function patchHtmlToMarkdownEmojiToShortcode() {
      var MARKER = "\uFFFF\uFFFF\uFFFF";
      var MARKER_END = "\uFFFE\uFFFE\uFFFE";
      var proto = MarkdownWYSIWYG.prototype;
      var origNodeToMarkdown = proto._nodeToMarkdownRecursive;
      if (!origNodeToMarkdown) return;
      var shortcodePattern = /^:[a-z0-9_+-]+:$/;
      proto._nodeToMarkdownRecursive = function (node, options) {
        if (node.nodeName === "CODE" && !this._findParentElement(node, 'PRE')) {
          var codeContent = (node.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '').trim();
          if (options && options.inTableCell) codeContent = codeContent.replace(/\|/g, '\\|');
          if (codeContent.indexOf('`') >= 0) return '`` ' + codeContent + ' ``';
          return '`' + codeContent + '`';
        }
        if (node.nodeName === "IMG" && node.getAttribute) {
          var sc = node.getAttribute("data-emoji-shortcode");
          if (sc && shortcodePattern.test(sc)) return sc;
        }
        if (node.nodeName === "SPAN" && node.getAttribute) {
          var shortcode = node.getAttribute("data-emoji-shortcode");
          if (!shortcode || !shortcodePattern.test(shortcode)) {
            return origNodeToMarkdown.apply(this, arguments);
          }
          var childContent = "";
          for (var i = 0; i < node.childNodes.length; i++) {
            childContent += origNodeToMarkdown.call(this, node.childNodes[i], options || {});
          }
          if (childContent.indexOf(MARKER) >= 0 || childContent.indexOf(MARKER_END) >= 0) {
            var emojiChar = node.textContent.split(MARKER).join("").split(MARKER_END).join("");
            return childContent.split(emojiChar).join(shortcode);
          }
          return shortcode;
        }
        return origNodeToMarkdown.apply(this, arguments);
      };
    })();


    // Selection preservation across mode switches is handled by the frontmatter
    // patch above (via injectMarkerAtCaretInEditable / CURSOR_MARKER).  That
    // approach naturally handles emoji <img> ↔ :shortcode: mapping because
    // _htmlToMarkdown converts <img data-emoji-shortcode> to :shortcode: with
    // adjacent CURSOR_MARKER text, and _markdownToHtml converts :shortcode: to
    // <img> with adjacent CURSOR_MARKER text.  No separate marker-based patch
    // is needed.

    // Re-render editable area with emoji patches now applied
    if (wysiwygEditor && wysiwygEditor.editableArea && wysiwygEditor.markdownArea) {
      var md = wysiwygEditor.markdownArea.value;
      if (md) {
        wysiwygEditor.editableArea.innerHTML = wysiwygEditor._markdownToHtml(md);
        populateRawHtmlBlocks(wysiwygEditor.editableArea);
      }
    }



    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
      _ekh.codeBlockBackspace = function (e) {
          if (e.key !== 'Backspace' && e.key !== 'Delete') return;
          var sel = window.getSelection();
          if (!sel || !sel.rangeCount) return;
          if (!sel.isCollapsed) {
            var r = sel.getRangeAt(0);
            var toRemove = [];
            var allAds = ea.querySelectorAll('.admonition');
            for (var ai = 0; ai < allAds.length; ai++) {
              var ad = allAds[ai];
              if (!r.intersectsNode(ad)) continue;
              var titleEl = ad.querySelector('.admonition-title');
              if (!titleEl || !r.intersectsNode(titleEl)) continue;
              var bodyIntersects = false;
              for (var bi = 0; bi < ad.childNodes.length; bi++) {
                var bc = ad.childNodes[bi];
                if (bc.nodeType === 1 && bc.classList && bc.classList.contains('admonition-title')) continue;
                if (r.intersectsNode(bc)) { bodyIntersects = true; break; }
              }
              if (bodyIntersects) toRemove.push(ad);
            }
            var allCodeBlocks = ea.querySelectorAll('.md-code-block');
            for (var ci = 0; ci < allCodeBlocks.length; ci++) {
              var cb = allCodeBlocks[ci];
              if (!r.intersectsNode(cb)) continue;
              var cbTitle = cb.querySelector('.md-code-title, .md-code-lang');
              if (!cbTitle || !r.intersectsNode(cbTitle)) continue;
              var cbPre = cb.querySelector('pre');
              if (cbPre && r.intersectsNode(cbPre)) toRemove.push(cb);
            }
            if (toRemove.length === 0) return;
            e.preventDefault();
            var insertionParent = toRemove[0].parentNode;
            var insertionRef = toRemove[0].nextSibling;
            for (var ri = 0; ri < toRemove.length; ri++) {
              var el = toRemove[ri];
              if (el.parentNode) {
                if (ri === 0) {
                  insertionParent = el.parentNode;
                  insertionRef = el.nextSibling;
                }
                el.parentNode.removeChild(el);
              }
            }
            try { r.deleteContents(); } catch (ex) {}
            var emptyBqs = ea.querySelectorAll('blockquote');
            for (var qi = emptyBqs.length - 1; qi >= 0; qi--) {
              var bq = emptyBqs[qi];
              if (!bq.textContent.replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '') && !bq.querySelector('pre, .md-code-block, .admonition, img')) {
                bq.parentNode.removeChild(bq);
              }
            }
            var newP = document.createElement('p');
            newP.innerHTML = '<br>';
            if (insertionParent && ea.contains(insertionParent)) {
              if (insertionRef && insertionParent.contains(insertionRef)) {
                insertionParent.insertBefore(newP, insertionRef);
              } else {
                insertionParent.appendChild(newP);
              }
            } else {
              ea.appendChild(newP);
            }
            var range = document.createRange();
            range.setStart(newP, 0);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            if (wysiwygEditor._finalizeUpdate) {
              wysiwygEditor._finalizeUpdate(ea.innerHTML);
            }
            return;
          }
          var node = sel.anchorNode;
          var pre = null;
          var wrapper = null;
          var anc = node;
          while (anc && anc !== ea) {
            if (anc.nodeName === 'PRE') pre = anc;
            if (anc.classList && anc.classList.contains('md-code-block')) wrapper = anc;
            anc = anc.parentNode;
          }
          if (!pre) return;
          var codeEl = pre.querySelector('code') || pre;
          var content = codeEl.textContent;
          var blockContainer = wrapper || pre;

          if (content === '' || content === '\n') {
            e.preventDefault();
            var preEl = blockContainer.nodeName === 'PRE' ? blockContainer : blockContainer.querySelector('pre');
            var literal = preEl && preEl.getAttribute('data-md-literal');
            var parentNode = blockContainer.parentNode;
            var nextSib = blockContainer.nextSibling;
            parentNode.removeChild(blockContainer);
            var p = document.createElement('p');
            if (literal) {
              p.style.whiteSpace = 'pre-wrap';
              p.textContent = literal;
            } else {
              p.appendChild(document.createElement('br'));
            }
            if (nextSib) {
              parentNode.insertBefore(p, nextSib);
            } else {
              parentNode.appendChild(p);
            }
            var range = document.createRange();
            if (literal) {
              var textNode = p.firstChild;
              if (!textNode || textNode.nodeType !== 3) textNode = p;
              range.setStart(textNode, (textNode.textContent || '').length);
            } else {
              range.setStart(p, 0);
            }
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            if (wysiwygEditor._finalizeUpdate) {
              wysiwygEditor._finalizeUpdate(ea.innerHTML);
            }
            return;
          }

      };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
      _ekh.admonitionBackspace = function (e) {
          if (e.key !== 'Backspace') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var node = sel.anchorNode;
          if (node.nodeType === 3) node = node.parentNode;
          var ad = null;
          var inTitle = false;
          var anc = node;
          while (anc && anc !== ea) {
            if (anc.classList && anc.classList.contains('admonition')) {
              ad = anc;
              var titleEl = ad.querySelector('.admonition-title');
              inTitle = titleEl && (titleEl === node || titleEl.contains(node));
              break;
            }
            anc = anc.parentNode;
          }
          if (!ad) return;
          if (inTitle) {
            var titleEl = ad.querySelector('.admonition-title');
            var titleText = (titleEl.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
            if (titleText.length === 0) {
              e.preventDefault();
              return;
            }
            var r = sel.getRangeAt(0);
            var atStart = false;
            var sn = r.startContainer;
            var so = r.startOffset;
            if (sn === titleEl && so === 0) {
              atStart = true;
            } else if (sn.nodeType === 3 && so === 0) {
              var prev = sn;
              while (prev && prev !== titleEl) {
                if (prev.previousSibling) { atStart = false; break; }
                prev = prev.parentNode;
                if (prev === titleEl) { atStart = true; break; }
              }
            } else if (sn.nodeType === 1 && so === 0 && (sn === titleEl || titleEl.contains(sn))) {
              var prev = sn;
              while (prev && prev !== titleEl) {
                if (prev.previousSibling) { atStart = false; break; }
                prev = prev.parentNode;
                if (prev === titleEl) { atStart = true; break; }
              }
            }
            if (atStart) {
              e.preventDefault();
            }
            return;
          }
          var bodyContent = '';
          for (var j = 0; j < ad.childNodes.length; j++) {
            var c = ad.childNodes[j];
            if (c.nodeType === 1 && c.classList && c.classList.contains('admonition-title')) continue;
            bodyContent += (c.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
          }
          bodyContent = bodyContent.replace(/\s/g, '');
          if (bodyContent.length === 0) {
            e.preventDefault();
            var nextSib = ad.nextSibling;
            var parentNode = ad.parentNode;
            parentNode.removeChild(ad);
            var p = document.createElement('p');
            var br = document.createElement('br');
            p.appendChild(br);
            if (nextSib) {
              parentNode.insertBefore(p, nextSib);
            } else {
              parentNode.appendChild(p);
            }
            var range = document.createRange();
            range.setStart(p, 0);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            if (wysiwygEditor._finalizeUpdate) {
              wysiwygEditor._finalizeUpdate(ea.innerHTML);
            }
          }
      };
    })();

    (function reverseBubbleHandler() {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
        var stripMarkers = /[\u200B\u200C\u200D\uFEFF]/g;

        function isSiblingInvisible(ps) {
          if (ps.nodeType === 1 && ps.nodeName === 'INPUT') return true;
          var text = (ps.textContent || '').replace(stripMarkers, '');
          if (text.length === 0) return true;
          if (ps.nodeType === 3 && text.trim().length === 0) {
            var prv = ps.previousSibling;
            if (prv && prv.nodeType === 1 && prv.nodeName === 'INPUT') return true;
          }
          return false;
        }

        function isAtStartOf(refEl, r) {
          var sc = r.startContainer;
          var so = r.startOffset;
          if (sc === refEl && so === 0) return true;
          if (sc.nodeType === 3) {
            if (so > 0) {
              var tb = sc.textContent.substring(0, so).replace(stripMarkers, '');
              if (tb.length > 0) return false;
            }
            var prev = sc;
            while (prev) {
              var ps = prev.previousSibling;
              if (ps) {
                if (!isSiblingInvisible(ps)) return false;
                prev = ps;
              } else {
                if (prev.parentNode === refEl) return true;
                prev = prev.parentNode;
              }
            }
          } else if (sc.nodeType === 1 && (sc === refEl || refEl.contains(sc))) {
            for (var ci = 0; ci < so; ci++) {
              if (!isSiblingInvisible(sc.childNodes[ci])) return false;
            }
            if (sc === refEl) return true;
            var prev = sc;
            while (prev && prev !== refEl) {
              var ps = prev.previousSibling;
              while (ps) {
                if (!isSiblingInvisible(ps)) return false;
                ps = ps.previousSibling;
              }
              prev = prev.parentNode;
              if (prev === refEl) return true;
            }
          }
          return false;
        }

        function isAdmonitionChrome(ch, isAdmonition) {
          if (!isAdmonition) return false;
          if (ch.nodeName === 'SUMMARY') return true;
          if (ch.classList && (ch.classList.contains('admonition-title') || ch.classList.contains('md-admonition-settings-btn'))) return true;
          return false;
        }

        function hasContentBeyond(container, skipEl, isAdmonition) {
          for (var ch = container.firstChild; ch; ch = ch.nextSibling) {
            if (ch === skipEl) continue;
            if (ch.nodeType !== 1) continue;
            if (isAdmonitionChrome(ch, isAdmonition)) continue;
            var t = (ch.textContent || '').replace(stripMarkers, '').replace(/\s/g, '');
            if (t.length > 0) return true;
            if (ch.querySelector && ch.querySelector('img, pre, .md-code-block, .admonition, details, table, blockquote, ul, ol')) return true;
          }
          return false;
        }

        function containerHasContent(container, isAdmonition) {
          for (var ch = container.firstChild; ch; ch = ch.nextSibling) {
            if (ch.nodeType !== 1) continue;
            if (isAdmonitionChrome(ch, isAdmonition)) continue;
            var t = (ch.textContent || '').replace(stripMarkers, '').replace(/\s/g, '');
            if (t.length > 0) return true;
            if (ch.querySelector && ch.querySelector('img, pre, .md-code-block, .admonition, details, table, blockquote, ul, ol')) return true;
          }
          return false;
        }

        function getFirstBodyEl(container, isAdmonition) {
          for (var ch = container.firstChild; ch; ch = ch.nextSibling) {
            if (ch.nodeType !== 1) continue;
            if (isAdmonitionChrome(ch, isAdmonition)) continue;
            return ch;
          }
          return null;
        }

        function isEmptyBlock(el) {
          var t = (el.textContent || '').replace(stripMarkers, '').replace(/\s/g, '');
          if (t.length > 0) return false;
          var onlyBr = el.childNodes.length <= 1 && (!el.firstChild || el.firstChild.nodeName === 'BR');
          return onlyBr || el.childNodes.length === 0 || t.length === 0;
        }

        function doInsertAndFocus(p, refEl, insertInside, sel) {
          if (insertInside) {
            refEl.parentNode.insertBefore(p, refEl);
          } else {
            refEl.parentNode.insertBefore(p, refEl);
          }
          var range = document.createRange();
          if (p.firstChild && p.firstChild.nodeType === 3) {
            range.setStart(p.firstChild, 0);
          } else {
            range.setStart(p, 0);
          }
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        }

        _ekh.reverseBubble = function (e) {
          if (e.key !== 'Enter' || e.shiftKey) return;
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var r = sel.getRangeAt(0);
          var node = r.startContainer;
          if (node.nodeType === 3) node = node.parentNode;

          var container = null;
          var containerType = null;
          var pre = null;
          var codeBlockWrapper = null;
          var anc = node;
          while (anc && anc !== ea) {
            if (anc.nodeName === 'PRE') { pre = anc; }
            if (anc.classList && anc.classList.contains('md-code-block')) { codeBlockWrapper = anc; }
            if (!container) {
              if (anc.nodeName === 'BLOCKQUOTE') { container = anc; containerType = 'blockquote'; }
              else if (isAdmonitionElement(anc)) { container = anc; containerType = 'admonition'; }
            }
            anc = anc.parentNode;
          }

          // Case D: code block body
          if (pre) {
            var codeEl = pre.querySelector('code');
            var target = codeEl || pre;
            var fullText = (target.textContent || '').replace(stripMarkers, '');
            if (!fullText.replace(/[\s\n\r]/g, '')) return;

            var cursorOffset = 0;
            if (codeEl && codeEl.contains(r.startContainer)) {
              var walker = document.createTreeWalker(codeEl, NodeFilter.SHOW_TEXT, null, false);
              var wn;
              while ((wn = walker.nextNode())) {
                if (wn === r.startContainer) { cursorOffset += r.startOffset; break; }
                cursorOffset += wn.textContent.length;
              }
            } else if (r.startContainer === pre && r.startOffset === 0) {
              cursorOffset = 0;
            } else {
              return;
            }
            var textBeforeCursor = fullText.substring(0, cursorOffset).replace(stripMarkers, '');
            if (textBeforeCursor.replace(/[\s\n\r]/g, '').length > 0) return;

            e.preventDefault();
            e.stopImmediatePropagation();
            var blockContainer = codeBlockWrapper || pre;
            var el = pre;
            while (el && el !== ea) {
              if (el.classList && el.classList.contains('md-code-block')) { blockContainer = el; }
              el = el.parentNode;
            }
            var p = document.createElement('p');
            p.innerHTML = '<br>';
            doInsertAndFocus(p, blockContainer, false, sel);
            return;
          }

          // Root-level list reverse bubble
          if (!container) {
            var rootList = null;
            var rootLi = null;
            var anc2 = node;
            while (anc2 && anc2 !== ea) {
              if (anc2.nodeName === 'LI' && !rootLi) rootLi = anc2;
              if ((anc2.nodeName === 'UL' || anc2.nodeName === 'OL') && anc2.parentNode === ea) {
                rootList = anc2;
                break;
              }
              anc2 = anc2.parentNode;
            }
            if (!rootList || !rootLi) return;
            var listText = (rootList.textContent || '').replace(stripMarkers, '').replace(/\s/g, '');
            if (listText.length === 0) return;
            var firstLi = null;
            for (var ch = rootList.firstChild; ch; ch = ch.nextSibling) {
              if (ch.nodeName === 'LI') { firstLi = ch; break; }
            }
            if (!firstLi) return;
            var liAnc = node;
            while (liAnc && liAnc !== rootList) {
              if (liAnc === firstLi) break;
              liAnc = liAnc.parentNode;
            }
            if (liAnc !== firstLi) return;
            if (!isAtStartOf(firstLi, r)) return;

            e.preventDefault();
            e.stopImmediatePropagation();
            var p = document.createElement('p');
            p.innerHTML = '<br>';
            ea.insertBefore(p, rootList);
            var range = document.createRange();
            range.setStart(p, 0);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            if (wysiwygEditor._finalizeUpdate) {
              wysiwygEditor._finalizeUpdate(ea.innerHTML);
            }
            return;
          }
          var isAd = containerType === 'admonition';

          // For admonitions, skip if cursor is in the title
          if (isAd) {
            var titleEl = container.querySelector('.admonition-title') || container.querySelector(':scope > summary');
            if (titleEl && (titleEl === node || titleEl.contains(node) || titleEl.contains(r.startContainer))) return;
          }

          if (!containerHasContent(container, isAd)) return;

          var firstBodyEl = getFirstBodyEl(container, isAd);
          if (!firstBodyEl) return;

          var cursorDirectChild = node;
          while (cursorDirectChild && cursorDirectChild.parentNode !== container) {
            cursorDirectChild = cursorDirectChild.parentNode;
          }
          if (!cursorDirectChild) return;

          // Case B: list as first body element
          if ((firstBodyEl.nodeName === 'UL' || firstBodyEl.nodeName === 'OL') && cursorDirectChild === firstBodyEl) {
            var firstLi = null;
            for (var ch = firstBodyEl.firstChild; ch; ch = ch.nextSibling) {
              if (ch.nodeName === 'LI') { firstLi = ch; break; }
            }
            if (!firstLi) return;
            var liAnc = node;
            while (liAnc && liAnc !== firstBodyEl) {
              if (liAnc === firstLi) break;
              liAnc = liAnc.parentNode;
            }
            if (liAnc !== firstLi) return;
            if (!isAtStartOf(firstLi, r)) return;

            e.preventDefault();
            e.stopImmediatePropagation();
            var p = document.createElement('p');
            p.innerHTML = '<br>';
            container.insertBefore(p, firstBodyEl);
            if (container.nodeName === 'BLOCKQUOTE') {
              ea.__liveWysiwygBlockquoteEnterCredit = { count: 2, bq: container };
            } else if (isAdmonitionElement(container)) {
              ea.__liveWysiwygAdmonitionEnterCredit = { count: 2, ad: container };
            }
            var range = document.createRange();
            range.setStart(p, 0);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            if (wysiwygEditor._finalizeUpdate) {
              wysiwygEditor._finalizeUpdate(ea.innerHTML);
            }
            return;
          }

          if (cursorDirectChild !== firstBodyEl) return;

          // Case C: empty P at top with content after it
          if ((firstBodyEl.nodeName === 'P' || firstBodyEl.nodeName === 'DIV') && isEmptyBlock(firstBodyEl)) {
            if (!hasContentBeyond(container, firstBodyEl, isAd)) return;
            e.preventDefault();
            e.stopImmediatePropagation();
            container.removeChild(firstBodyEl);
            container.parentNode.insertBefore(firstBodyEl, container);
            var caseCParent = firstBodyEl.parentNode;
            if (caseCParent && caseCParent !== ea) {
              if (caseCParent.nodeName === 'BLOCKQUOTE') {
                ea.__liveWysiwygBlockquoteEnterCredit = { count: 2, bq: caseCParent };
              } else if (isAdmonitionElement(caseCParent)) {
                ea.__liveWysiwygAdmonitionEnterCredit = { count: 2, ad: caseCParent };
              }
            }
            var range = document.createRange();
            if (firstBodyEl.firstChild && firstBodyEl.firstChild.nodeType === 3) {
              range.setStart(firstBodyEl.firstChild, 0);
            } else {
              range.setStart(firstBodyEl, 0);
            }
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            if (wysiwygEditor._finalizeUpdate) {
              wysiwygEditor._finalizeUpdate(ea.innerHTML);
            }
            return;
          }

          // Case A: non-empty P/heading at start
          if (!isAtStartOf(firstBodyEl, r)) return;

          e.preventDefault();
          e.stopImmediatePropagation();
          var p = document.createElement('p');
          p.innerHTML = '<br>';
          container.parentNode.insertBefore(p, container);
          var caseAParent = p.parentNode;
          if (caseAParent && caseAParent !== ea) {
            if (caseAParent.nodeName === 'BLOCKQUOTE') {
              ea.__liveWysiwygBlockquoteEnterCredit = { count: 2, bq: caseAParent };
            } else if (isAdmonitionElement(caseAParent)) {
              ea.__liveWysiwygAdmonitionEnterCredit = { count: 2, ad: caseAParent };
            }
          }
          var range = document.createRange();
          range.setStart(p, 0);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
        var listConsecutiveEnters = 0;
        var lastEnterList = null;
        var stripMarkersList = /[\u200B\u200C\u200D\uFEFF]/g;
        function isLiEmpty(li) {
          var t = (li.textContent || '').replace(stripMarkersList, '').replace(/[\s ]/g, '');
          return t.length === 0;
        }
        _ekh.listEnterExit = function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg' || e.key !== 'Enter' || e.shiftKey) return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) {
            listConsecutiveEnters = 0;
            lastEnterList = null;
            return;
          }
          var r = sel.getRangeAt(0);
          var node = r.startContainer;
          if (node.nodeType === 3) node = node.parentNode;
          var list = null;
          var li = null;
          var anc = node;
          while (anc && anc !== ea) {
            if (anc.nodeName === 'LI') li = anc;
            if (anc.nodeName === 'UL' || anc.nodeName === 'OL') {
              list = anc;
              break;
            }
            anc = anc.parentNode;
          }
          if (!list || !li) {
            listConsecutiveEnters = 0;
            lastEnterList = null;
            return;
          }

          if (lastEnterList !== list) {
            listConsecutiveEnters = 0;
            lastEnterList = list;
          }
          if (!isLiEmpty(li)) {
            listConsecutiveEnters++;
            if (listConsecutiveEnters < 2) return;
            return;
          }
          listConsecutiveEnters++;
          if (listConsecutiveEnters < 2) return;
          var hasLiAfter = false;
          var nextLi = li.nextSibling;
          while (nextLi) {
            if (nextLi.nodeName === 'LI' && !isLiEmpty(nextLi)) {
              hasLiAfter = true;
              break;
            }
            nextLi = nextLi.nextSibling;
          }
          if (hasLiAfter) {
            listConsecutiveEnters = 0;
            return;
          }
          e.preventDefault();
          e.stopImmediatePropagation();
          listConsecutiveEnters = 0;
          lastEnterList = null;
          var lis = [];
          for (var j = 0; j < list.childNodes.length; j++) {
            if (list.childNodes[j].nodeName === 'LI') lis.push(list.childNodes[j]);
          }
          var removed = 0;
          for (var i = lis.length - 1; i >= 0 && removed < 2; i--) {
            if (isLiEmpty(lis[i])) {
              list.removeChild(lis[i]);
              removed++;
            } else {
              break;
            }
          }
          var parentLi = list.parentNode;
          var isNestedList = parentLi && parentLi.nodeName === 'LI';
          if (isNestedList) {
            var parentList = parentLi.parentNode;
            if (parentList && (parentList.nodeName === 'UL' || parentList.nodeName === 'OL')) {
              if (list.childNodes.length === 0) {
                parentLi.removeChild(list);
              }
              var newLi = document.createElement('li');
              var hasCheckbox = false;
              for (var k = 0; k < parentList.children.length; k++) {
                var sib = parentList.children[k];
                if (sib.nodeName === 'LI') {
                  var cb = sib.querySelector('input[type="checkbox"]');
                  if (cb && cb.parentNode === sib) { hasCheckbox = true; break; }
                }
              }
              if (hasCheckbox) {
                var prevCb = getDirectCheckboxOfLi(parentLi);
                addCheckboxToLi(newLi, prevCb ? prevCb.checked : false);
              } else newLi.innerHTML = '<br>';
              var nextSib = parentLi.nextSibling;
              if (nextSib) {
                parentList.insertBefore(newLi, nextSib);
              } else {
                parentList.appendChild(newLi);
              }
              var range = document.createRange();
              if (hasCheckbox) {
                var space = newLi.querySelector('input[type="checkbox"]');
                if (space) space = space.nextSibling;
                if (space && space.nodeType === 3) range.setStart(space, space.length || 1);
                else range.setStart(newLi, 0);
              } else {
                range.setStart(newLi, 0);
              }
              range.collapse(true);
              sel.removeAllRanges();
              sel.addRange(range);
              if (wysiwygEditor._finalizeUpdate) {
                wysiwygEditor._finalizeUpdate(ea.innerHTML);
              }
              return;
            }
          }
          var p = document.createElement('p');
          p.innerHTML = '<br>';
          var insertParent, insertBefore;
          var adFromList = null;
          if (list.childNodes.length === 0) {
            var listParent = list.parentNode;
            var nextSib = list.nextSibling;
            listParent.removeChild(list);
            if (listParent.nodeName === 'BLOCKQUOTE') {
              insertParent = listParent;
              insertBefore = nextSib;
            } else {
              var a = listParent;
              while (a && a !== ea) {
                if (isAdmonitionElement(a)) { adFromList = a; break; }
                a = a.parentNode;
              }
              if (adFromList && listParent.parentNode === adFromList) {
                insertParent = adFromList;
                insertBefore = listParent.nextSibling;
              } else {
                insertParent = listParent.parentNode;
                insertBefore = listParent.nextSibling;
              }
            }
          } else {
            var bodyEl = list.parentNode;
            if (bodyEl.nodeName === 'BLOCKQUOTE') {
              insertParent = bodyEl;
              insertBefore = list.nextSibling;
            } else {
              var a = bodyEl;
              while (a && a !== ea) {
                if (isAdmonitionElement(a)) { adFromList = a; break; }
                a = a.parentNode;
              }
              if (adFromList && bodyEl.parentNode === adFromList) {
                insertParent = adFromList;
                insertBefore = bodyEl.nextSibling;
              } else {
                insertParent = list.parentNode;
                insertBefore = list.nextSibling;
              }
            }
          }
          if (insertBefore) {
            insertParent.insertBefore(p, insertBefore);
          } else {
            insertParent.appendChild(p);
          }
          if (adFromList) {
            addSettingsButtonToAdmonition(adFromList);
            var outerAd = adFromList.parentNode;
            while (outerAd && outerAd !== ea) {
              if (isAdmonitionElement(outerAd)) { addSettingsButtonToAdmonition(outerAd); break; }
              outerAd = outerAd.parentNode;
            }
            ea.__liveWysiwygAdmonitionEnterCredit = { count: 2, ad: adFromList };
          }
          var bqFromList = null;
          var a = insertParent;
          while (a && a !== ea) {
            if (a.nodeName === 'BLOCKQUOTE') { bqFromList = a; break; }
            a = a.parentNode;
          }
          if (bqFromList) {
            ea.__liveWysiwygBlockquoteEnterCredit = { count: 2, bq: bqFromList };
          }
          var range = document.createRange();
          range.setStart(p, 0);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
        var adConsecutiveEnters = 0;
        var lastEnterAd = null;
        _ekh.admonitionEnterExit = function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg' || e.key !== 'Enter') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) {
            adConsecutiveEnters = 0;
            lastEnterAd = null;
            return;
          }
          var node = sel.anchorNode;
          if (node.nodeType === 3) node = node.parentNode;
          var ad = null;
          var inTitle = false;
          var anc = node;
          while (anc && anc !== ea) {
            if (isAdmonitionElement(anc)) {
              ad = anc;
              var titleEl = ad.querySelector('.admonition-title') || ad.querySelector(':scope > summary');
              inTitle = titleEl && (titleEl === node || titleEl.contains(node));
              break;
            }
            anc = anc.parentNode;
          }
          if (!ad) {
            adConsecutiveEnters = 0;
            lastEnterAd = null;
            return;
          }
          if (inTitle) {
            adConsecutiveEnters = 0;
            lastEnterAd = null;
            e.preventDefault();
            var titleEl = ad.querySelector('.admonition-title') || ad.querySelector(':scope > summary');
            var r = sel.getRangeAt(0);
            var checkRange = document.createRange();
            checkRange.setStart(titleEl, 0);
            checkRange.setEnd(r.startContainer, r.startOffset);
            var atTitleStart = checkRange.toString().length === 0;
            var titleText = (titleEl.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
            if (atTitleStart && titleText.length > 0) {
              var p = document.createElement('p');
              p.innerHTML = '<br>';
              ad.parentNode.insertBefore(p, ad);
              var range = document.createRange();
              range.setStart(p, 0);
              range.collapse(true);
              sel.removeAllRanges();
              sel.addRange(range);
              if (wysiwygEditor._finalizeUpdate) {
                wysiwygEditor._finalizeUpdate(ea.innerHTML);
              }
            } else {
              if (titleText.length === 0) {
                var adType = null;
                var types = ['note', 'warning', 'danger', 'tip', 'hint', 'important', 'caution', 'error', 'attention'];
                for (var ti = 0; ti < types.length; ti++) {
                  if (ad.classList.contains(types[ti])) { adType = types[ti]; break; }
                }
                if (adType) {
                  titleEl.textContent = adType.charAt(0).toUpperCase() + adType.slice(1);
                } else {
                  titleEl.textContent = 'Note';
                }
              }
              var firstBody = null;
              for (var ci = 0; ci < ad.childNodes.length; ci++) {
                var cn = ad.childNodes[ci];
                if (cn.nodeType === 1 && cn !== titleEl && cn.nodeName !== 'BR') {
                  firstBody = cn;
                  break;
                }
              }
              if (!firstBody) {
                firstBody = document.createElement('p');
                firstBody.innerHTML = '<br>';
                ad.appendChild(firstBody);
              }
              var range = document.createRange();
              if (firstBody.firstChild && firstBody.firstChild.nodeType === 3) {
                range.setStart(firstBody.firstChild, 0);
              } else {
                range.setStart(firstBody, 0);
              }
              range.collapse(true);
              sel.removeAllRanges();
              sel.addRange(range);
              if (wysiwygEditor._finalizeUpdate) {
                wysiwygEditor._finalizeUpdate(ea.innerHTML);
              }
            }
            return;
          }
          if (e.shiftKey) return;
          var inListItem = false;
          var a = node;
          while (a && a !== ad) {
            if (a.nodeName === 'LI') { inListItem = true; break; }
            a = a.parentNode;
          }
          if (inListItem) {
            adConsecutiveEnters = 0;
            lastEnterAd = null;
            return;
          }
          var directChild = node;
          while (directChild && directChild.parentNode !== ad) {
            directChild = directChild.parentNode;
          }
          var isBlock = directChild && (directChild.nodeName === 'P' || directChild.nodeName === 'DIV') && (!directChild.classList || !directChild.classList.contains('admonition-title'));
          if (!isBlock) {
            adConsecutiveEnters = 0;
            lastEnterAd = null;
            return;
          }
          var hadCredit = false;
          var credit = ea.__liveWysiwygAdmonitionEnterCredit;
          if (credit && credit.ad === ad) {
            ea.__liveWysiwygAdmonitionEnterCredit = null;
            var blockTextCheck = (directChild.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
            var onlyBr = directChild.childNodes.length === 1 && directChild.firstChild && directChild.firstChild.nodeName === 'BR';
            var hasContent = blockTextCheck.length > 0 && !onlyBr;
            if (hasContent) {
              adConsecutiveEnters = 0;
              lastEnterAd = ad;
            } else {
              adConsecutiveEnters = credit.count;
              lastEnterAd = ad;
              hadCredit = true;
            }
          } else if (lastEnterAd !== ad) {
            adConsecutiveEnters = 0;
            lastEnterAd = ad;
          }
          adConsecutiveEnters++;
          if (adConsecutiveEnters < 3) return;
          var hasContentAfter = false;
          var sib = directChild ? directChild.nextSibling : null;
          while (sib) {
            if (sib.nodeType === 1) {
              var sibText = (sib.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
              if (sibText.length > 0 || sib.querySelector('img:not([data-emoji-shortcode])')) { hasContentAfter = true; break; }
            } else if (sib.nodeType === 3) {
              var sibText = (sib.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
              if (sibText.length > 0) { hasContentAfter = true; break; }
            }
            sib = sib.nextSibling;
          }
          if (hasContentAfter) {
            adConsecutiveEnters = 0;
            return;
          }
          e.preventDefault();
          e.stopImmediatePropagation();
          adConsecutiveEnters = 0;
          lastEnterAd = null;
          var stripMarkersAd = /[\u200B\u200C\u200D\uFEFF]/g;
          function removeTrailingEmptyBlocks(container) {
            var kids = container.childNodes;
            for (var i = kids.length - 1; i >= 0; i--) {
              var k = kids[i];
              if (k.nodeType !== 1) continue;
              var tag = k.nodeName;
              if (tag !== 'P' && tag !== 'DIV') continue;
              var t = (k.textContent || '').replace(stripMarkersAd, '').replace(/\s/g, '');
              if (t.length === 0 && !k.querySelector('img:not([data-emoji-shortcode])')) {
                container.removeChild(k);
              } else {
                break;
              }
            }
          }
          var bodyEls = [];
          for (var j = 0; j < ad.childNodes.length; j++) {
            var c = ad.childNodes[j];
            if (c.nodeType !== 1) continue;
            if (c.nodeName === 'SUMMARY' || (c.classList && (c.classList.contains('admonition-title') || c.classList.contains('md-admonition-settings-btn')))) continue;
            removeTrailingEmptyBlocks(c);
            bodyEls.push(c);
          }
          var maxToRemove = hadCredit ? 1 : 999;
          var removed = 0;
          while (bodyEls.length > 0 && removed < maxToRemove) {
            var last = bodyEls[bodyEls.length - 1];
            var t = (last.textContent || '').replace(stripMarkersAd, '').replace(/\s/g, '');
            if (t.length === 0 && !last.querySelector('img:not([data-emoji-shortcode])')) {
              ad.removeChild(last);
              bodyEls.pop();
              removed++;
            } else {
              var txt = (last.textContent || '').replace(stripMarkersAd, '');
              var trimmed = txt.replace(/\n+$/, '');
              if (trimmed !== txt && last.childNodes.length === 1 && last.firstChild && last.firstChild.nodeType === 3) {
                last.firstChild.textContent = trimmed;
              }
              break;
            }
          }
          addSettingsButtonToAdmonition(ad);
          var p = document.createElement('p');
          p.innerHTML = '<br>';
          if (ad.nextSibling) {
            ad.parentNode.insertBefore(p, ad.nextSibling);
          } else {
            ad.parentNode.appendChild(p);
          }
          var range = document.createRange();
          range.setStart(p, 0);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          var adParent = ad.parentNode;
          if (adParent && adParent.nodeName === 'BLOCKQUOTE') {
            ea.__liveWysiwygBlockquoteEnterCredit = { count: 2, bq: adParent };
          } else if (adParent && isAdmonitionElement(adParent)) {
            addSettingsButtonToAdmonition(adParent);
            ea.__liveWysiwygAdmonitionEnterCredit = { count: 2, ad: adParent };
          }
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
        var bqConsecutiveEnters = 0;
        var lastEnterBq = null;
        _ekh.blockquoteEnterExit = function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg' || e.key !== 'Enter' || e.shiftKey) return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) {
            bqConsecutiveEnters = 0;
            lastEnterBq = null;
            return;
          }
          var node = sel.anchorNode;
          if (node.nodeType === 3) node = node.parentNode;
          var bq = null;
          var anc = node;
          while (anc && anc !== ea) {
            if (anc.nodeName === 'BLOCKQUOTE') {
              bq = anc;
              break;
            }
            anc = anc.parentNode;
          }
          if (!bq) {
            bqConsecutiveEnters = 0;
            lastEnterBq = null;
            return;
          }
          var inAdmonition = false;
          var a = node;
          while (a && a !== bq) {
            if (isAdmonitionElement(a)) { inAdmonition = true; break; }
            a = a.parentNode;
          }
          if (inAdmonition) {
            bqConsecutiveEnters = 0;
            lastEnterBq = null;
            return;
          }
          var inListItem = false;
          var a = node;
          while (a && a !== bq) {
            if (a.nodeName === 'LI') { inListItem = true; break; }
            a = a.parentNode;
          }
          if (inListItem) {
            bqConsecutiveEnters = 0;
            lastEnterBq = null;
            return;
          }
          var directChild = node;
          while (directChild && directChild.parentNode !== bq) {
            directChild = directChild.parentNode;
          }
          var isAdmonitionChild = directChild && isAdmonitionElement(directChild);
          var isBlock = directChild && (directChild.nodeName === 'P' || directChild.nodeName === 'DIV') && !isAdmonitionChild;
          if (!isBlock) {
            bqConsecutiveEnters = 0;
            lastEnterBq = null;
            return;
          }
          var cursorBlock = node;
          while (cursorBlock && cursorBlock !== bq && cursorBlock.nodeName !== 'P' && cursorBlock.nodeName !== 'DIV') {
            cursorBlock = cursorBlock.parentNode;
          }
          var hadCredit = false;
          var credit = ea.__liveWysiwygBlockquoteEnterCredit;
          if (credit && credit.bq === bq) {
            ea.__liveWysiwygBlockquoteEnterCredit = null;
            var contentBlock = (cursorBlock && cursorBlock !== bq) ? cursorBlock : directChild;
            var blockTextCheck = (contentBlock.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
            var onlyBr = contentBlock.childNodes.length === 1 && contentBlock.firstChild && contentBlock.firstChild.nodeName === 'BR';
            var hasContent = blockTextCheck.length > 0 && !onlyBr;
            if (hasContent) {
              bqConsecutiveEnters = 0;
              lastEnterBq = bq;
            } else {
              bqConsecutiveEnters = credit.count;
              lastEnterBq = bq;
              hadCredit = true;
            }
          } else if (lastEnterBq !== bq) {
            bqConsecutiveEnters = 0;
            lastEnterBq = bq;
          }
          bqConsecutiveEnters++;
          if (bqConsecutiveEnters < 3) return;
          var hasContentAfterBq = false;
          var sibBq = directChild ? directChild.nextSibling : null;
          while (sibBq) {
            if (sibBq.nodeType === 1) {
              var sibTextBq = (sibBq.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
              if (sibTextBq.length > 0 || sibBq.querySelector('img:not([data-emoji-shortcode])')) { hasContentAfterBq = true; break; }
            } else if (sibBq.nodeType === 3) {
              var sibTextBq = (sibBq.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
              if (sibTextBq.length > 0) { hasContentAfterBq = true; break; }
            }
            sibBq = sibBq.nextSibling;
          }
          if (hasContentAfterBq) {
            bqConsecutiveEnters = 0;
            return;
          }
          e.preventDefault();
          e.stopImmediatePropagation();
          bqConsecutiveEnters = 0;
          lastEnterBq = null;
          var stripMarkersBq = /[\u200B\u200C\u200D\uFEFF]/g;
          function removeTrailingEmptyBlocksBq(container) {
            var kids = container.childNodes;
            for (var i = kids.length - 1; i >= 0; i--) {
              var k = kids[i];
              if (k.nodeType !== 1) continue;
              var tag = k.nodeName;
              if (tag !== 'P' && tag !== 'DIV') continue;
              var t = (k.textContent || '').replace(stripMarkersBq, '').replace(/\s/g, '');
              if (t.length === 0 && !k.querySelector('img:not([data-emoji-shortcode])')) {
                container.removeChild(k);
              } else {
                break;
              }
            }
          }
          var bodyEls = [];
          for (var j = 0; j < bq.childNodes.length; j++) {
            var c = bq.childNodes[j];
            if (c.nodeType !== 1) continue;
            removeTrailingEmptyBlocksBq(c);
            bodyEls.push(c);
          }
          var maxToRemove = hadCredit ? 1 : 999;
          var removed = 0;
          while (bodyEls.length > 0 && removed < maxToRemove) {
            var last = bodyEls[bodyEls.length - 1];
            var t = (last.textContent || '').replace(stripMarkersBq, '').replace(/\s/g, '');
            if (t.length === 0 && !last.querySelector('img:not([data-emoji-shortcode])')) {
              bq.removeChild(last);
              bodyEls.pop();
              removed++;
            } else {
              var txt = (last.textContent || '').replace(stripMarkersBq, '');
              var trimmed = txt.replace(/\n+$/, '');
              if (trimmed !== txt && last.childNodes.length === 1 && last.firstChild && last.firstChild.nodeType === 3) {
                last.firstChild.textContent = trimmed;
              }
              break;
            }
          }
          var p = document.createElement('p');
          p.innerHTML = '<br>';
          if (bq.nextSibling) {
            bq.parentNode.insertBefore(p, bq.nextSibling);
          } else {
            bq.parentNode.appendChild(p);
          }
          var adFromBq = null;
          var aBq = p.parentNode;
          while (aBq && aBq !== ea) {
            if (isAdmonitionElement(aBq)) { adFromBq = aBq; break; }
            aBq = aBq.parentNode;
          }
          if (adFromBq) {
            ea.__liveWysiwygAdmonitionEnterCredit = { count: 2, ad: adFromBq };
          }
          var range = document.createRange();
          range.setStart(p, 0);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
      _ekh.headingEnter = function (e) {
          if (e.key !== 'Enter' || e.shiftKey) return;
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var r = sel.getRangeAt(0);
          var node = r.startContainer;
          var heading = null;
          var el = (node.nodeType === 3) ? node.parentNode : node;
          while (el && el !== ea) {
            if (/^H[1-6]$/.test(el.nodeName)) { heading = el; break; }
            el = el.parentNode;
          }
          if (!heading) return;
          var atStart = false;
          if (r.startContainer === heading && r.startOffset === 0) {
            atStart = true;
          } else if (r.startContainer.nodeType === 3 && r.startOffset === 0) {
            var prev = r.startContainer;
            while (prev) {
              var ps = prev.previousSibling;
              if (ps) {
                var text = (ps.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
                if (text.length > 0) break;
                prev = ps;
              } else {
                if (prev.parentNode === heading) { atStart = true; break; }
                prev = prev.parentNode;
              }
            }
          }
          if (!atStart) return;
          e.preventDefault();
          var p = document.createElement('p');
          p.innerHTML = '&#8203;';
          heading.parentNode.insertBefore(p, heading);
          var newRange = document.createRange();
          newRange.setStart(p.firstChild || p, 0);
          newRange.collapse(true);
          sel.removeAllRanges();
          sel.addRange(newRange);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
      };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
      _ekh.hiddenTitleAdmonitionEnter = function (e) {
          if (e.key !== 'Enter' || e.shiftKey) return;
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
          var r = sel.getRangeAt(0);
          var node = r.startContainer;
          var admonition = null;
          var el = (node.nodeType === 3) ? node.parentNode : node;
          while (el && el !== ea) {
            if (isAdmonitionElement(el)) { admonition = el; break; }
            el = el.parentNode;
          }
          if (!admonition || !admonition.hasAttribute('data-hide-title')) return;

          var firstContent = null;
          for (var ch = admonition.firstChild; ch; ch = ch.nextSibling) {
            if (ch.nodeType !== 1) continue;
            if (ch.classList && ch.classList.contains('md-admonition-settings-btn')) continue;
            firstContent = ch;
            break;
          }
          if (!firstContent) return;

          var cursorBlock = node;
          while (cursorBlock && cursorBlock.parentNode !== admonition) {
            cursorBlock = cursorBlock.parentNode;
          }
          if (cursorBlock !== firstContent) return;

          var atStart = false;
          if (r.startContainer === firstContent && r.startOffset === 0) {
            atStart = true;
          } else if (r.startContainer.nodeType === 3 && r.startOffset === 0) {
            var prev = r.startContainer;
            while (prev) {
              var ps = prev.previousSibling;
              if (ps) {
                var text = (ps.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
                if (text.length > 0) break;
                prev = ps;
              } else {
                if (prev.parentNode === firstContent) { atStart = true; break; }
                prev = prev.parentNode;
              }
            }
          }
          if (!atStart) return;

          e.preventDefault();
          var p = document.createElement('p');
          p.innerHTML = '&#8203;';
          admonition.parentNode.insertBefore(p, admonition);
          var newRange = document.createRange();
          newRange.setStart(p.firstChild || p, 0);
          newRange.collapse(true);
          sel.removeAllRanges();
          sel.addRange(newRange);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
      };
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;
        var stripMarkers = /[\u200B\u200C\u200D\uFEFF]/g;
        var consecutiveEnters = 0;
        var lastEnterPre = null;

        _ekh.codeBlockEnterExit = function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;

          var sel = window.getSelection();
          if (!sel || !sel.isCollapsed || !sel.rangeCount) {
            consecutiveEnters = 0;
            lastEnterPre = null;
            return;
          }

          var node = sel.anchorNode;
          var pre = null;
          var wrapper = null;
          var title = null;
          var anc = node;
          while (anc && anc !== ea) {
            if (anc.nodeName === 'PRE') pre = anc;
            if (anc.classList && anc.classList.contains('md-code-block')) wrapper = anc;
            if (anc.classList && anc.classList.contains('md-code-title')) title = anc;
            anc = anc.parentNode;
          }

          if (title && !pre && (e.key === 'Enter' || e.key === 'Backspace')) {
            var titleStripMarkers = /[​‌‍﻿]/g;
            var atTitleStart = false;
            var r = sel.getRangeAt(0);
            var sn = r.startContainer;
            var so = r.startOffset;
            if (sn === title && so === 0) {
              atTitleStart = true;
            } else if (sn.nodeType === 3 && so === 0) {
              var prev = sn;
              while (prev && prev !== title) {
                if (prev.previousSibling) { atTitleStart = false; break; }
                prev = prev.parentNode;
                if (prev === title) { atTitleStart = true; break; }
              }
            } else if (sn.nodeType === 1 && so === 0 && (sn === title || title.contains(sn))) {
              var prev = sn;
              while (prev && prev !== title) {
                if (prev.previousSibling) { atTitleStart = false; break; }
                prev = prev.parentNode;
                if (prev === title) { atTitleStart = true; break; }
              }
            }

            if (e.key === 'Enter') {
              e.preventDefault();
              e.stopImmediatePropagation();
              var titleText = (title.textContent || '').replace(titleStripMarkers, '').trim();
              if (atTitleStart && titleText.length > 0) {
                var codeBlock = wrapper || title.parentNode;
                while (codeBlock && codeBlock !== ea && !(codeBlock.classList && codeBlock.classList.contains('md-code-block'))) {
                  codeBlock = codeBlock.parentNode;
                }
                if (!codeBlock || codeBlock === ea) codeBlock = title.parentNode;
                var p = document.createElement('p');
                p.innerHTML = '<br>';
                codeBlock.parentNode.insertBefore(p, codeBlock);
                var range = document.createRange();
                range.setStart(p, 0);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
                if (wysiwygEditor._finalizeUpdate) {
                  wysiwygEditor._finalizeUpdate(ea.innerHTML);
                }
              } else {
                var codeBlock = wrapper || title.parentNode;
                while (codeBlock && codeBlock !== ea && !(codeBlock.classList && codeBlock.classList.contains('md-code-block'))) {
                  codeBlock = codeBlock.parentNode;
                }
                if (!codeBlock || codeBlock === ea) codeBlock = title.parentNode;
                var targetPre = codeBlock.querySelector('pre');
                if (targetPre) {
                  var codeEl = targetPre.querySelector('code');
                  var focusTarget = codeEl || targetPre;
                  var range = document.createRange();
                  if (focusTarget.firstChild && focusTarget.firstChild.nodeType === 3) {
                    range.setStart(focusTarget.firstChild, 0);
                  } else {
                    range.setStart(focusTarget, 0);
                  }
                  range.collapse(true);
                  sel.removeAllRanges();
                  sel.addRange(range);
                }
              }
              title.blur();
              title.dispatchEvent(new Event('blur'));
              return;
            }

            if (e.key === 'Backspace' && atTitleStart) {
              var titleText = (title.textContent || '').replace(titleStripMarkers, '').trim();
              if (titleText.length > 0) {
                e.preventDefault();
                e.stopImmediatePropagation();
                return;
              }
              e.preventDefault();
              e.stopImmediatePropagation();
              var codeBlock = wrapper || title.parentNode;
              while (codeBlock && codeBlock !== ea && !(codeBlock.classList && codeBlock.classList.contains('md-code-block'))) {
                codeBlock = codeBlock.parentNode;
              }
              if (!codeBlock || codeBlock === ea) return;
              var targetPre = codeBlock.querySelector('pre');
              if (!targetPre) return;
              targetPre.removeAttribute('data-lang');
              targetPre.removeAttribute('data-title');
              targetPre.removeAttribute('data-linenums');
              targetPre.removeAttribute('data-hl-lines');
              var codeEl = targetPre.querySelector('code');
              if (codeEl) codeEl.className = '';
              var parent = codeBlock.parentNode;
              parent.insertBefore(targetPre, codeBlock);
              parent.removeChild(codeBlock);
              targetPre.style.position = 'relative';
              addLangButtonToBasicPre(targetPre, ea);
              var focusTarget = codeEl || targetPre;
              var range = document.createRange();
              if (focusTarget.firstChild && focusTarget.firstChild.nodeType === 3) {
                range.setStart(focusTarget.firstChild, 0);
              } else {
                range.setStart(focusTarget, 0);
              }
              range.collapse(true);
              sel.removeAllRanges();
              sel.addRange(range);
              if (wysiwygEditor._finalizeUpdate) {
                wysiwygEditor._finalizeUpdate(ea.innerHTML);
              }
              return;
            }
          }

          function normalizePreTextNodes(preEl, selection) {
            var codeEl = preEl.querySelector('code');
            if (!codeEl) return;
            var stray = [];
            for (var ci = 0; ci < preEl.childNodes.length; ci++) {
              var cn = preEl.childNodes[ci];
              if (cn === codeEl) continue;
              if (cn.nodeType === 1 && cn.classList && (cn.classList.contains('md-code-lang-btn') || cn.classList.contains('md-code-lang-dropdown') || cn.classList.contains('md-code-settings-btn') || cn.classList.contains('md-code-settings-btn-advanced') || cn.classList.contains('md-code-settings-dropdown') || cn.classList.contains('md-code-line-numbers'))) continue;
              if (cn.nodeType === 3 || cn.nodeType === 1) stray.push(cn);
            }
            if (stray.length === 0) return;
            var r = (selection && selection.rangeCount) ? selection.getRangeAt(0) : null;
            var cursorInStray = false;
            var cursorStrayNode = null;
            var cursorStrayOffset = 0;
            if (r) {
              for (var si = 0; si < stray.length; si++) {
                if (stray[si] === r.startContainer || stray[si].contains(r.startContainer)) {
                  cursorInStray = true;
                  cursorStrayNode = r.startContainer;
                  cursorStrayOffset = r.startOffset;
                  break;
                }
              }
            }
            var offsetInCode = codeEl.textContent.length;
            for (var si = 0; si < stray.length; si++) {
              var txt = stray[si].textContent;
              if (txt) codeEl.appendChild(document.createTextNode(txt));
              preEl.removeChild(stray[si]);
            }
            if (cursorInStray && r) {
              var newOffset = offsetInCode;
              var prevStrayText = '';
              for (var si = 0; si < stray.length; si++) {
                if (stray[si] === cursorStrayNode || stray[si].contains(cursorStrayNode)) {
                  newOffset = offsetInCode + prevStrayText.length + cursorStrayOffset;
                  break;
                }
                prevStrayText += stray[si].textContent;
              }
              var walker = document.createTreeWalker(codeEl, NodeFilter.SHOW_TEXT, null, false);
              var acc = 0;
              var wn;
              while ((wn = walker.nextNode())) {
                if (acc + wn.textContent.length >= newOffset) {
                  r.setStart(wn, newOffset - acc);
                  r.collapse(true);
                  selection.removeAllRanges();
                  selection.addRange(r);
                  break;
                }
                acc += wn.textContent.length;
              }
            }
          }

          if (pre && e.key === 'Tab') {
            e.preventDefault();
            e.stopImmediatePropagation();
            consecutiveEnters = 0;
            lastEnterPre = null;
            normalizePreTextNodes(pre, sel);
            var codeEl = pre.querySelector('code');
            if (codeEl) {
              var r = sel.getRangeAt(0);
              if (codeEl.contains(r.startContainer)) {
                var indentSettings = getIndentSettings();
                var tabStr = indentSettings.type === 'tab' ? '\t' : new Array((indentSettings.size || 4) + 1).join(' ');
                var doc = codeEl.ownerDocument;
                var tabNode = doc.createTextNode(tabStr);
                r.insertNode(tabNode);
                r.setStart(tabNode, tabStr.length);
                r.setEnd(tabNode, tabStr.length);
                r.collapse(true);
                sel.removeAllRanges();
                sel.addRange(r);
                if (ea.dispatchEvent) {
                  ea.dispatchEvent(new Event('input', { bubbles: true }));
                }
              }
            }
            return;
          }

          if (pre && e.key === 'Backspace') {
            var codeEl = pre.querySelector('code');
            var target = codeEl || pre;
            var codeText = (target.textContent || '').replace(stripMarkers, '').replace(/[\s\n\r]/g, '');
            if (codeText.length > 0) {
              var r = sel.getRangeAt(0);
              if (target.contains(r.startContainer) || r.startContainer === target) {
                var atPos0 = false;
                if (r.startContainer === target && r.startOffset === 0) {
                  atPos0 = true;
                } else if (r.startContainer.nodeType === 3 && r.startOffset === 0) {
                  var walker = document.createTreeWalker(target, NodeFilter.SHOW_TEXT, null, false);
                  var first = walker.nextNode();
                  if (first === r.startContainer) atPos0 = true;
                } else if (r.startContainer.nodeType === 1 && r.startOffset === 0 && target.contains(r.startContainer)) {
                  var prev = r.startContainer;
                  while (prev && prev !== target) {
                    if (prev.previousSibling) break;
                    prev = prev.parentNode;
                    if (prev === target) { atPos0 = true; break; }
                  }
                }
                if (atPos0) {
                  e.preventDefault();
                  e.stopImmediatePropagation();
                  return;
                }
              }
            }
          }

          if (e.key !== 'Enter') {
            if (pre && e.key === 'Backspace' && consecutiveEnters > 0) {
              consecutiveEnters = Math.max(0, consecutiveEnters - 1);
            } else {
              consecutiveEnters = 0;
              lastEnterPre = null;
            }
            return;
          }

          if (!pre) {
            consecutiveEnters = 0;
            lastEnterPre = null;
            return;
          }

          if (e.shiftKey) return;

          if (lastEnterPre !== pre) {
            consecutiveEnters = 0;
            lastEnterPre = pre;
          }

          consecutiveEnters++;
          e.preventDefault();
          e.stopImmediatePropagation();
          normalizePreTextNodes(pre, sel);

          if (consecutiveEnters < 3) {
            var codeEl = pre.querySelector('code');
            if (codeEl) {
              var r = sel.getRangeAt(0);
              if (codeEl.contains(r.startContainer)) {
                var indentStr = '';
                var indentSettings = getIndentSettings();
                if (indentSettings.enabled) {
                  var fullText = codeEl.textContent;
                  var cursorOffset = 0;
                  var walker = document.createTreeWalker(codeEl, NodeFilter.SHOW_TEXT, null, false);
                  var wn;
                  while ((wn = walker.nextNode())) {
                    if (wn === r.startContainer) { cursorOffset += r.startOffset; break; }
                    cursorOffset += wn.textContent.length;
                  }
                  var lineStart = fullText.lastIndexOf('\n', cursorOffset - 1) + 1;
                  var currentLine = fullText.substring(lineStart, cursorOffset);
                  var leadingMatch = currentLine.match(/^([ \t]*)/);
                  indentStr = leadingMatch ? leadingMatch[1] : '';
                  var trimmedLine = currentLine.trimEnd();
                  if (/[:{(\[]\s*$/.test(trimmedLine)) {
                    var unit = indentSettings.type === 'tab' ? '\t' : new Array(indentSettings.size + 1).join(' ');
                    indentStr += unit;
                  }
                }
                var doc = codeEl.ownerDocument;
                var nl = doc.createTextNode('\n' + indentStr);
                r.insertNode(nl);
                r.setStart(nl, 1 + indentStr.length);
                r.setEnd(nl, 1 + indentStr.length);
                r.collapse(true);
                sel.removeAllRanges();
                sel.addRange(r);
                var afterText = codeEl.textContent.substring(
                  (function () {
                    var off = 0;
                    var w = doc.createTreeWalker(codeEl, NodeFilter.SHOW_TEXT, null, false);
                    var n;
                    while ((n = w.nextNode())) {
                      if (n === nl) return off + 1 + indentStr.length;
                      off += n.textContent.length;
                    }
                    return codeEl.textContent.length;
                  })()
                );
                if (!afterText || !afterText.replace(/[\n\r\s\t\u200B\u200C\u200D\uFEFF]/g, '')) {
                  var lastTextNode = null;
                  var tw = doc.createTreeWalker(codeEl, NodeFilter.SHOW_TEXT, null, false);
                  var tn;
                  while ((tn = tw.nextNode())) lastTextNode = tn;
                  if (lastTextNode) {
                    if (!lastTextNode.textContent.endsWith('\n')) {
                      lastTextNode.textContent += '\n';
                    }
                  } else {
                    codeEl.appendChild(doc.createTextNode('\n'));
                  }
                }
                if (ea.dispatchEvent) {
                  ea.dispatchEvent(new Event('input', { bubbles: true }));
                }
              }
            }
            return;
          }

          var codeElCheck = pre.querySelector('code');
          var cursorAtEnd = false;
          if (codeElCheck) {
            var rCheck = sel.getRangeAt(0);
            if (codeElCheck.contains(rCheck.startContainer)) {
              var fullTextCheck = codeElCheck.textContent;
              var cursorOffsetCheck = 0;
              var walkerCheck = document.createTreeWalker(codeElCheck, NodeFilter.SHOW_TEXT, null, false);
              var wnCheck;
              while ((wnCheck = walkerCheck.nextNode())) {
                if (wnCheck === rCheck.startContainer) { cursorOffsetCheck += rCheck.startOffset; break; }
                cursorOffsetCheck += wnCheck.textContent.length;
              }
              var afterCursor = fullTextCheck.substring(cursorOffsetCheck);
              if (afterCursor.replace(/[\n\r\s\t\u200B\u200C\u200D\uFEFF]/g, '').length === 0) {
                cursorAtEnd = true;
              }
            }
          }
          if (!cursorAtEnd) {
            consecutiveEnters = 0;
            var codeEl = pre.querySelector('code');
            if (codeEl) {
              var r = sel.getRangeAt(0);
              if (codeEl.contains(r.startContainer)) {
                var doc = codeEl.ownerDocument;
                var nl = doc.createTextNode('\n');
                r.insertNode(nl);
                r.setStart(nl, 1);
                r.setEnd(nl, 1);
                r.collapse(true);
                sel.removeAllRanges();
                sel.addRange(r);
                if (ea.dispatchEvent) {
                  ea.dispatchEvent(new Event('input', { bubbles: true }));
                }
              }
            }
            return;
          }

          consecutiveEnters = 0;
          lastEnterPre = null;

          var blockContainer = wrapper || pre;
          var el = pre;
          while (el && el !== ea) {
            if (el.classList && el.classList.contains('md-code-block')) {
              blockContainer = el;
            }
            el = el.parentNode;
          }
          if (pre) {
            var codeEl = pre.querySelector('code');
            var codeClass = (codeEl && codeEl.className) ? codeEl.className : '';
            var effectiveChildren = 0;
            var singleCode = null;
            for (var ei = 0; ei < pre.childNodes.length; ei++) {
              var en = pre.childNodes[ei];
              if (en.nodeType === 1 && en.classList && (en.classList.contains('md-code-lang-btn') || en.classList.contains('md-code-lang-dropdown') || en.classList.contains('md-code-line-numbers') || en.classList.contains('md-code-settings-btn') || en.classList.contains('md-code-settings-btn-advanced'))) continue;
              if (en.nodeType === 1 && en.nodeName === 'CODE') { singleCode = en; effectiveChildren++; }
              else effectiveChildren++;
            }
            var rawContent;
            if (effectiveChildren === 1 && singleCode) {
              rawContent = singleCode.textContent;
            } else {
              var parts = [];
              for (var ci = 0; ci < pre.childNodes.length; ci++) {
                var cn = pre.childNodes[ci];
                if (cn.nodeType === 1 && cn.classList && (cn.classList.contains('md-code-lang-btn') || cn.classList.contains('md-code-lang-dropdown') || cn.classList.contains('md-code-line-numbers') || cn.classList.contains('md-code-settings-btn') || cn.classList.contains('md-code-settings-btn-advanced'))) continue;
                if (cn.nodeType === 3) parts.push(cn.textContent);
                else if (cn.nodeType === 1) parts.push(cn.textContent);
              }
              rawContent = parts.join('\n');
            }
            rawContent = rawContent.replace(stripMarkers, '');
            var cleaned = rawContent.replace(/(\n[ \t]*)+$/, '');
            while (pre.firstChild) pre.removeChild(pre.firstChild);
            var newCode = document.createElement('code');
            if (codeClass) newCode.className = codeClass;
            newCode.textContent = cleaned.length > 0 ? cleaned + '\n' : '\n';
            pre.appendChild(newCode);
            if (!wrapper) {
              enhanceBasicPreBlocks(ea);
            }
          }
          var p = document.createElement('p');
          var br = document.createElement('br');
          p.appendChild(br);
          blockContainer.insertAdjacentElement('afterend', p);
          var codeBlockAncestor = p.parentNode;
          while (codeBlockAncestor && codeBlockAncestor !== ea) {
            if (codeBlockAncestor.classList && codeBlockAncestor.classList.contains('md-code-block')) {
              codeBlockAncestor.parentNode.insertBefore(p, codeBlockAncestor.nextSibling);
              break;
            }
            codeBlockAncestor = codeBlockAncestor.parentNode;
          }
          var actualParent = p.parentNode;
          if (actualParent && actualParent !== ea) {
            if (actualParent.classList && actualParent.classList.contains('admonition')) {
              ea.__liveWysiwygAdmonitionEnterCredit = { count: 2, ad: actualParent };
            } else if (actualParent.nodeName === 'BLOCKQUOTE') {
              ea.__liveWysiwygBlockquoteEnterCredit = { count: 2, bq: actualParent };
            }
          }
          var range = document.createRange();
          range.setStart(p, 0);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        };
    })();

    function _isCodeUINode(n) {
      if (n.nodeType !== 1 || !n.classList) return false;
      return n.classList.contains('md-code-lang-btn') || n.classList.contains('md-code-lang-btn-advanced') ||
             n.classList.contains('md-code-lang-dropdown') || n.classList.contains('md-code-line-numbers') ||
             n.classList.contains('md-code-settings-btn') || n.classList.contains('md-code-settings-btn-advanced') ||
             n.classList.contains('md-code-settings-dropdown') || n.classList.contains('md-code-btn-group-advanced');
    }

    function _buildTargetRange(target) {
      var range = document.createRange();
      if (target.nodeName === 'PRE') {
        var codeEl = target.querySelector('code');
        var isSingleCode = false;
        if (codeEl) {
          var effectiveCount = 0;
          for (var si = 0; si < target.childNodes.length; si++) {
            if (_isCodeUINode(target.childNodes[si])) continue;
            effectiveCount++;
          }
          isSingleCode = (effectiveCount === 1 && codeEl.childNodes.length === 1 &&
                          codeEl.firstChild && codeEl.firstChild.nodeType === 3);
        }
        if (isSingleCode) {
          var textNode = codeEl.firstChild;
          var len = textNode.textContent.length;
          if (textNode.textContent.endsWith('\n') && len > 0) len = len - 1;
          range.setStart(textNode, 0);
          range.setEnd(textNode, len);
        } else {
          var firstContent = null, lastContent = null;
          for (var ci = 0; ci < target.childNodes.length; ci++) {
            var cn = target.childNodes[ci];
            if (_isCodeUINode(cn)) continue;
            if (!firstContent) firstContent = cn;
            lastContent = cn;
          }
          if (firstContent) {
            range.setStartBefore(firstContent);
            if (lastContent.nodeType === 3 && lastContent.textContent.endsWith('\n')) {
              range.setEnd(lastContent, lastContent.textContent.length - 1);
            } else {
              range.setEndAfter(lastContent);
            }
          } else {
            range.selectNodeContents(target);
          }
        }
      } else {
        range.selectNodeContents(target);
      }
      return range;
    }

    function _buildAdmonitionBodyRange(ad) {
      var range = document.createRange();
      var firstBody = null, lastBody = null;
      for (var ci = 0; ci < ad.childNodes.length; ci++) {
        var cn = ad.childNodes[ci];
        if (cn.nodeType === 1 && cn.classList && cn.classList.contains('admonition-title')) continue;
        if (cn.nodeType === 3 && !cn.textContent.replace(/[​‌‍﻿\s]/g, '')) continue;
        if (!firstBody) firstBody = cn;
        lastBody = cn;
      }
      if (firstBody && lastBody) {
        range.setStartBefore(firstBody);
        range.setEndAfter(lastBody);
      } else {
        range.selectNodeContents(ad);
      }
      return range;
    }

    function _selectionCoversRange(sel, targetRange) {
      if (!sel.rangeCount) return false;
      var cur = sel.getRangeAt(0);
      try {
        return cur.compareBoundaryPoints(Range.START_TO_START, targetRange) <= 0 &&
               cur.compareBoundaryPoints(Range.END_TO_END, targetRange) >= 0;
      } catch (ex) { return false; }
    }

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;

        var isCodeUINode = _isCodeUINode;
        var buildTargetRange = _buildTargetRange;
        var buildAdmonitionBodyRange = _buildAdmonitionBodyRange;
        var selectionCoversRange = _selectionCoversRange;

        function isSelectableTarget(node) {
          if (node === ea) return true;
          if (node.nodeType !== 1) return false;
          var name = node.nodeName;
          var cl = node.classList;
          if (name === 'CODE' && !node.closest('pre')) return true;
          if (cl && (cl.contains('md-code-title') || cl.contains('md-code-lang'))) return true;
          if (name === 'PRE') return true;
          if (cl && cl.contains('md-code-block')) return true;
          if (cl && cl.contains('admonition')) return true;
          if (/^(P|H[1-6]|LI|TD|TH)$/.test(name)) return true;
          if (/^(UL|OL|TABLE|BLOCKQUOTE)$/.test(name)) return true;
          return false;
        }

        var HEADING_RE = /^H[1-6]$/;

        function buildHeadingSectionRange(siblings, startIdx, endIdx) {
          var range = document.createRange();
          range.setStartBefore(siblings[startIdx]);
          range.setEndAfter(siblings[endIdx]);
          return range;
        }

        _ekh.progressiveSelectAll = function (e) {
          if (!(e.key === 'a' && (e.metaKey || e.ctrlKey))) return;
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          var sel = window.getSelection();
          if (!sel || !sel.rangeCount) return;

          var targetRanges = [];
          var node = sel.anchorNode;
          var r = sel.rangeCount ? sel.getRangeAt(0) : null;

          if (node === ea && r) {
            if (r.startContainer === ea) {
              for (var ri = r.startOffset; ri < ea.childNodes.length; ri++) {
                if (ea.childNodes[ri].nodeType === 1) { node = ea.childNodes[ri]; break; }
              }
            } else {
              node = r.startContainer;
            }
          } else if (node && node.nodeType === 3 && r && /^\s*$/.test(node.textContent)) {
            var sc = r.startContainer;
            if (sc === ea) {
              for (var ri = r.startOffset; ri < ea.childNodes.length; ri++) {
                if (ea.childNodes[ri].nodeType === 1) { node = ea.childNodes[ri]; break; }
              }
              if (!node || node.nodeType !== 1) {
                for (var ri = r.startOffset - 1; ri >= 0; ri--) {
                  if (ea.childNodes[ri].nodeType === 1) { node = ea.childNodes[ri]; break; }
                }
              }
            } else if (sc && sc.nodeType === 3) {
              node = sc.parentNode;
              if (node === ea) {
                var idx = -1;
                for (var i = 0; i < ea.childNodes.length; i++) {
                  if (ea.childNodes[i] === sc) { idx = i; break; }
                }
                if (idx >= 0) {
                  for (var ri = idx + 1; ri < ea.childNodes.length; ri++) {
                    if (ea.childNodes[ri].nodeType === 1) { node = ea.childNodes[ri]; break; }
                  }
                  if (!node || node.nodeType !== 1) {
                    for (var ri = idx - 1; ri >= 0; ri--) {
                      if (ea.childNodes[ri].nodeType === 1) { node = ea.childNodes[ri]; break; }
                    }
                  }
                }
              }
            } else if (sc && sc.nodeType === 1) {
              node = sc;
            }
          }

          var elCur = (node && node.nodeType === 3) ? node.parentNode : node;
          while (elCur && elCur !== ea) {
            if (isSelectableTarget(elCur)) {
              if (elCur.classList && elCur.classList.contains('admonition')) {
                var inTitle = false;
                var titleEl = elCur.querySelector('.admonition-title');
                var check = (node && node.nodeType === 3) ? node.parentNode : node;
                while (check && check !== elCur) {
                  if (check === titleEl) { inTitle = true; break; }
                  check = check.parentNode;
                }
                if (!inTitle) {
                  targetRanges.push(buildAdmonitionBodyRange(elCur));
                }
              }
              targetRanges.push(buildTargetRange(elCur));
            }
            elCur = elCur.parentNode;
          }

          var topChild = (node && node.nodeType === 3) ? node.parentNode : node;
          while (topChild && topChild !== ea && topChild.parentNode !== ea) {
            topChild = topChild.parentNode;
          }
          if (topChild && topChild.parentNode === ea) {
            var siblings = ea.childNodes;
            var topIdx = -1;
            for (var ti = 0; ti < siblings.length; ti++) {
              if (siblings[ti] === topChild) { topIdx = ti; break; }
            }
            if (topIdx >= 0) {
              if (topChild.nodeType === 1 && HEADING_RE.test(topChild.nodeName)) {
                var ownLevel = parseInt(topChild.nodeName.charAt(1));
                var ownEnd = siblings.length - 1;
                for (var oi = topIdx + 1; oi < siblings.length; oi++) {
                  var os = siblings[oi];
                  if (os.nodeType === 1 && HEADING_RE.test(os.nodeName) && parseInt(os.nodeName.charAt(1)) <= ownLevel) {
                    ownEnd = oi - 1;
                    break;
                  }
                }
                if (ownEnd >= topIdx + 1) {
                  targetRanges.push(buildHeadingSectionRange(siblings, topIdx, ownEnd));
                }
              }

              var curLevel = (topChild.nodeType === 1 && HEADING_RE.test(topChild.nodeName))
                ? parseInt(topChild.nodeName.charAt(1))
                : 7;

              for (var hi = topIdx - 1; hi >= 0; hi--) {
                var sib = siblings[hi];
                if (sib.nodeType !== 1 || !HEADING_RE.test(sib.nodeName)) continue;
                var hLevel = parseInt(sib.nodeName.charAt(1));
                if (hLevel >= curLevel) continue;
                var secStart = hi + 1;
                var secEnd = siblings.length - 1;
                for (var si = hi + 1; si < siblings.length; si++) {
                  var ss = siblings[si];
                  if (ss.nodeType === 1 && HEADING_RE.test(ss.nodeName) && parseInt(ss.nodeName.charAt(1)) <= hLevel) {
                    secEnd = si - 1;
                    break;
                  }
                }
                if (secStart <= secEnd) {
                  targetRanges.push(buildHeadingSectionRange(siblings, hi, secEnd));
                }
                curLevel = hLevel;
              }
            }
          }

          targetRanges.push(buildTargetRange(ea));

          for (var i = 0; i < targetRanges.length; i++) {
            if (!selectionCoversRange(sel, targetRanges[i])) {
              e.preventDefault();
              sel.removeAllRanges();
              sel.addRange(targetRanges[i]);
              return;
            }
          }
        };
    })();

    // ───── Editor Keyboard Router (Tier 3) ─────
    // Single capture-phase keydown handler replacing 16 individual handlers.
    // Priority is determined by call order. See DESIGN-centralized-keyboard.md.
    (function _setupEditorKeyboard() {
      var ea = wysiwygEditor.editableArea;
      if (!ea || ea.dataset.liveWysiwygKeyboardRouterAttached) return;
      ea.dataset.liveWysiwygKeyboardRouterAttached = '1';

      ea.addEventListener('keydown', function _editorKeydownRouter(e) {
        if (_navEditMode) return;
        if (_ekh.inlineCodeClear) _ekh.inlineCodeClear(e);
        if (_ekh.checklistCursorNorm) _ekh.checklistCursorNorm(e);

        if (_ekh.emojiKey) { _ekh.emojiKey(e); if (e.defaultPrevented) return; }

        var key = e.key;

        if (key === 'Enter') {
          if (_ekh.reverseBubble) { _ekh.reverseBubble(e); if (e.defaultPrevented) return; }
          if (_ekh.listEnterExit) { _ekh.listEnterExit(e); if (e.defaultPrevented) return; }
          if (_ekh.admonitionEnterExit) { _ekh.admonitionEnterExit(e); if (e.defaultPrevented) return; }
          if (_ekh.blockquoteEnterExit) { _ekh.blockquoteEnterExit(e); if (e.defaultPrevented) return; }
          if (_ekh.headingEnter) { _ekh.headingEnter(e); if (e.defaultPrevented) return; }
          if (_ekh.hiddenTitleAdmonitionEnter) { _ekh.hiddenTitleAdmonitionEnter(e); if (e.defaultPrevented) return; }
          if (_ekh.codeBlockEnterExit) { _ekh.codeBlockEnterExit(e); if (e.defaultPrevented) return; }
        } else if (key === 'Backspace') {
          if (_ekh.checklistBackspace) { _ekh.checklistBackspace(e); if (e.defaultPrevented) return; }
          if (_ekh.mdAuto) { _ekh.mdAuto(e); if (e.defaultPrevented) return; }
          if (_ekh.codeBlockBackspace) { _ekh.codeBlockBackspace(e); if (e.defaultPrevented) return; }
          if (_ekh.admonitionBackspace) { _ekh.admonitionBackspace(e); if (e.defaultPrevented) return; }
        } else if (key === 'Delete') {
          if (_ekh.mdAuto) _ekh.mdAuto(e);
        } else if (key === ' ') {
          if (_ekh.mdAuto) _ekh.mdAuto(e);
        } else if (key === 'ArrowLeft' || key === 'ArrowRight') {
          if (_ekh.checklistArrow) _ekh.checklistArrow(e);
        } else if (key === 'a' && (e.metaKey || e.ctrlKey)) {
          if (_ekh.progressiveSelectAll) _ekh.progressiveSelectAll(e);
        }
      }, true);
    })();

    (function blockCutPasteHandler() {
      var ea = wysiwygEditor.editableArea;
      if (!ea || ea.dataset.liveWysiwygBlockCutPasteAttached) return;
      ea.dataset.liveWysiwygBlockCutPasteAttached = '1';

      var BLOCK_ATTR = 'data-wysiwyg-block';

      function classifyBlock(node) {
        if (!node || node.nodeType !== 1) return null;
        var name = node.nodeName;
        var cl = node.classList;
        if (name === 'UL' || name === 'OL') return 'list';
        if (name === 'LI') return 'list-item';
        if (cl && cl.contains('admonition')) return 'admonition';
        if (name === 'DETAILS' && isAdmonitionElement(node)) return 'admonition';
        if (cl && cl.contains('md-code-block')) return 'codeblock';
        if (name === 'PRE') return 'codeblock';
        if (name === 'BLOCKQUOTE') return 'blockquote';
        return null;
      }

      function findSelectedBlock(sel) {
        if (!sel || !sel.rangeCount) return null;
        var node = sel.anchorNode;
        if (!node) return null;
        var el = (node.nodeType === 3) ? node.parentNode : node;
        var candidates = [];
        while (el && el !== ea) {
          var type = classifyBlock(el);
          if (type) {
            candidates.push({ node: el, type: type });
          }
          el = el.parentNode;
        }
        for (var i = 0; i < candidates.length; i++) {
          var c = candidates[i];
          var targetRange = _buildTargetRange(c.node);
          if (_selectionCoversRange(sel, targetRange)) {
            if (c.node.nodeName === 'PRE' && c.node.parentNode &&
                c.node.parentNode.classList && c.node.parentNode.classList.contains('md-code-block')) {
              return { node: c.node.parentNode, type: 'codeblock' };
            }
            return c;
          }
        }
        return null;
      }

      function isEmptyContainer(container) {
        var text = (container.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
        if (text.length > 0) return false;
        if (container.querySelector('pre, .md-code-block, .admonition, details, img, table, blockquote, ul, ol')) return false;
        return true;
      }

      function insertPlaceholder(parent) {
        var p = document.createElement('p');
        p.innerHTML = '&#8203;';
        parent.appendChild(p);
        var sel = window.getSelection();
        if (sel) {
          var range = document.createRange();
          range.setStart(p, 0);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
        }
      }

      function stripCodeUIFromClone(clone) {
        var uis = clone.querySelectorAll('.md-code-lang-btn, .md-code-lang-btn-advanced, .md-code-lang-dropdown, .md-code-settings-btn, .md-code-settings-btn-advanced, .md-code-settings-dropdown, .md-code-btn-group-advanced, .md-admonition-settings-btn');
        for (var i = uis.length - 1; i >= 0; i--) {
          uis[i].parentNode.removeChild(uis[i]);
        }
        return clone;
      }

      function _wrapLiInList(liNode) {
        var parentList = liNode.parentNode;
        var listTag = (parentList && parentList.nodeName === 'OL') ? 'OL' : 'UL';
        var wrapList = document.createElement(listTag);
        var clone = liNode.cloneNode(true);
        stripCodeUIFromClone(clone);
        wrapList.appendChild(clone);
        return wrapList;
      }

      function _imageToClipboard(e, img) {
        var imgClone = img.cloneNode(true);
        var tempP = document.createElement('p');
        tempP.appendChild(imgClone);
        e.clipboardData.setData('text/html', tempP.outerHTML);
        var tempDiv = document.createElement('div');
        tempDiv.appendChild(imgClone.cloneNode(true));
        var plainText = '';
        try {
          plainText = wysiwygEditor._htmlToMarkdown(tempDiv);
        } catch (ex) {
          var alt = img.getAttribute('alt') || '';
          var src = img.getAttribute('data-orig-src') || img.getAttribute('src') || '';
          plainText = '![' + alt + '](' + src + ')';
        }
        e.clipboardData.setData('text/plain', plainText);
      }

      function _removeSelectedImage() {
        if (!_activeImageSelection) return;
        var img = _activeImageSelection.img;
        var wrapper = img && img.closest('.md-image-wrapper');
        var target = wrapper || img;
        if (!target || !target.parentNode) return;
        var parent = target.parentNode;
        dismissImageSelection();
        parent.removeChild(target);
        var parentText = (parent.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
        if (parentText.length === 0 && parent.querySelectorAll('img').length === 0) {
          if (parent !== ea && (parent.nodeName === 'P' || parent.nodeName === 'DIV')) {
            var newP = document.createElement('p');
            newP.innerHTML = '<br>';
            parent.parentNode.replaceChild(newP, parent);
            var r = document.createRange();
            r.setStart(newP, 0);
            r.collapse(true);
            var s = window.getSelection();
            s.removeAllRanges();
            s.addRange(r);
          } else if (parent === ea) {
            insertPlaceholder(ea);
          }
        } else {
          var r = document.createRange();
          r.setStart(parent, 0);
          r.collapse(true);
          var s = window.getSelection();
          s.removeAllRanges();
          s.addRange(r);
        }
        if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
      }

      ea.addEventListener('cut', function (e) {
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;

        if (_activeImageSelection && _activeImageSelection.img) {
          e.preventDefault();
          wysiwygEditor.__cursorBeforeInput = captureWysiwygCursor(ea);
          _imageToClipboard(e, _activeImageSelection.img);
          _removeSelectedImage();
          return;
        }

        var sel = window.getSelection();
        var block = findSelectedBlock(sel);
        if (!block) return;

        e.preventDefault();

        wysiwygEditor.__cursorBeforeInput = captureWysiwygCursor(ea);

        if (block.type === 'list-item') {
          var wrapList = _wrapLiInList(block.node);
          var wrapperHtml = '<div ' + BLOCK_ATTR + '="list">' + wrapList.outerHTML + '</div>';
          e.clipboardData.setData('text/html', wrapperHtml);
          var tempDiv = document.createElement('div');
          tempDiv.appendChild(wrapList.cloneNode(true));
          var plainText = '';
          try { plainText = wysiwygEditor._htmlToMarkdown(tempDiv); }
          catch (ex) { plainText = block.node.textContent || ''; }
          e.clipboardData.setData('text/plain', plainText);

          var parentList = block.node.parentNode;
          var nextLi = block.node.nextElementSibling;
          var prevLi = block.node.previousElementSibling;
          parentList.removeChild(block.node);
          var remainingLis = parentList.querySelectorAll(':scope > li');
          if (remainingLis.length === 0) {
            var grandParent = parentList.parentNode;
            var newP = document.createElement('p');
            newP.innerHTML = '<br>';
            grandParent.insertBefore(newP, parentList);
            grandParent.removeChild(parentList);
            var r = document.createRange();
            r.setStart(newP, 0);
            r.collapse(true);
            sel.removeAllRanges();
            sel.addRange(r);
            if (isEmptyContainer(grandParent) && grandParent === ea) {
              insertPlaceholder(ea);
            }
          } else {
            var focusLi = nextLi || prevLi || remainingLis[0];
            if (focusLi) {
              var r = document.createRange();
              r.selectNodeContents(focusLi);
              r.collapse(true);
              sel.removeAllRanges();
              sel.addRange(r);
            }
          }
          if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
          return;
        }

        var clone = block.node.cloneNode(true);
        stripCodeUIFromClone(clone);

        var wrapperHtml = '<div ' + BLOCK_ATTR + '="' + block.type + '">' + clone.outerHTML + '</div>';
        e.clipboardData.setData('text/html', wrapperHtml);

        var tempDiv = document.createElement('div');
        tempDiv.appendChild(clone.cloneNode(true));
        var plainText = '';
        try {
          plainText = wysiwygEditor._htmlToMarkdown(tempDiv);
        } catch (ex) {
          plainText = block.node.textContent || '';
        }
        e.clipboardData.setData('text/plain', plainText);

        var parent = block.node.parentNode;
        parent.removeChild(block.node);

        if (isEmptyContainer(parent)) {
          if (parent === ea) {
            insertPlaceholder(ea);
          } else if (isAdmonitionElement(parent)) {
            var titleEl = (parent.nodeName === 'DETAILS')
              ? parent.querySelector(':scope > summary')
              : parent.querySelector(':scope > .admonition-title');
            var gearBtn = parent.querySelector(':scope > .md-admonition-settings-btn');
            var hasOtherContent = false;
            for (var ci = 0; ci < parent.childNodes.length; ci++) {
              var cn = parent.childNodes[ci];
              if (cn === titleEl || cn === gearBtn) continue;
              if (cn.nodeType === 3 && !cn.textContent.replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '')) continue;
              hasOtherContent = true;
              break;
            }
            if (!hasOtherContent) {
              var bp = document.createElement('p');
              bp.innerHTML = '&#8203;';
              parent.appendChild(bp);
            }
          } else if (parent.nodeName === 'BLOCKQUOTE' || parent.nodeName === 'LI') {
            var bp = document.createElement('p');
            bp.innerHTML = '&#8203;';
            parent.appendChild(bp);
          }
        }

        if (wysiwygEditor._finalizeUpdate) {
          wysiwygEditor._finalizeUpdate(ea.innerHTML);
        }
      }, true);

      ea.addEventListener('copy', function (e) {
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;

        if (_activeImageSelection && _activeImageSelection.img) {
          e.preventDefault();
          _imageToClipboard(e, _activeImageSelection.img);
          return;
        }

        var sel = window.getSelection();
        var block = findSelectedBlock(sel);
        if (!block) return;

        e.preventDefault();

        if (block.type === 'list-item') {
          var wrapList = _wrapLiInList(block.node);
          var wrapperHtml = '<div ' + BLOCK_ATTR + '="list">' + wrapList.outerHTML + '</div>';
          e.clipboardData.setData('text/html', wrapperHtml);
          var tempDiv = document.createElement('div');
          tempDiv.appendChild(wrapList.cloneNode(true));
          var plainText = '';
          try { plainText = wysiwygEditor._htmlToMarkdown(tempDiv); }
          catch (ex) { plainText = block.node.textContent || ''; }
          e.clipboardData.setData('text/plain', plainText);
          return;
        }

        var clone = block.node.cloneNode(true);
        stripCodeUIFromClone(clone);

        var wrapperHtml = '<div ' + BLOCK_ATTR + '="' + block.type + '">' + clone.outerHTML + '</div>';
        e.clipboardData.setData('text/html', wrapperHtml);

        var tempDiv = document.createElement('div');
        tempDiv.appendChild(clone.cloneNode(true));
        var plainText = '';
        try {
          plainText = wysiwygEditor._htmlToMarkdown(tempDiv);
        } catch (ex) {
          plainText = block.node.textContent || '';
        }
        e.clipboardData.setData('text/plain', plainText);
      }, true);

      function findPasteContext(sel) {
        if (!sel || !sel.rangeCount) return { type: 'toplevel', container: ea, targetBlock: null };
        var range = sel.getRangeAt(0);
        var node = range.startContainer;
        var el = (node.nodeType === 3) ? node.parentNode : node;

        if (el === ea && range.startOffset < ea.childNodes.length) {
          var child = ea.childNodes[range.startOffset];
          if (child && child.nodeType === 1) {
            el = child;
          }
        }

        var ctx = { type: 'toplevel', container: ea, targetBlock: null, li: null, admonition: null, blockquote: null };

        var cur = el;
        while (cur && cur !== ea) {
          if (cur.nodeName === 'LI' && !ctx.li) {
            ctx.li = cur;
            ctx.type = 'list-item';
          }
          if (!ctx.admonition && isAdmonitionElement(cur)) {
            ctx.admonition = cur;
            if (ctx.type === 'toplevel') ctx.type = 'admonition';
          }
          if (cur.nodeName === 'BLOCKQUOTE' && !ctx.blockquote) {
            ctx.blockquote = cur;
            if (ctx.type === 'toplevel') ctx.type = 'blockquote';
          }
          cur = cur.parentNode;
        }

        var inner = el;
        var contextParent = null;
        if (ctx.type === 'list-item') contextParent = ctx.li;
        else if (ctx.type === 'admonition') contextParent = ctx.admonition;
        else if (ctx.type === 'blockquote') contextParent = ctx.blockquote;
        else contextParent = ea;

        while (inner && inner !== contextParent && inner.parentNode !== contextParent) {
          inner = inner.parentNode;
        }
        if (inner && inner !== contextParent && inner.parentNode === contextParent) {
          ctx.targetBlock = inner;
        }

        ctx.container = contextParent;
        return ctx;
      }

      function isEmptyParagraph(node) {
        if (!node || node.nodeName !== 'P') return false;
        var text = (node.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
        return text.length === 0 && !node.querySelector('img, pre, .md-code-block, .admonition, details, table, blockquote, ul, ol');
      }

      function insertBlockAfterTarget(block, ctx) {
        var target = ctx.targetBlock;
        var container = ctx.container;
        if (target && isEmptyParagraph(target)) {
          container.insertBefore(block, target);
          container.removeChild(target);
        } else if (target && target.parentNode === container) {
          container.insertBefore(block, target.nextSibling);
        } else {
          container.appendChild(block);
        }
      }

      function isEmptyListItem(li) {
        var text = (li.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '');
        if (text.length > 0) return false;
        if (li.querySelector('img, pre, .md-code-block, .admonition, table, blockquote, ul, ol')) return false;
        return true;
      }

      function isCursorAtStartOfLi(li, sel) {
        if (!sel || !sel.isCollapsed || !sel.rangeCount) return false;
        var r = sel.getRangeAt(0);
        var sc = r.startContainer;
        var so = r.startOffset;
        var stripZws = /[\u200B\u200C\u200D\uFEFF]/g;
        if (sc === li && so === 0) return true;
        if (sc.nodeType === 3) {
          if (so > 0) {
            var before = sc.textContent.substring(0, so).replace(stripZws, '');
            if (before.trim().length > 0) return false;
          }
          var prev = sc;
          while (prev) {
            var ps = prev.previousSibling;
            if (ps) {
              if (ps.nodeType === 1 && ps.nodeName === 'INPUT') { prev = ps; continue; }
              var ptxt = (ps.textContent || '').replace(stripZws, '');
              if (ptxt.trim().length === 0) { prev = ps; continue; }
              return false;
            } else {
              if (prev.parentNode === li) return true;
              prev = prev.parentNode;
            }
          }
        } else if (sc.nodeType === 1 && (sc === li || li.contains(sc))) {
          for (var ci = 0; ci < so; ci++) {
            var ch = sc.childNodes[ci];
            if (ch.nodeType === 1 && ch.nodeName === 'INPUT') continue;
            var ctxt = (ch.textContent || '').replace(stripZws, '');
            if (ctxt.trim().length > 0) return false;
          }
          if (sc === li) return true;
          var cur = sc;
          while (cur && cur !== li) {
            var ps = cur.previousSibling;
            while (ps) {
              if (ps.nodeType === 1 && ps.nodeName === 'INPUT') { ps = ps.previousSibling; continue; }
              var ptxt = (ps.textContent || '').replace(stripZws, '');
              if (ptxt.trim().length > 0) return false;
              ps = ps.previousSibling;
            }
            cur = cur.parentNode;
            if (cur === li) return true;
          }
        }
        return false;
      }

      function pasteList(listEl, ctx, sel) {
        if (ctx.type === 'list-item') {
          var parentList = ctx.li.parentNode;
          if (!parentList || (parentList.nodeName !== 'UL' && parentList.nodeName !== 'OL')) {
            insertBlockAfterTarget(listEl, ctx);
            return;
          }
          var liWasEmpty = isEmptyListItem(ctx.li);
          if (liWasEmpty) {
            var liCount = 0;
            for (var ci = 0; ci < parentList.childNodes.length; ci++) {
              if (parentList.childNodes[ci].nodeName === 'LI') liCount++;
            }
            if (liCount === 1) {
              parentList.parentNode.insertBefore(listEl, parentList);
              parentList.parentNode.removeChild(parentList);
              return;
            }
          }
          var items = [];
          while (listEl.firstChild) {
            if (listEl.firstChild.nodeName === 'LI') {
              items.push(listEl.firstChild);
            }
            listEl.removeChild(listEl.firstChild);
          }
          var targetCb = getDirectCheckboxOfLi(ctx.li);
          if (targetCb) {
            var checkedState = targetCb.checked;
            for (var j = 0; j < items.length; j++) {
              var existingCb = getDirectCheckboxOfLi(items[j]);
              if (existingCb) {
                existingCb.checked = checkedState;
                if (checkedState) existingCb.setAttribute('checked', '');
                else existingCb.removeAttribute('checked');
              } else {
                var newCb = document.createElement('input');
                newCb.type = 'checkbox';
                newCb.checked = checkedState;
                if (checkedState) newCb.setAttribute('checked', '');

                items[j].insertBefore(newCb, items[j].firstChild);
                items[j].insertBefore(document.createTextNode(' '), newCb.nextSibling);
              }
            }
          }
          var insertBefore = !liWasEmpty && isCursorAtStartOfLi(ctx.li, sel);
          var ref = insertBefore ? ctx.li : ctx.li.nextSibling;
          for (var i = 0; i < items.length; i++) {
            parentList.insertBefore(items[i], ref);
          }
          if (liWasEmpty && ctx.li.parentNode) {
            ctx.li.parentNode.removeChild(ctx.li);
          }
        } else {
          insertBlockAfterTarget(listEl, ctx);
        }
      }

      function pasteAdmonition(adEl, ctx) {
        if (ctx.type === 'list-item') {
          var topBlock = ctx.li;
          while (topBlock && topBlock.parentNode !== ea) topBlock = topBlock.parentNode;
          if (topBlock && topBlock.parentNode === ea) {
            ea.insertBefore(adEl, topBlock.nextSibling);
          } else {
            ea.appendChild(adEl);
          }
        } else if (ctx.type === 'admonition') {
          insertBlockAfterTarget(adEl, ctx);
        } else if (ctx.type === 'blockquote') {
          insertBlockAfterTarget(adEl, ctx);
        } else {
          insertBlockAfterTarget(adEl, ctx);
        }
      }

      function pasteCodeblock(blockEl, ctx) {
        if (ctx.type === 'list-item') {
          var target = ctx.targetBlock;
          if (target && target.parentNode === ctx.li) {
            ctx.li.insertBefore(blockEl, target.nextSibling);
          } else {
            ctx.li.appendChild(blockEl);
          }
        } else {
          insertBlockAfterTarget(blockEl, ctx);
        }
      }

      function pasteBlockquote(bqEl, ctx) {
        if (ctx.type === 'list-item') {
          var target = ctx.targetBlock;
          if (target && target.parentNode === ctx.li) {
            ctx.li.insertBefore(bqEl, target.nextSibling);
          } else {
            ctx.li.appendChild(bqEl);
          }
        } else if (ctx.type === 'admonition') {
          insertBlockAfterTarget(bqEl, ctx);
        } else {
          insertBlockAfterTarget(bqEl, ctx);
        }
      }

      function focusInsidePastedBlock(blockType, blockEl) {
        var sel = window.getSelection();
        if (!sel) return;
        var rng = document.createRange();
        var target = null;

        if (blockType === 'list') {
          var lastLi = null;
          for (var i = blockEl.children.length - 1; i >= 0; i--) {
            if (blockEl.children[i].nodeName === 'LI') { lastLi = blockEl.children[i]; break; }
          }
          if (lastLi) {
            var deepest = lastLi;
            for (;;) {
              var nestedList = null;
              for (var j = deepest.children.length - 1; j >= 0; j--) {
                if (deepest.children[j].nodeName === 'UL' || deepest.children[j].nodeName === 'OL') {
                  nestedList = deepest.children[j];
                  break;
                }
              }
              if (nestedList) {
                var nestedLi = null;
                for (var k = nestedList.children.length - 1; k >= 0; k--) {
                  if (nestedList.children[k].nodeName === 'LI') { nestedLi = nestedList.children[k]; break; }
                }
                if (nestedLi) { deepest = nestedLi; } else break;
              } else break;
            }
            target = deepest;
          }
        } else if (blockType === 'admonition') {
          var bodyEl = null;
          for (var i = blockEl.childNodes.length - 1; i >= 0; i--) {
            var cn = blockEl.childNodes[i];
            if (cn.nodeType === 1 && !(cn.classList && cn.classList.contains('admonition-title'))) {
              bodyEl = cn;
              break;
            }
          }
          target = bodyEl || blockEl;
        } else if (blockType === 'codeblock') {
          var pre = blockEl.nodeName === 'PRE' ? blockEl : blockEl.querySelector('pre');
          if (pre) {
            var code = pre.querySelector('code');
            var textNode = code ? code.firstChild : pre.firstChild;
            if (textNode && textNode.nodeType === 3) {
              rng.setStart(textNode, textNode.textContent.length);
              rng.collapse(true);
              sel.removeAllRanges();
              sel.addRange(rng);
              return;
            }
          }
          target = pre || blockEl;
        } else if (blockType === 'blockquote') {
          var lastChild = null;
          for (var i = blockEl.childNodes.length - 1; i >= 0; i--) {
            if (blockEl.childNodes[i].nodeType === 1) { lastChild = blockEl.childNodes[i]; break; }
          }
          target = lastChild || blockEl;
        }

        if (target) {
          rng.selectNodeContents(target);
          rng.collapse(false);
          sel.removeAllRanges();
          sel.addRange(rng);
        }
      }

      function focusInsidePastedListItems(items) {
        if (!items || items.length === 0) return;
        var lastItem = items[items.length - 1];
        var deepest = lastItem;
        for (;;) {
          var nestedList = null;
          for (var j = deepest.children.length - 1; j >= 0; j--) {
            if (deepest.children[j].nodeName === 'UL' || deepest.children[j].nodeName === 'OL') {
              nestedList = deepest.children[j];
              break;
            }
          }
          if (nestedList) {
            var nestedLi = null;
            for (var k = nestedList.children.length - 1; k >= 0; k--) {
              if (nestedList.children[k].nodeName === 'LI') { nestedLi = nestedList.children[k]; break; }
            }
            if (nestedLi) { deepest = nestedLi; } else break;
          } else break;
        }
        var sel = window.getSelection();
        if (sel) {
          var rng = document.createRange();
          rng.selectNodeContents(deepest);
          rng.collapse(false);
          sel.removeAllRanges();
          sel.addRange(rng);
        }
      }

      ea.addEventListener('paste', function (e) {
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        var clipHtml = (e.clipboardData || window.clipboardData).getData('text/html');
        if (!clipHtml) return;
        _flushHistoryCapture();

        var temp = document.createElement('div');
        temp.innerHTML = clipHtml;
        var wrapper = temp.querySelector('[' + BLOCK_ATTR + ']');
        if (!wrapper) return;

        var blockType = wrapper.getAttribute(BLOCK_ATTR);
        if (!blockType) return;

        var blockContent = wrapper.firstElementChild;
        if (!blockContent) return;

        e.preventDefault();

        wysiwygEditor.__cursorBeforeInput = captureWysiwygCursor(ea);

        var sel = window.getSelection();
        var ctx = findPasteContext(sel);

        switch (blockType) {
          case 'list':
            var pastedItems = [];
            for (var pi = 0; pi < blockContent.children.length; pi++) {
              if (blockContent.children[pi].nodeName === 'LI') pastedItems.push(blockContent.children[pi]);
            }
            pasteList(blockContent, ctx, sel);
            for (var ri = 0; ri < pastedItems.length; ri++) {
              var rCbs = pastedItems[ri].querySelectorAll('input[type="checkbox"][data-live-wysiwyg-checklist]');
              for (var rci = 0; rci < rCbs.length; rci++) {
                rCbs[rci].removeAttribute('data-live-wysiwyg-checklist');
              }
            }
            enhanceChecklists(ea);
            if (blockContent.parentNode) {
              focusInsidePastedBlock('list', blockContent);
            } else if (pastedItems.length > 0) {
              focusInsidePastedListItems(pastedItems);
            }
            break;
          case 'admonition':
            blockContent.setAttribute('contenteditable', 'true');
            pasteAdmonition(blockContent, ctx);
            enhanceAdmonitions(ea);
            focusInsidePastedBlock('admonition', blockContent);
            break;
          case 'codeblock':
            pasteCodeblock(blockContent, ctx);
            enhanceBasicPreBlocks(ea);
            enhanceCodeBlocks(ea);
            enhanceAdmonitions(ea);
            enhanceImages(ea);
            focusInsidePastedBlock('codeblock', blockContent);
            break;
          case 'blockquote':
            pasteBlockquote(blockContent, ctx);
            focusInsidePastedBlock('blockquote', blockContent);
            break;
        }

        if (wysiwygEditor._finalizeUpdate) {
          wysiwygEditor._finalizeUpdate(ea.innerHTML);
        }
      }, true);
    })();

        const observer = new MutationObserver(function () {
      if (!textarea.parentNode) return;
      if (textarea.classList.contains('live-edit-hidden')) {
        observer.disconnect();
        destroyWysiwyg(textarea, true, false);
      }
    });
    observer.observe(textarea, { attributes: true, attributeFilter: ['class'] });
    ensureToggleButton(textarea, true);
    updateToggleButton(true);

    (function patchEditorModeState() {
      var orig = wysiwygEditor.switchToMode;
      wysiwygEditor.switchToMode = function (mode, isInitialSetup) {
        var result = orig.apply(this, arguments);
        if (!isInitialSetup && wysiwygEditor) {
          setEditorState(true, mode);
        }
        return result;
      };
    })();

    (function attachFocusModeButton() {
      if (!wysiwygEditor || !wysiwygEditor.toolbar) return;
      if (wysiwygEditor.toolbar.querySelector('.live-wysiwyg-focus-btn')) return;
      var btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'md-toolbar-button live-wysiwyg-focus-btn';
      btn.title = 'Focus Mode';
      btn.innerHTML = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" y1="3" x2="14" y2="10"></line><line x1="3" y1="21" x2="10" y2="14"></line></svg>';
      btn.style.cssText = 'margin-left:auto;';
      btn.addEventListener('click', function () {
        if (isFocusModeActive) {
          exitFocusMode();
        } else {
          enterFocusMode();
        }
      });
      wysiwygEditor.toolbar.appendChild(btn);
    })();

    if (wysiwygEditor) {
      wysiwygEditor.switchToMode(preferredMode, true);
      var appliedReadModeSelection = readonly_to_edit_mode_text_selection(wysiwygEditor);
      if (!appliedReadModeSelection) {
        if (preferredMode === 'markdown') {
          wysiwygEditor.markdownArea.setSelectionRange(0, 0);
          if (wysiwygEditor.markdownEditorContainer) {
            wysiwygEditor.markdownEditorContainer.scrollTop = 0;
          }
        } else {
          var ea = wysiwygEditor.editableArea;
          if (ea) {
            ea.scrollTop = 0;
            if (lastWysiwygSemanticSelection && restoreSelectionFromSemantic(ea, lastWysiwygSemanticSelection)) {
              installSemanticClearListeners(ea);
            } else {
              focusCursorAtDocStart(ea);
            }
          }
        }
      }

      if (!isFocusModeActive && window.__liveWysiwygEarlyOverlay) {
        enterFocusMode();
      } else if (!isFocusModeActive && _getSetting('live_wysiwyg_autofocus') === '1') {
        enterFocusMode();
      }

    }
  }

  function observeForTextarea() {
    var textarea = document.querySelector('.live-edit-source');
    if (!textarea || textarea.classList.contains('live-edit-hidden')) return false;
    var focusNavRelaunch = !!window.__liveWysiwygEarlyOverlay;
    var editorEnabled = isEditorEnabled();
    var shouldAutoload = focusNavRelaunch || editorEnabled !== false;
    ensureToggleButton(textarea, false);
    if (shouldAutoload) {
      replaceTextareaWithWysiwyg(textarea);
    } else {
      updateToggleButton(false);
    }
    return true;
  }

  function _autoClickEditButton() {
    var editBtn = document.querySelector('.live-edit-controls button[accesskey="e"]');
    if (editBtn && !editBtn.classList.contains('live-edit-hidden') && !editBtn.disabled) {
      editBtn.click();
      return true;
    }
    return false;
  }

  function _watchForEditButton(retryCount) {
    if (_autoClickEditButton()) {
      _deleteSetting('live_wysiwyg_focus_nav_retry');
      return;
    }

    var controls = document.querySelector('.live-edit-controls');
    if (controls) {
      var observer = new MutationObserver(function (mutations) {
        if (_autoClickEditButton()) {
          observer.disconnect();
          _deleteSetting('live_wysiwyg_focus_nav_retry');
        }
      });
      observer.observe(controls, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'disabled'] });
      setTimeout(function () {
        observer.disconnect();
        if (!document.querySelector('.live-edit-source:not(.live-edit-hidden)')) {
          _handleEditButtonFail(retryCount);
        } else {
          _deleteSetting('live_wysiwyg_focus_nav_retry');
        }
      }, 8000);
      return;
    }

    var bodyObserver = new MutationObserver(function () {
      if (document.querySelector('.live-edit-controls')) {
        bodyObserver.disconnect();
        _watchForEditButton(retryCount);
      }
    });
    bodyObserver.observe(document.body, { childList: true, subtree: true });
    setTimeout(function () {
      bodyObserver.disconnect();
      if (!document.querySelector('.live-edit-source:not(.live-edit-hidden)')) {
        _handleEditButtonFail(retryCount);
      } else {
        _deleteSetting('live_wysiwyg_focus_nav_retry');
      }
    }, 8000);
  }

  function _handleEditButtonFail(retryCount) {
    if (retryCount < 3) {
      _setSetting('live_wysiwyg_focus_nav_retry', String(retryCount + 1));
      _setSetting('live_wysiwyg_focus_nav', '1');
      var overlay = window.__liveWysiwygEarlyOverlay;
      if (overlay) {
        var txt = overlay.querySelector('div[style*="font-size"]');
        if (txt) txt.textContent = 'Re-establishing connection... (attempt ' + (retryCount + 2) + '/4)';
      }
      setTimeout(function () { location.reload(); }, 500);
    } else {
      _deleteSetting('live_wysiwyg_focus_nav_retry');
      var overlay = window.__liveWysiwygEarlyOverlay;
      if (overlay) {
        var spinner = overlay.querySelector('div[style*="border-radius:50%"]');
        if (spinner) spinner.style.display = 'none';
        var txt = overlay.querySelector('div[style*="font-size"]');
        if (txt) txt.textContent = 'Connection could not be established. Please reload the page.';
      }
    }
  }

  function init() {
    if (!observeForTextarea()) {
      if (_getSetting('live_wysiwyg_autolaunch') === '1' && !window.__liveWysiwygEarlyOverlay) {
        _autoClickEditButton();
      }
      startBodyObserver();
      if (window.__liveWysiwygEarlyOverlay) {
        var retrySetting = _getSetting('live_wysiwyg_focus_nav_retry');
        var retryCount = retrySetting ? parseInt(retrySetting, 10) : 0;
        _watchForEditButton(retryCount);
      }
    } else if (window.__liveWysiwygEarlyOverlay) {
      _deleteSetting('live_wysiwyg_focus_nav_retry');
    }
  }

  window.addEventListener('popstate', function (e) {
    if (!isFocusModeActive || !wysiwygEditor) return;
    var state = e.state;
    if (state && state.srcPath) {
      _doAjaxNavigate(location.href, '', state.srcPath);
    } else {
      var popOv = _showFullScreenTransition('Navigating...');
      _setSetting('live_wysiwyg_focus_nav', '1');
      _fadeOverlayToOpaque(popOv, function () {
        location.reload();
      });
    }
  });

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
