/**
 * 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;
  }

  var _compat = window.LiveWysiwygCompat;

  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',
    'mermaid'
  ];

  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;
    }
  }

  var _dismissLinkDropdownFn = null;
  function _dismissAllDropdowns() {
    dismissActiveSettingsDropdown();
    dismissActiveLangDropdown();
    dismissAdmonitionSettingsDropdown();
    dismissImageInsertDropdown();
    dismissImageGearDropdown();
    if (_dismissLinkDropdownFn) _dismissLinkDropdownFn();
    if (_admonitionDropdownDismiss) _admonitionDropdownDismiss();
    hideSelectionEditPopup();
    _dismissAssetPreviewPopup();
    _dismissHistoryBranchPopup();
  }

  function createLangDropdown(anchorBtn, currentLang, onSelect) {
    _dismissAllDropdowns();
    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;
      if (left + 180 > window.innerWidth) left = window.innerWidth - 180;
      var top = rect.bottom + 2;
      if (top + dropdown.offsetHeight > window.innerHeight) {
        top = rect.top - 2 - dropdown.offsetHeight;
      }
      if (top < 0) top = 0;
      dropdown.style.top = top + '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);
    addCopyButtonToBasicPre(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);
    var oldCopy = pre.querySelector('.md-code-copy-btn');
    if (oldCopy) oldCopy.parentNode.removeChild(oldCopy);
    enhanceCodeBlocks(editableArea);
    enhanceMermaidBlocks(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);
    addCopyButtonToAdvancedBlock(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>';
  var COPY_SVG = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
  var CHECK_SVG = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';

  function addCopyButtonToBasicPre(pre) {
    if (pre.querySelector('.md-code-copy-btn')) return;
    var btn = document.createElement('button');
    btn.className = 'md-code-copy-btn';
    btn.setAttribute('contenteditable', 'false');
    btn.setAttribute('title', 'Copy code');
    btn.innerHTML = COPY_SVG;
    btn.type = 'button';
    pre.appendChild(btn);
    btn.addEventListener('mousedown', function (e) {
      e.preventDefault();
      e.stopPropagation();
      var codeEl = pre.querySelector('code');
      var text = codeEl ? codeEl.textContent : pre.textContent;
      _compat.writeClipboardText(text).then(function (ok) {
        if (!ok) return;
        btn.innerHTML = CHECK_SVG;
        btn.classList.add('md-code-copy-btn--copied');
        setTimeout(function () {
          btn.innerHTML = COPY_SVG;
          btn.classList.remove('md-code-copy-btn--copied');
        }, 1500);
      });
    });
  }

  function addCopyButtonToAdvancedBlock(wrapper) {
    var group = getOrCreateAdvancedBtnGroup(wrapper);
    if (group.querySelector('.md-code-copy-btn')) return;
    var btn = document.createElement('button');
    btn.className = 'md-code-copy-btn';
    btn.setAttribute('contenteditable', 'false');
    btn.setAttribute('title', 'Copy code');
    btn.innerHTML = COPY_SVG;
    btn.type = 'button';
    var gearBtn = group.querySelector('.md-code-settings-btn-advanced');
    if (gearBtn) {
      group.insertBefore(btn, gearBtn);
    } else {
      group.insertBefore(btn, group.firstChild);
    }
    btn.addEventListener('mousedown', function (e) {
      e.preventDefault();
      e.stopPropagation();
      var pre = wrapper.querySelector('pre');
      if (!pre) return;
      var codeEl = pre.querySelector('code');
      var text = codeEl ? codeEl.textContent : pre.textContent;
      _compat.writeClipboardText(text).then(function (ok) {
        if (!ok) return;
        btn.innerHTML = CHECK_SVG;
        btn.classList.add('md-code-copy-btn--copied');
        setTimeout(function () {
          btn.innerHTML = COPY_SVG;
          btn.classList.remove('md-code-copy-btn--copied');
        }, 1500);
      });
    });
  }

  function createSettingsDropdown(anchorBtn) {
    _dismissAllDropdowns();
    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;
      if (left + 200 > window.innerWidth) left = window.innerWidth - 200;
      var top = rect.bottom + 2;
      if (top + dropdown.offsetHeight > window.innerHeight) {
        top = rect.top - 2 - dropdown.offsetHeight;
      }
      if (top < 0) top = 0;
      dropdown.style.top = top + '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 stripEnhancementArtifacts(editableArea) {
    if (!editableArea) return;
    var i, el, child;
    var wrappers = editableArea.querySelectorAll('.md-code-block');
    for (i = 0; i < wrappers.length; i++) {
      el = wrappers[i];
      child = el.querySelector('pre');
      if (child && el.parentNode) {
        el.parentNode.insertBefore(child, el);
        el.parentNode.removeChild(el);
      }
    }
    var staleButtons = editableArea.querySelectorAll(
      '.md-code-lang-btn, .md-code-settings-btn, .md-code-copy-btn, ' +
      '.md-admonition-settings-btn'
    );
    for (i = 0; i < staleButtons.length; i++) {
      el = staleButtons[i];
      if (el.parentNode) el.parentNode.removeChild(el);
    }
    var imgWrappers = editableArea.querySelectorAll('.md-image-wrapper');
    for (i = 0; i < imgWrappers.length; i++) {
      el = imgWrappers[i];
      child = el.querySelector('img');
      if (child && el.parentNode) {
        el.parentNode.insertBefore(child, el);
        el.parentNode.removeChild(el);
      }
    }
    var chk = editableArea.querySelectorAll('input[data-live-wysiwyg-checklist]');
    for (i = 0; i < chk.length; i++) {
      chk[i].removeAttribute('data-live-wysiwyg-checklist');
    }
    var patched = editableArea.querySelectorAll('summary[data-live-wysiwyg-click-patched]');
    for (i = 0; i < patched.length; i++) {
      patched[i].removeAttribute('data-live-wysiwyg-click-patched');
    }
  }

  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);
    }
  }

  var _mermaidJsLoaded = false;
  var _mermaidJsLoading = false;
  function _loadMermaidJs(cb) {
    if (_mermaidJsLoaded) { if (cb) cb(); return; }
    if (typeof mermaid !== 'undefined' && typeof mermaid.render === 'function') {
      _mermaidJsLoaded = true;
      if (cb) cb();
      return;
    }
    if (_mermaidJsLoading) {
      var iv = setInterval(function () {
        if (_mermaidJsLoaded) { clearInterval(iv); if (cb) cb(); }
      }, 100);
      return;
    }
    _mermaidJsLoading = true;
    var s = document.createElement('script');
    s.src = 'http://' + location.hostname + ':' + liveWysiwygLinkCheckPort + '/mermaid-editor/mermaid.min.js';
    s.onload = function () {
      _mermaidJsLoaded = true;
      if (typeof mermaid !== 'undefined') {
        mermaid.initialize({ startOnLoad: false, theme: 'default' });
      }
      if (cb) cb();
    };
    s.onerror = function () { _mermaidJsLoading = false; };
    document.head.appendChild(s);
  }

  function _buildMaterialMermaidCSS(svgId) {
    var bodyStyle = getComputedStyle(document.body);
    if (!bodyStyle.getPropertyValue('--md-mermaid-node-bg-color').trim()) return '';
    var s = '#' + svgId;
    return s + ' .node circle,' + s + ' .node ellipse,' + s + ' .node path,' + s + ' .node polygon,' + s + ' .node rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}' +
      s + ' marker{fill:var(--md-mermaid-edge-color)!important}' +
      s + ' .edgeLabel .label rect{fill:#0000}' +
      s + ' .flowchartTitleText{fill:var(--md-mermaid-label-fg-color)}' +
      s + ' .label{color:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' .label foreignObject{line-height:normal;overflow:visible}' +
      s + ' .label div .edgeLabel{color:var(--md-mermaid-label-fg-color)}' +
      s + ' .edgeLabel,' + s + ' .edgeLabel p,' + s + ' .label div .edgeLabel{background-color:var(--md-mermaid-label-bg-color)}' +
      s + ' .edgeLabel,' + s + ' .edgeLabel p{fill:var(--md-mermaid-label-bg-color);color:var(--md-mermaid-edge-color)}' +
      s + ' .edgePath .path,' + s + ' .flowchart-link{stroke:var(--md-mermaid-edge-color);stroke-width:.05rem}' +
      s + ' .edgePath .arrowheadPath{fill:var(--md-mermaid-edge-color);stroke:none}' +
      s + ' .cluster rect{fill:var(--md-default-fg-color--lightest);stroke:var(--md-default-fg-color--lighter)}' +
      s + ' .cluster span{color:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' g #flowchart-circleEnd,' + s + ' g #flowchart-circleStart,' + s + ' g #flowchart-crossEnd,' + s + ' g #flowchart-crossStart,' + s + ' g #flowchart-pointEnd,' + s + ' g #flowchart-pointStart{stroke:none}' +
      s + ' .nodeLabel,' + s + ' .nodeLabel p{color:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' a .nodeLabel{text-decoration:underline}' +
      s + ' .classDiagramTitleText{fill:var(--md-mermaid-label-fg-color)}' +
      s + ' g.classGroup line,' + s + ' g.classGroup rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}' +
      s + ' g.classGroup text{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' .classLabel .box{fill:var(--md-mermaid-label-bg-color);background-color:var(--md-mermaid-label-bg-color);opacity:1}' +
      s + ' .classLabel .label{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' .node .divider{stroke:var(--md-mermaid-node-fg-color)}' +
      s + ' .relation{stroke:var(--md-mermaid-edge-color)}' +
      s + ' .cardinality{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' .cardinality text{fill:inherit!important}' +
      s + ' defs marker.marker.composition.class path,' + s + ' defs marker.marker.dependency.class path,' + s + ' defs marker.marker.extension.class path{fill:var(--md-mermaid-edge-color)!important;stroke:var(--md-mermaid-edge-color)!important}' +
      s + ' defs marker.marker.aggregation.class path{fill:var(--md-mermaid-label-bg-color)!important;stroke:var(--md-mermaid-edge-color)!important}' +
      s + ' .statediagramTitleText{fill:var(--md-mermaid-label-fg-color)}' +
      s + ' g.stateGroup rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}' +
      s + ' g.stateGroup .state-title{fill:var(--md-mermaid-label-fg-color)!important;font-family:var(--md-mermaid-font-family)}' +
      s + ' g.stateGroup .composit{fill:var(--md-mermaid-label-bg-color)}' +
      s + ' .node circle.state-end,' + s + ' .node circle.state-start,' + s + ' .start-state{fill:var(--md-mermaid-edge-color);stroke:none}' +
      s + ' .end-state-inner,' + s + ' .end-state-outer{fill:var(--md-mermaid-edge-color)}' +
      s + ' .end-state-inner,' + s + ' .node circle.state-end{stroke:var(--md-mermaid-label-bg-color)}' +
      s + ' .transition{stroke:var(--md-mermaid-edge-color)}' +
      s + ' [id^=state-fork] rect,' + s + ' [id^=state-join] rect{fill:var(--md-mermaid-edge-color)!important;stroke:none!important}' +
      s + ' .statediagram-cluster.statediagram-cluster .inner{fill:var(--md-default-bg-color)}' +
      s + ' .statediagram-cluster rect{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}' +
      s + ' .statediagram-state rect.divider{fill:var(--md-default-fg-color--lightest);stroke:var(--md-default-fg-color--lighter)}' +
      s + ' defs #statediagram-barbEnd{stroke:var(--md-mermaid-edge-color)}' +
      s + ' .entityTitleText{fill:var(--md-mermaid-label-fg-color)}' +
      s + ' .attributeBoxEven,' + s + ' .attributeBoxOdd{fill:var(--md-mermaid-node-bg-color);stroke:var(--md-mermaid-node-fg-color)}' +
      s + ' .entityBox{fill:var(--md-mermaid-label-bg-color);stroke:var(--md-mermaid-node-fg-color)}' +
      s + ' .entityLabel{fill:var(--md-mermaid-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' .relationshipLabelBox{fill:var(--md-mermaid-label-bg-color);fill-opacity:1;background-color:var(--md-mermaid-label-bg-color);opacity:1}' +
      s + ' .relationshipLabel{fill:var(--md-mermaid-label-fg-color)}' +
      s + ' .relationshipLine{stroke:var(--md-mermaid-edge-color)}' +
      s + ' defs #ONE_OR_MORE_END *,' + s + ' defs #ONE_OR_MORE_START *,' + s + ' defs #ONLY_ONE_END *,' + s + ' defs #ONLY_ONE_START *,' + s + ' defs #ZERO_OR_MORE_END *,' + s + ' defs #ZERO_OR_MORE_START *,' + s + ' defs #ZERO_OR_ONE_END *,' + s + ' defs #ZERO_OR_ONE_START *{stroke:var(--md-mermaid-edge-color)!important}' +
      s + ' defs #ZERO_OR_MORE_END circle,' + s + ' defs #ZERO_OR_MORE_START circle{fill:var(--md-mermaid-label-bg-color)}' +
      s + ' text:not([class]):last-child{fill:var(--md-mermaid-label-fg-color)}' +
      s + ' .actor{fill:var(--md-mermaid-sequence-actor-bg-color);stroke:var(--md-mermaid-sequence-actor-border-color)}' +
      s + ' text.actor>tspan{fill:var(--md-mermaid-sequence-actor-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' line{stroke:var(--md-mermaid-sequence-actor-line-color)}' +
      s + ' .actor-man circle,' + s + ' .actor-man line{fill:var(--md-mermaid-sequence-actorman-bg-color);stroke:var(--md-mermaid-sequence-actorman-line-color)}' +
      s + ' .messageLine0,' + s + ' .messageLine1{stroke:var(--md-mermaid-sequence-message-line-color)}' +
      s + ' .note{fill:var(--md-mermaid-sequence-note-bg-color);stroke:var(--md-mermaid-sequence-note-border-color)}' +
      s + ' .loopText,' + s + ' .loopText>tspan,' + s + ' .messageText,' + s + ' .noteText>tspan{stroke:none;font-family:var(--md-mermaid-font-family)!important}' +
      s + ' .messageText{fill:var(--md-mermaid-sequence-message-fg-color)}' +
      s + ' .loopText,' + s + ' .loopText>tspan{fill:var(--md-mermaid-sequence-loop-fg-color)}' +
      s + ' .noteText>tspan{fill:var(--md-mermaid-sequence-note-fg-color)}' +
      s + ' #arrowhead path{fill:var(--md-mermaid-sequence-message-line-color);stroke:none}' +
      s + ' .loopLine{fill:var(--md-mermaid-sequence-loop-bg-color);stroke:var(--md-mermaid-sequence-loop-border-color)}' +
      s + ' .labelBox{fill:var(--md-mermaid-sequence-label-bg-color);stroke:none}' +
      s + ' .labelText,' + s + ' .labelText>span{fill:var(--md-mermaid-sequence-label-fg-color);font-family:var(--md-mermaid-font-family)}' +
      s + ' .sequenceNumber{fill:var(--md-mermaid-sequence-number-fg-color)}' +
      s + ' rect.rect{fill:var(--md-mermaid-sequence-box-bg-color);stroke:none}' +
      s + ' rect.rect+text.text{fill:var(--md-mermaid-sequence-box-fg-color)}' +
      s + ' defs #sequencenumber{fill:var(--md-mermaid-sequence-number-bg-color)!important}';
  }

  function _renderMermaidPreview(previewDiv, code) {
    if (typeof mermaid === 'undefined') return;
    previewDiv.innerHTML = '';
    var id = 'mermaid-preview-' + Math.random().toString(36).slice(2, 8);
    mermaid.render(id, code).then(function (result) {
      var svg = result.svg;
      var materialCSS = _buildMaterialMermaidCSS(id);
      if (materialCSS) {
        svg = svg.replace('</style>', materialCSS + '</style>');
      }
      previewDiv.innerHTML = svg;
    }).catch(function () {
      previewDiv.innerHTML = '<div style="color:#999;font-size:.85rem;padding:8px">Invalid mermaid syntax</div>';
    });
  }

  function enhanceMermaidBlocks(editableArea) {
    if (!editableArea) return;
    var pres = editableArea.querySelectorAll('pre[data-lang="mermaid"]');
    for (var i = 0; i < pres.length; i++) {
      var pre = pres[i];
      if (pre.parentNode && pre.parentNode.classList && pre.parentNode.classList.contains('md-mermaid-block')) {
        var mermaidWrapper = pre.parentNode;
        var existingPreview = mermaidWrapper.querySelector('.md-mermaid-preview');
        if (existingPreview && !existingPreview.innerHTML.trim()) {
          var code = pre.textContent || '';
          if (code.trim()) {
            (function (p, c) {
              _loadMermaidJs(function () { _renderMermaidPreview(p, c); });
            })(existingPreview, code);
          }
        }
        var existingBtn = mermaidWrapper.querySelector('.md-mermaid-expand-btn');
        if (existingBtn && !existingBtn.__mermaidHandlerAttached) {
          existingBtn.__mermaidHandlerAttached = true;
          (function (block, btn) {
            btn.addEventListener('click', function (e) {
              e.preventDefault();
              e.stopPropagation();
              if (typeof enterMermaidMode === 'function') enterMermaidMode(block);
            });
          })(mermaidWrapper, existingBtn);
        }
        continue;
      }
      if (pre.parentNode && pre.parentNode.classList && pre.parentNode.classList.contains('md-code-block')) continue;
      var wrapper = document.createElement('div');
      wrapper.className = 'md-mermaid-block';
      wrapper.setAttribute('contenteditable', 'false');
      var preview = document.createElement('div');
      preview.className = 'md-mermaid-preview';
      var expandBtn = document.createElement('button');
      expandBtn.className = 'md-mermaid-expand-btn';
      expandBtn.setAttribute('contenteditable', 'false');
      expandBtn.setAttribute('title', 'Edit in Mermaid Mode');
      expandBtn.innerHTML = '&#x26F6;';
      (function (block) {
        expandBtn.addEventListener('click', function (e) {
          e.preventDefault();
          e.stopPropagation();
          if (typeof enterMermaidMode === 'function') enterMermaidMode(block);
        });
      })(wrapper);
      pre.parentNode.insertBefore(wrapper, pre);
      wrapper.appendChild(preview);
      wrapper.appendChild(expandBtn);
      pre.style.display = 'none';
      wrapper.appendChild(pre);
      var code = pre.textContent || '';
      (function (p, c) {
        _loadMermaidJs(function () { _renderMermaidPreview(p, c); });
      })(preview, code);
    }
  }

  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.getAttribute('data-lang') === 'mermaid') continue;
      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);
      };
    }

    proto._handleKeyDownShared = function () {};
  })();

  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) {
    _dismissAllDropdowns();

    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;
      if (left + 210 > window.innerWidth) left = window.innerWidth - 210;
      var top = rect.bottom + 2;
      if (top + dropdown.offsetHeight > window.innerHeight) {
        top = rect.top - 2 - dropdown.offsetHeight;
      }
      if (top < 0) top = 0;
      dropdown.style.top = top + '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 detailsTagMatch = decoded.match(/^\s*<details\b([^>]*)>/i);
        var detailsAttrs = detailsTagMatch ? detailsTagMatch[1] : '';
        var detailsClassMatch = detailsAttrs.match(/class\s*=\s*["']([^"']*)["']/i);
        var detailsHasOpen = /\bopen\b/i.test(detailsAttrs);
        var detailsType = 'note';
        if (detailsClassMatch) {
          var detailsClasses = detailsClassMatch[1].split(/\s+/);
          for (var dti = 0; dti < ADMONITION_TYPE_IDS.length; dti++) {
            if (detailsClasses.indexOf(ADMONITION_TYPE_IDS[dti]) >= 0) {
              detailsType = ADMONITION_TYPE_IDS[dti];
              break;
            }
          }
        }

        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 = detailsType;
        newDetails.setAttribute('data-details-tag', '1');
        if (!detailsHasOpen) 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);
        enhanceMermaidBlocks(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');
    if (!det.hasAttribute('open')) 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);
    enhanceMermaidBlocks(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) {
      _dismissAllDropdowns();
      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);
    };
  })();

  // --- Ctrl/Cmd+hover overlay link (state hoisted for keyboard router access) ---
  var _ctrlLinkOverlay = null;
  var _ctrlHeld = false;

  function _showCtrlLinkOverlay(anchorEl) {
    _hideCtrlLinkOverlay();
    var href = anchorEl.getAttribute('href');
    if (!href) return;
    var rect = anchorEl.getBoundingClientRect();
    var overlay = document.createElement('a');
    overlay.href = href;
    overlay.target = '_blank';
    overlay.rel = 'noopener';
    overlay.setAttribute('contenteditable', 'false');
    overlay.style.cssText = 'position:fixed;display:block;opacity:0;cursor:pointer;z-index:99997;' +
      'top:' + rect.top + 'px;left:' + rect.left + 'px;width:' + rect.width + 'px;height:' + rect.height + 'px;';
    overlay.addEventListener('mouseleave', function () { _hideCtrlLinkOverlay(); });
    var host = _focusOverlay || document.body;
    host.appendChild(overlay);
    _ctrlLinkOverlay = overlay;
  }

  function _hideCtrlLinkOverlay() {
    if (_ctrlLinkOverlay && _ctrlLinkOverlay.parentNode) {
      _ctrlLinkOverlay.parentNode.removeChild(_ctrlLinkOverlay);
    }
    _ctrlLinkOverlay = null;
  }

  (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;
      }
    }
    _dismissLinkDropdownFn = dismissLinkDropdown;

    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) {
      _dismissAllDropdowns();
      _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);
            }
            _compat.exec('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); }
      });
      if (!existingAnchor) _compat.cacheClipboardForGesture();
      requestAnimationFrame(function () {
        urlInput.focus(); urlInput.select();
        if (!existingAnchor && urlInput.value === 'https://') {
          _compat.readClipboardText().then(function (text) {
            text = (text || '').trim();
            if (/^https?:\/\//.test(text)) {
              urlInput.value = text;
              urlInput.select();
              dirty = true;
            }
          });
        }
      });

      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();
        }
      });

      document.addEventListener('selectionchange', function () {
        if (!wysiwygEditor || wysiwygEditor.currentMode !== 'wysiwyg') return;
        if (!editableArea) return;
        _updateHeadingTrackerWysiwyg(editableArea);
      });

      editableArea.addEventListener('mouseover', function (e) {
        if (!_ctrlHeld) return;
        var node = e.target;
        while (node && node !== editableArea) {
          if (node.nodeName === 'A' && node.getAttribute('href')) {
            _showCtrlLinkOverlay(node);
            return;
          }
          node = node.parentNode;
        }
        _hideCtrlLinkOverlay();
      });
    }

    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) {
    _dismissAllDropdowns();

    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;
      if (left + 260 > window.innerWidth) left = window.innerWidth - 260;
      var top = rect.bottom + 2;
      if (top + dropdown.offsetHeight > window.innerHeight) {
        top = rect.top - 2 - dropdown.offsetHeight;
      }
      if (top < 0) top = 0;
      dropdown.style.top = top + '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
    });
    _compat.cacheClipboardForGesture();
    requestAnimationFrame(function () {
      urlInput.focus();
      _compat.readClipboardText().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());
        }
      });
    });

    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) {
    _dismissAllDropdowns();

    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;
      if (left + 240 > window.innerWidth) left = window.innerWidth - 240;
      var top = rect.bottom + 2;
      if (top + dropdown.offsetHeight > window.innerHeight) {
        top = rect.top - 2 - dropdown.offsetHeight;
      }
      if (top < 0) top = 0;
      dropdown.style.top = top + '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') || cn.classList.contains('md-code-copy-btn'))) 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') || ch.classList.contains('md-code-copy-btn'))) 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-mermaid-block')) {
        var mermaidPre = node.querySelector('pre');
        if (mermaidPre) {
          return this._nodeToMarkdownRecursive(mermaidPre, 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') || node.classList.contains('md-code-copy-btn'))) {
        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 ? _admonitionTitleText(titleEl).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();
            var detailsOpenTag = '<details';
            if (type) detailsOpenTag += ' class="' + type + '"';
            if (isExpanded) detailsOpenTag += ' open';
            detailsOpenTag += '>';
            return detailsOpenTag + '\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';
        } else if (_isDetailsAdmonition) {
          var fbTitleEl = node.querySelector(':scope > summary');
          var fbSummary = fbTitleEl ? _admonitionTitleText(fbTitleEl).replace(/\u00a0/g, ' ').trim() : 'Details';
          var fbExpanded = !node.hasAttribute('data-default-collapsed');
          var fbBodyParts = [];
          for (var fj = 0; fj < node.childNodes.length; fj++) {
            var fc = node.childNodes[fj];
            if (fc === fbTitleEl) continue;
            if (fc.nodeType === 1 && fc.classList && fc.classList.contains('md-admonition-settings-btn')) continue;
            if (fc.nodeType === 3) {
              var ftxt = fc.textContent;
              if (ftxt && !/^[\s\u200B\u200C\u200D\uFEFF]*$/.test(ftxt)) fbBodyParts.push(ftxt);
              continue;
            }
            if (fc.nodeType !== 1) continue;
            fbBodyParts.push(this._nodeToMarkdownRecursive(fc, options || {}));
          }
          var fbBody = fbBodyParts.join('\n').trim();
          var fbOpenTag = '<details';
          if (fbExpanded) fbOpenTag += ' open';
          fbOpenTag += '>';
          return fbOpenTag + '\n<summary>' + fbSummary + '</summary>\n\n' + fbBody + '\n\n</details>\n\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 enhanceMermaidBlocks === 'function') enhanceMermaidBlocks(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');
  }

  var TABLE_WIDTH_DEFAULT = 120;
  function _getGlobalTableWidth() {
    var v = parseInt(_getSetting('live_wysiwyg_table_width'), 10);
    return v > 0 ? v : TABLE_WIDTH_DEFAULT;
  }
  function _setGlobalTableWidth(w) {
    _setSetting('live_wysiwyg_table_width', String(w));
  }
  window._getGlobalTableWidth = _getGlobalTableWidth;
  window._setGlobalTableWidth = _setGlobalTableWidth;

  function _getMinimalTables() { return _getSetting('live_wysiwyg_minimal_tables') === '1'; }
  function _setMinimalTables(v) { _setSetting('live_wysiwyg_minimal_tables', v ? '1' : '0'); }
  window._getMinimalTables = _getMinimalTables;
  window._setMinimalTables = _setMinimalTables;

  function _computeNaturalTableWidth(tableEl) {
    var rows = tableEl.querySelectorAll('tr');
    if (!rows.length) return 0;
    var colCount = rows[0].cells.length;
    var maxWidths = [];
    for (var c = 0; c < colCount; c++) maxWidths.push(3);
    for (var r = 0; r < rows.length; r++) {
      for (c = 0; c < rows[r].cells.length && c < colCount; c++) {
        var text = (rows[r].cells[c].textContent || '').replace(/[\u200B\u200C\u200D]/g, '').trim();
        if (text.length > maxWidths[c]) maxWidths[c] = text.length;
      }
    }
    var total = 1;
    for (c = 0; c < colCount; c++) total += maxWidths[c] + 3;
    return total;
  }
  window._computeNaturalTableWidth = _computeNaturalTableWidth;

  function _collectTableWidthsFromDOM(editableArea) {
    if (!editableArea) return [];
    var domTables = editableArea.querySelectorAll('table');
    var globalW = _getGlobalTableWidth();
    var widths = [];
    for (var t = 0; t < domTables.length; t++) {
      var stored = parseInt(domTables[t].dataset.tableWidth, 10) || 0;
      var natural = _computeNaturalTableWidth(domTables[t]);
      if (natural > stored && natural <= globalW) {
        stored = natural;
        domTables[t].dataset.tableWidth = stored;
      } else if (natural > stored && natural > globalW) {
        stored = globalW;
        domTables[t].dataset.tableWidth = stored;
      }
      widths.push(stored);
    }
    return widths;
  }

  function _parseTableCells(line) {
    var trimmed = line.replace(/[\u200B\u200C\u200D]/g, '').trim();
    if (trimmed.charAt(0) === '|') trimmed = trimmed.substring(1);
    if (trimmed.charAt(trimmed.length - 1) === '|') trimmed = trimmed.substring(0, trimmed.length - 1);
    return trimmed.split('|').map(function (c) { return c.trim(); });
  }

  function _parseTableCellsRaw(line) {
    var trimmed = line.trim();
    if (trimmed.charAt(0) === '|') trimmed = trimmed.substring(1);
    if (trimmed.charAt(trimmed.length - 1) === '|') trimmed = trimmed.substring(0, trimmed.length - 1);
    return trimmed.split('|').map(function (c) { return c.trim(); });
  }

  function _formatBalancedTable(tableLines, widthLimit) {
    var rows = tableLines.map(_parseTableCells);
    var rawRows = tableLines.map(_parseTableCellsRaw);
    var sepIdx = 1;
    var colCount = rows[0].length;
    var limit = widthLimit || _getGlobalTableWidth();

    var aligns = [];
    for (var c = 0; c < colCount; c++) {
      var sep = (rows[sepIdx] && rows[sepIdx][c]) || '---';
      var left = sep.charAt(0) === ':';
      var right = sep.charAt(sep.length - 1) === ':';
      if (left && right) aligns.push('center');
      else if (right) aligns.push('right');
      else aligns.push('left');
    }

    var widths = [];
    for (c = 0; c < colCount; c++) {
      var maxW = 3;
      for (var r = 0; r < rows.length; r++) {
        if (r === sepIdx) continue;
        var cell = (rows[r][c] || '');
        if (cell.length > maxW) maxW = cell.length;
      }
      widths.push(maxW);
    }

    var overhead = 1 + colCount * 3;
    var total = overhead;
    for (c = 0; c < colCount; c++) total += widths[c];
    if (total > limit) {
      var available = limit - overhead;
      var fair = Math.max(3, Math.floor(available / colCount));
      for (c = 0; c < colCount; c++) {
        if (widths[c] > fair) widths[c] = fair;
      }
    } else if (total < limit && !_getMinimalTables()) {
      var extra = limit - total;
      var contentTotal = 0;
      for (c = 0; c < colCount; c++) contentTotal += widths[c];
      if (contentTotal > 0) {
        var distributed = 0;
        for (c = 0; c < colCount - 1; c++) {
          var share = Math.floor(extra * widths[c] / contentTotal);
          widths[c] += share;
          distributed += share;
        }
        widths[colCount - 1] += (extra - distributed);
      }
    }

    var out = [];
    for (var r2 = 0; r2 < rows.length; r2++) {
      if (r2 === sepIdx) {
        var sepCells = [];
        for (c = 0; c < colCount; c++) {
          var al = aligns[c];
          var dashCount = widths[c];
          if (al === 'center') {
            sepCells.push(':' + '-'.repeat(Math.max(1, dashCount - 2)) + ':');
          } else if (al === 'right') {
            sepCells.push('-'.repeat(Math.max(1, dashCount - 1)) + ':');
          } else {
            sepCells.push('-'.repeat(dashCount));
          }
        }
        out.push('| ' + sepCells.join(' | ') + ' |');
      } else {
        var cells = [];
        for (c = 0; c < colCount; c++) {
          var cell2 = rawRows[r2][c] || '';
          var cleanLen = (rows[r2][c] || '').length;
          var pad = widths[c] - cleanLen;
          if (pad <= 0) {
            cells.push(cell2);
          } else if (aligns[c] === 'right') {
            cells.push(' '.repeat(pad) + cell2);
          } else if (aligns[c] === 'center') {
            var lpad = Math.floor(pad / 2);
            cells.push(' '.repeat(lpad) + cell2 + ' '.repeat(pad - lpad));
          } else {
            cells.push(cell2 + ' '.repeat(pad));
          }
        }
        out.push('| ' + cells.join(' | ') + ' |');
      }
    }
    return out.join('\n');
  }

  function preprocessTables(markdown) {
    if (!markdown || typeof markdown !== 'string') return { tables: [] };
    var tables = [];
    var lines = markdown.split('\n');
    var i = 0;
    while (i < lines.length) {
      if (i + 1 < lines.length &&
          /\|/.test(lines[i]) &&
          /^\|[\s:=-]+(\|[\s:=-]+)+\|?\s*$/.test(lines[i + 1])) {
        var start = i;
        i += 2;
        while (i < lines.length && /\|/.test(lines[i]) && !/^\s*$/.test(lines[i])) {
          i++;
        }
        var rawLines = lines.slice(start, i);
        var raw = rawLines.join('\n');
        var norm = raw.replace(/\s+/g, '');
        var allSame = true;
        for (var k = 1; k < rawLines.length; k++) {
          if (rawLines[k].length !== rawLines[0].length) { allSame = false; break; }
        }
        var dw = allSame ? rawLines[0].length : 0;
        tables.push({ raw: raw, norm: norm, detectedWidth: dw });
      } else {
        i++;
      }
    }
    return { tables: tables };
  }

  function postprocessTables(markdown, tableData, tableWidths) {
    if (!markdown || typeof markdown !== 'string') return markdown;
    if (!tableData || !tableData.tables) return markdown;
    var originals = tableData.tables;
    var lines = markdown.split('\n');
    var result = [];
    var used = 0;
    var tableIdx = 0;
    var i = 0;
    while (i < lines.length) {
      if (i + 1 < lines.length &&
          /\|/.test(lines[i]) &&
          /^\|(\s*:?---+:?\s*\|)+\s*$/.test(lines[i + 1])) {
        var start = i;
        i += 2;
        while (i < lines.length && /\|/.test(lines[i]) && !/^\s*$/.test(lines[i])) {
          i++;
        }
        var tableLines = lines.slice(start, i);
        var tableText = tableLines.join('\n');
        var hasCursorMarkers = tableText.indexOf('\u200C\u200C\u200C\u200C\u200C\u200C') >= 0 || tableText.indexOf('\u200D\u200D\u200D\u200D\u200D\u200D') >= 0;
        var norm = tableText.replace(/[\u200B\u200C\u200D]/g, '').replace(/\s+/g, '');
        var perTableWidth = (tableWidths && tableWidths[tableIdx]) || 0;
        var matched = false;
        for (var j = used; j < originals.length; j++) {
          if (originals[j].norm === norm) {
            var origLines = originals[j].raw.split('\n');
            var allSameLen = true;
            for (var k = 1; k < origLines.length; k++) {
              if (origLines[k].length !== origLines[0].length) { allSameLen = false; break; }
            }
            var effectiveWidth = perTableWidth || originals[j].detectedWidth || _getGlobalTableWidth();
            if (allSameLen && !hasCursorMarkers && (!perTableWidth || perTableWidth === originals[j].detectedWidth)) {
              result.push(originals[j].raw);
            } else if (hasCursorMarkers) {
              result.push(_formatBalancedTable(tableLines, effectiveWidth));
            } else {
              result.push(_formatBalancedTable(origLines, effectiveWidth));
            }
            used = j + 1;
            matched = true;
            break;
          }
        }
        if (!matched) {
          var newWidth = perTableWidth || _getGlobalTableWidth();
          result.push(_formatBalancedTable(tableLines, newWidth));
        }
        tableIdx++;
      } else {
        result.push(lines[i]);
        i++;
      }
    }
    return result.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 + 1;
              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._liveWysiwygTableData = preprocessTables(mdWithRefsExtracted);
        this._liveWysiwygCodeBlockData = preprocessCodeBlocks(mdWithRefsExtracted);
        this._liveWysiwygHrData = preprocessHorizontalRules(mdWithRefsExtracted);
        this._liveWysiwygInlineCodeData = preprocessInlineCode(mdWithRefsExtracted);
        mdToUse = mdWithRefsExtracted;
      }
      var setResult = origSetValue.apply(this, [mdToUse, isInitialSetup]);
      if (this._liveWysiwygTableData && this.editableArea) {
        var domTbls = this.editableArea.querySelectorAll('table');
        var tblArr = this._liveWysiwygTableData.tables;
        for (var ti = 0; ti < domTbls.length && ti < tblArr.length; ti++) {
          if (tblArr[ti].detectedWidth > 0) {
            domTbls[ti].dataset.tableWidth = tblArr[ti].detectedWidth;
          }
        }
      }
      return setResult;
    };
    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._liveWysiwygTableData = preprocessTables(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 tableWidthsForSwitch = _collectTableWidthsFromDOM(this.editableArea);
      var result = origSwitchToMode.apply(this, arguments);
      if (mode === 'wysiwyg' && this._liveWysiwygTableData && this.editableArea) {
        var domTbls2 = this.editableArea.querySelectorAll('table');
        var tblArr2 = this._liveWysiwygTableData.tables;
        for (var ti2 = 0; ti2 < domTbls2.length && ti2 < tblArr2.length; ti2++) {
          if (tblArr2[ti2].detectedWidth > 0) {
            domTbls2[ti2].dataset.tableWidth = tblArr2[ti2].detectedWidth;
          }
        }
      }
      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._liveWysiwygTableData) {
          md = postprocessTables(md, this._liveWysiwygTableData, tableWidthsForSwitch);
        }
        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._liveWysiwygTableData) {
        var tw = _collectTableWidthsFromDOM(this.editableArea);
        body = postprocessTables(body, this._liveWysiwygTableData, tw);
      }
      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 _admonitionTitleText(el) {
    var result = '';
    for (var i = 0; i < el.childNodes.length; i++) {
      var child = el.childNodes[i];
      if (child.nodeType === 3) {
        result += child.textContent;
      } else if (child.nodeType === 1) {
        var sc = child.getAttribute && child.getAttribute('data-emoji-shortcode');
        if (sc) {
          result += sc;
        } else {
          result += _admonitionTitleText(child);
        }
      }
    }
    return result;
  }

  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, '');
          var needed = 1;
          var brun = 0;
          for (var ci = 0; ci < inner.length; ci++) {
            if (inner.charAt(ci) === '`') { brun++; if (brun >= needed) needed = brun + 1; }
            else { brun = 0; }
          }
          if (needed >= 2) {
            var ticks = '';
            for (var ti = 0; ti < needed; ti++) ticks += '`';
            md += ticks + ' ';
            walkChildren(node);
            md += ' ' + ticks;
          } 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 = _admonitionTitleText(adTitleEl).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 = _admonitionTitleText(summaryEl).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;
        }
        ensureTrailingNewlines(md.length > 0 ? 2 : 0);
        var detFbPrefix = '??? note';
        var detFbSummaryEl = null;
        for (var fsc = node.firstChild; fsc; fsc = fsc.nextSibling) {
          if (fsc.nodeType === 1 && fsc.nodeName === 'SUMMARY') { detFbSummaryEl = fsc; break; }
        }
        if (detFbSummaryEl) {
          var detFbSummaryText = _admonitionTitleText(detFbSummaryEl).replace(/\u00b6/g, '').trim();
          if (detFbSummaryText && detFbSummaryText !== 'Note') detFbPrefix += ' "' + detFbSummaryText + '"';
        }
        md += detFbPrefix + '\n';
        var detFbSavedLen = md.length;
        for (var fdc = node.firstChild; fdc; fdc = fdc.nextSibling) {
          if (fdc === detFbSummaryEl) continue;
          if (fdc.nodeType === 1 && fdc.classList && fdc.classList.contains('md-admonition-settings-btn')) continue;
          walk(fdc);
        }
        var detFbBody = md.slice(detFbSavedLen);
        md = md.slice(0, detFbSavedLen);
        var detFbLines = detFbBody.split('\n');
        for (var fbli = 0; fbli < detFbLines.length; fbli++) {
          md += detFbLines[fbli] ? '    ' + detFbLines[fbli] : '';
          if (fbli < detFbLines.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 enhanceMermaidBlocks === 'function') enhanceMermaidBlocks(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);
        enhanceMermaidBlocks(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);
          enhanceMermaidBlocks(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);
        enhanceMermaidBlocks(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 _mermaidModeActive = false;
  var _mermaidOverlay = null;
  var _mermaidSourceBlock = null;
  var _mermaidIframe = null;
  var _mermaidSessionId = '';
  var _mermaidSavedBodyOverflow = '';
  var _mermaidSavedDocElOverflow = '';
  var _mermaidOriginalCode = '';
  var MERMAID_MODE_STYLE_ID = 'live-wysiwyg-mermaid-mode-styles';

  function _replaceMermaidCodeBlock(markdown, originalCode, newCode) {
    var trimmedOriginal = originalCode.trim();
    var re = /^```mermaid\s*\n([\s\S]*?)^```\s*$/gm;
    var match;
    while ((match = re.exec(markdown)) !== null) {
      if (match[1].trim() === trimmedOriginal) {
        var blockStart = match.index;
        var blockEnd = match.index + match[0].length;
        var fenceOpen = '```mermaid\n';
        var fenceClose = '\n```';
        return markdown.substring(0, blockStart) + fenceOpen + newCode + fenceClose + markdown.substring(blockEnd);
      }
    }
    return markdown;
  }

  var _focusOverlay = null;
  var _focusTocObserver = null;
  var _focusContentScrollHandler = null;
  var _focusTocDebounceTimer = null;
  var _focusHeadingScrollHandler = null;
  var _focusSavedBodyOverflow = '';
  var _focusSavedDocElOverflow = '';
  var _focusSavedContentHeight = '';
  var _focusOriginalToolbarParent = null;
  var _focusMdInputHandler = null;
  var _focusMdCursorHandler = null;
  var _focusMdPasteHandler = null;

  var _helpModalOpen = false;
  var _helpSections = null;
  var _helpRenderedCache = {};

  var _focusModeGuardActive = false;
  var _focusModePollerTimer = null;
  var _focusModeRebuildPromptOpen = false;
  var _admonitionDropdownDismiss = null;
  var _reviewPopupDismiss = null;
  var _userActionInProgress = false;
  var _focusModeBuildEpoch = null;
  var _bgSavePendingRebuild = false;
  var _fmgOrigXHROpen = null;
  var _fmgOrigXHRSend = null;
  var _focusModeLocationGuardHandle = 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 _navBatchQueue = [];
  var _batchClaimedPaths = (typeof Set !== 'undefined' ? new Set() : null);
  var _navSnapshots = [];
  var _navSnapshotIndex = -1;
  var _navDiskSnapshotIndex = -1;
  var _navCleanSnapshot = null;
  var _navBadges = [];
  var _uidCounter = 0;
  var _suppressWarningSnapshot = false;
  var _warningSnapshotTimer = null;
  var _warningDirectMode = false;
  var _navTopWarnings = [];
  var _virtualMkdocsYml = null;
  var _virtualGeneratedMkdocsYml = null;
  var _headingTracker = { active: false, element: null, lineIndex: -1, originalText: '', originalSlug: '', srcPath: '' };
  var _lastCopiedHeadingLink = 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();
    var origPath = (typeof liveWysiwygOriginalMkdocsYml === 'string' && liveWysiwygOriginalMkdocsYml)
      ? liveWysiwygOriginalMkdocsYml : null;
    var primaryPath = origPath || '../mkdocs.yml';
    return _wsGetContents(primaryPath).then(function (yml) {
      _virtualMkdocsYml = yml || '';
      if (origPath) {
        return _wsGetContents('../mkdocs.yml').then(function (genYml) {
          _virtualGeneratedMkdocsYml = genYml || '';
        }).catch(function (err) {
          console.warn('[nav] Failed to pre-fetch generated mkdocs.yml:', err);
          _virtualGeneratedMkdocsYml = null;
        });
      }
    }).catch(function (err) {
      console.warn('[nav] Failed to pre-fetch mkdocs.yml:', err);
      _virtualMkdocsYml = '';
    });
  }

  function _applyYmlTransform(fn) {
    _virtualMkdocsYml = fn(_virtualMkdocsYml || '');
    if (_virtualGeneratedMkdocsYml != null) {
      _virtualGeneratedMkdocsYml = fn(_virtualGeneratedMkdocsYml || '');
    }
  }

  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'
  };

  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 _fmDeepEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return a == b;
    if (typeof a !== typeof b) return false;
    if (typeof a !== 'object') return false;
    return JSON.stringify(a) === JSON.stringify(b);
  }

  function _extractRawFmBlocks(rawFmText) {
    if (!rawFmText) return {};
    var inner = rawFmText;
    if (inner.startsWith('---')) {
      var startIdx = inner.indexOf('\n');
      if (startIdx === -1) return {};
      inner = inner.substring(startIdx + 1);
    }
    var endIdx = inner.lastIndexOf('\n---');
    if (endIdx !== -1) inner = inner.substring(0, endIdx);
    else {
      endIdx = inner.lastIndexOf('\n...');
      if (endIdx !== -1) inner = inner.substring(0, endIdx);
    }

    var lines = inner.split('\n');
    var blocks = {};
    var currentKey = null;
    var currentLines = [];
    for (var i = 0; i < lines.length; i++) {
      var line = lines[i];
      var m = line.match(/^([a-zA-Z_][\w-]*)\s*:/);
      if (m) {
        if (currentKey !== null) {
          blocks[currentKey] = currentLines.join('\n');
        }
        currentKey = m[1];
        currentLines = [line];
      } else if (currentKey !== null) {
        currentLines.push(line);
      }
    }
    if (currentKey !== null) {
      blocks[currentKey] = currentLines.join('\n');
    }
    return blocks;
  }

  function _buildFrontmatterFromFm(fm, isIndex, origFm, rawFmText) {
    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;
      }
    }

    var rawBlocks = _extractRawFmBlocks(rawFmText);

    function makeLine(key) {
      var val = fm[key];
      if (val == null) return null;
      if (key in nwKeys && shouldStrip(key, val)) return null;
      if (rawBlocks[key] && origFm && origFm.hasOwnProperty(key) && _fmDeepEqual(val, origFm[key])) {
        return rawBlocks[key];
      }
      var serialized = _fmSerialize(val);
      if (serialized.indexOf('\n') !== -1) {
        var indented = serialized.split('\n').map(function(l) { return '  ' + l; }).join('\n');
        return key + ':\n' + indented;
      }
      return key + ': ' + serialized;
    }

    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;
    }
    if (val !== null && typeof val === 'object' && typeof jsyaml !== 'undefined') {
      return jsyaml.dump(val, { indent: 2, lineWidth: -1, noRefs: true }).trimEnd();
    }
    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;
      }
      console.log('[bulk-ws] creating new WebSocket connection to port', ws_port);
      var ws = new WebSocket('ws://' + location.hostname + ':' + ws_port);
      ws.onerror = function () {
        console.error('[bulk-ws] connection error (onerror fired)');
        reject(new Error('Bulk WS connection failed'));
      };
      ws.onclose = function (ev) {
        console.warn('[bulk-ws] connection closed: code=' + ev.code + ' reason=' + (ev.reason || '(none)') + ' wasClean=' + ev.wasClean);
        _bulkWs = null;
      };
      ws.onopen = function () {
        console.log('[bulk-ws] connection opened, waiting for connected message');
        var connHandler = function (e) {
          ws.removeEventListener('message', connHandler);
          try {
            var data = JSON.parse(e.data);
            if (data && data.action === 'connected') {
              console.log('[bulk-ws] received connected message, ready');
              _bulkWs = ws;
              resolve(ws);
              return;
            }
          } catch (err) { /* not JSON */ }
          _bulkWs = ws;
          resolve(ws);
        };
        ws.addEventListener('message', connHandler);
        setTimeout(function () {
          ws.removeEventListener('message', connHandler);
          console.warn('[bulk-ws] connected message timeout, resolving anyway');
          _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 sendTs = Date.now();
        var handler = function (e) {
          try {
            var data = JSON.parse(e.data);
            if (data && data.action === action) {
              var elapsed = Date.now() - sendTs;
              if (data.success === false) {
                console.error('[ws-send] ' + action + ' ' + path + ' server returned error in ' + elapsed + 'ms:', data.error);
              } else {
                console.log('[ws-send] ' + action + ' ' + path + ' OK in ' + elapsed + 'ms');
              }
              cleanup();
              resolve(data);
            } else if (data && data.action === 'error') {
              console.error('[ws-send] server error while waiting for ' + action + ' ' + path + ':', data.message);
            }
          } catch (err) {
            cleanup();
            resolve(e.data);
          }
        };
        var closeHandler = function (ev) {
          console.error('[ws-send] WS CLOSED while awaiting ' + action + ' ' + path +
            ' (code=' + ev.code + ' reason=' + (ev.reason || 'none') + ' clean=' + ev.wasClean +
            ' elapsed=' + (Date.now() - sendTs) + 'ms, readyState=' + ws.readyState + ')');
          cleanup();
          _bulkWs = null;
          reject({ _wsRetryable: true, message: 'WS closed during ' + action + ' ' + path });
        };
        var errorHandler = function () {
          console.error('[ws-send] WS ERROR while awaiting ' + action + ' ' + path +
            ' (elapsed=' + (Date.now() - sendTs) + 'ms, readyState=' + ws.readyState + ')');
          cleanup();
          _bulkWs = null;
          reject({ _wsRetryable: true, message: 'WS error during ' + action + ' ' + path });
        };
        var timer = setTimeout(function () {
          console.error('[ws-send] TIMEOUT (15s) for ' + action + ' ' + path +
            ' readyState=' + ws.readyState + ' — server may be blocked on sync I/O');
          cleanup();
          _bulkWs = null;
          reject({ _wsRetryable: true, message: '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);
        console.log('[ws-send] >> ' + action + ' ' + path);
        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) {
        var retryable = err && err._wsRetryable;
        console.warn('[ws-send] attempt ' + attempt + '/' + _WS_MAX_RETRIES + ' failed for ' +
          action + ' ' + path + ' retryable=' + !!retryable + ': ' + (err && err.message || err));
        if (retryable && attempt < _WS_MAX_RETRIES) {
          console.log('[ws-send] retrying after rebuild+reconnect...');
          return _waitForRebuildAndReconnect().then(tryOnce);
        }
        throw retryable ? new Error(err.message) : err;
      });
    }
    return tryOnce();
  }

  function _wsGetContents(path) {
    return _wsSend('get_contents', path).then(function (resp) {
      if (resp && resp.success === false) {
        console.error('[ws-get] server failed to read ' + path + ': ' + (resp.error || 'unknown'));
        throw new Error('Failed to read ' + path + ': ' + (resp.error || 'unknown'));
      }
      if (resp && typeof resp.contents === 'string') return resp.contents;
      if (typeof resp === 'string') return resp;
      if (resp && resp.contents !== undefined && resp.contents !== null) 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 _reloadLocationGuardHandle = 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 && !_bgSavePendingRebuild && !_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);
    };

    _reloadLocationGuardHandle = _compat.installLocationGuard({
      id: 'reload-guard',
      isActive: function () { return _reloadGuardActive; }
    });
  }

  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 (_reloadLocationGuardHandle) {
      _reloadLocationGuardHandle.remove();
      _reloadLocationGuardHandle = 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);
    };

    _focusModeLocationGuardHandle = _compat.installLocationGuard({
      id: 'focus-mode',
      isActive: function () { return _focusModeGuardActive; },
      onIntercept: function () {
        if (!_reloadGuardActive && !_userActionInProgress && !_bgSavePendingRebuild) _onExternalRebuild();
      }
    });

    _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 (_focusModeLocationGuardHandle) {
      _focusModeLocationGuardHandle.remove();
      _focusModeLocationGuardHandle = 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 consecutiveFailures = 0;

    function poll() {
      if (!_focusModeGuardActive) return;
      var host = window.location.hostname || '127.0.0.1';
      var epochUrl = 'http://' + host + ':' + liveWysiwygLinkCheckPort + '/build-epoch';
      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;
        consecutiveFailures = 0;
        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 (_bgSavePendingRebuild) _bgSavePendingRebuild = false;
        _focusModePollerTimer = setTimeout(poll, 2000);
      }).catch(function () {
        if (!_focusModeGuardActive) return;
        consecutiveFailures++;
        var delay = Math.min(2000 * Math.pow(2, consecutiveFailures - 1), 30000);
        if (consecutiveFailures >= 3) {
          _refreshLinkCheckPort().then(function () {
            _focusModePollerTimer = setTimeout(poll, delay);
          });
        } else {
          _focusModePollerTimer = setTimeout(poll, delay);
        }
      });
    }
    _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) _exitNavEditModeDestructive(true);
          _focusModeRefreshContent().then(function () {
            _startFocusModeRebuildPoller();
          });
        } else {
          _startFocusModeRebuildPoller();
        }
      });
    }
  }

  function _closeBulkWs() {
    if (_bulkWs) {
      console.log('[bulk-ws] closing (readyState=' + _bulkWs.readyState + ')');
      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() {
    console.log('[ws-reconnect] starting: close bulk WS, wait for rebuild, reconnect');
    _closeBulkWs();
    return _waitForRebuild().then(function () {
      console.log('[ws-reconnect] rebuild detected, refreshing link check port');
      return _refreshLinkCheckPort();
    }).then(function () {
      var wsAttempts = 0;
      var wsMaxAttempts = 20;
      var wsDelay = 1500;
      function tryConnect() {
        wsAttempts++;
        console.log('[ws-reconnect] WS connect attempt ' + wsAttempts + '/' + wsMaxAttempts);
        return _getOrCreateBulkWs().catch(function (err) {
          console.warn('[ws-reconnect] attempt ' + wsAttempts + ' failed:', err && err.message || err);
          if (wsAttempts < wsMaxAttempts) {
            return new Promise(function (r) { setTimeout(r, wsDelay); }).then(tryConnect);
          }
          throw new Error('WebSocket did not recover after ' + wsMaxAttempts + ' attempts');
        });
      }
      return tryConnect();
    });
  }

  // ======================================================================
  // 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;
    }
  }

  function _markdownRoundTripFaithful(markdownContent) {
    if (!markdownContent || typeof markdownContent !== 'string') return true;
    var editor = wysiwygEditor;
    if (!editor || !editor._markdownToHtml || !editor._htmlToMarkdown) return true;
    var parsed = parseFrontmatter(markdownContent);
    var body = parsed.body;
    if (!body || !body.trim()) return true;
    var prev = _inMemoryRenderMode;
    _inMemoryRenderMode = true;
    try {
      var html = editor._markdownToHtml(body);
      var md2 = editor._htmlToMarkdown(html);
      var norm = function (s) {
        return (s || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '').replace(/\s+$/gm, '').replace(/\n{3,}/g, '\n\n').trim();
      };
      var n1 = norm(body);
      var n2 = norm(md2);
      var faithful = n1 === n2;
      if (!faithful) {
      }
      return faithful;
    } 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;
  var _undoViaBeforeinput = false;


  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 (/^```mermaid\s*$/i.test(first) && newLines.length > 1) return 'mermaid diagram created';
        if (/^```/.test(first) && newLines.length > 1) {
          var lang = first.replace(/^```\s*/, '').trim();
          return lang ? lang + ' code block' : 'code block';
        }
        if (/^#{1,6}\s/.test(first)) {
          var headingText = first.replace(/^#{1,6}\s+/, '').trim();
          return headingText ? '\u201C' + _truncateExcerpt(headingText, 40) + '\u201D' : 'heading';
        }
        if (/^(!{3}|\?{3}\+?)\s/.test(first)) {
          var admType = first.replace(/^(?:!{3}|\?{3}\+?)\s+/, '').split(/\s/)[0] || '';
          return admType ? admType + ' admonition' : 'admonition';
        }
        if (/^>\s/.test(first) && newLines.length > 1) return 'blockquote';
        if (/^(\s*[-*+]|\s*\d+\.)\s/.test(first) && newLines.length > 1) return 'list items';
        if (/^(---|___|\*\*\*)\s*$/.test(first)) return '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])) {
          var removedText = oldLines[0].replace(/^#{1,6}\s+/, '').trim();
          return removedText ? 'removed \u201C' + _truncateExcerpt(removedText, 30) + '\u201D' : 'removed heading';
        }
      }
      if (newLines.length > 0) {
        var excerpt = _extractExcerptFromLines(newLines);
        if (excerpt) return '\u201C' + excerpt + '\u201D';
      }
      if (singleOp.type === 'delete' && oldLines.length > 0) {
        var delExcerpt = _extractExcerptFromLines(oldLines);
        if (delExcerpt) return 'removed \u201C' + delExcerpt + '\u201D';
      }
    }
    var allNewLines = [];
    for (var j = 0; j < diff.ops.length; j++) {
      var op2 = diff.ops[j];
      var lines2 = op2.type === 'replace' ? op2.new : (op2.type === 'insert' ? op2.lines : null);
      if (lines2) allNewLines = allNewLines.concat(lines2);
    }
    if (allNewLines.length > 0) {
      var multiExcerpt = _extractExcerptFromLines(allNewLines);
      if (multiExcerpt) return '\u201C' + multiExcerpt + '\u201D';
    }
    var total = totalOld + totalNew;
    return total + ' line' + (total !== 1 ? 's' : '') + ' changed';
  }

  function _truncateExcerpt(text, maxLen) {
    if (text.length <= maxLen) return text;
    return text.substring(0, maxLen - 1) + '\u2026';
  }

  function _extractExcerptFromLines(lines) {
    for (var i = 0; i < lines.length; i++) {
      var clean = lines[i].replace(/^[\s#>*\-+`!?]+/, '').replace(/[*_~`]+/g, '').trim();
      if (clean.length > 2) return _truncateExcerpt(clean, 45);
    }
    return '';
  }

  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;

    var htmlSnapshot = null;
    if (wysiwygEditor && wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
      htmlSnapshot = wysiwygEditor.editableArea.innerHTML;
    }

    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,
      htmlSnapshot: htmlSnapshot
    };
    _historyNodes[nodeId] = node;

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

    _historyCurrentId = nodeId;
    _historyLastMd = markdown;

    _historyPrune();
    _autoSaveAndPersistHistory();
  }

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

    // Protect: root-to-current path + active redo path from every branch point
    var onPath = {};
    var id = _historyCurrentId;
    while (id !== null && _historyNodes[id]) {
      onPath[id] = true;
      id = _historyNodes[id].parentId;
    }
    // Protect the active redo path forward from current
    var fwd = _historyCurrentId;
    while (fwd !== null && _historyNodes[fwd]) {
      onPath[fwd] = true;
      fwd = _historyNodes[fwd].activeChildId || null;
    }
    // Protect every node's activeChildId chain (preserves all active branches)
    for (var ai = 0; ai < ids.length; ai++) {
      var aN = _historyNodes[ids[ai]];
      if (aN && aN.activeChildId && onPath[parseInt(ids[ai], 10)]) {
        var walk = aN.activeChildId;
        while (walk !== null && _historyNodes[walk] && !onPath[walk]) {
          onPath[walk] = true;
          walk = _historyNodes[walk].activeChildId || null;
        }
      }
    }

    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;
  }

  // --- History Mode (Layer 4) ---

  var _historyModeActive = false;
  var _historyOverlay = null;
  var _historyBranchPopup = null;
  var _historyBranchPopupTimer = null;
  var _historyBranchPopupHighlight = 0;
  var _historyBranchPopupNodeId = null;
  var _historyDagSelectedNodeId = null;
  var _historyFullsizePreview = null;
  var _historyPreviewCache = {};
  var _historyDagExpandedGroups = {};
  var _historyDagActiveBranchKey = null;
  var _historyDagVtreeSelectedBranch = {};
  var _historyDagAnimatingGroup = null;
  var _historyDagViewMode = 'detailed';

  function _formatRelativeTime(ts) {
    var diff = Date.now() - ts;
    if (diff < 60000) return 'just now';
    if (diff < 3600000) return Math.floor(diff / 60000) + 'm ago';
    if (diff < 86400000) return Math.floor(diff / 3600000) + 'h ago';
    return Math.floor(diff / 86400000) + 'd ago';
  }

  function _getSnippetForNode(node) {
    if (!node || !node.diff || !node.diff.ops || node.diff.ops.length === 0) return '';
    for (var i = 0; i < node.diff.ops.length; i++) {
      var op = node.diff.ops[i];
      var lines = op.type === 'replace' ? op.new : (op.type === 'insert' ? op.lines : null);
      if (lines && lines.length > 0) {
        var snippet = [];
        for (var k = 0; k < Math.min(lines.length, 4); k++) {
          snippet.push(lines[k]);
        }
        var text = snippet.join('\n');
        if (text.length > 120) text = text.substring(0, 117) + '...';
        return text;
      }
    }
    if (node.diff.ops.length > 0 && node.diff.ops[0].type === 'delete') {
      var oldLines = node.diff.ops[0].old;
      if (oldLines && oldLines.length > 0) {
        var delSnippet = [];
        for (var d = 0; d < Math.min(oldLines.length, 4); d++) {
          delSnippet.push(oldLines[d]);
        }
        var delText = delSnippet.join('\n');
        if (delText.length > 120) delText = delText.substring(0, 117) + '...';
        return '\u2212 ' + delText;
      }
    }
    return '';
  }

  function _stripFrontmatterForPreview(markdown) {
    if (!markdown) return '';
    var parsed = parseFrontmatter(markdown);
    return parsed.body;
  }

  function _renderMarkdownPreview(markdown) {
    var body = _stripFrontmatterForPreview(markdown);
    if (typeof marked !== 'undefined') {
      return marked.parse(body, { gfm: true, breaks: false, smartLists: true });
    }
    return '<pre>' + body.replace(/</g, '&lt;') + '</pre>';
  }

  // --- Way 1: Branch Picker Popup ---

  function _dismissHistoryBranchPopup() {
    if (_historyBranchPopupTimer) {
      clearTimeout(_historyBranchPopupTimer);
      _historyBranchPopupTimer = null;
    }
    if (_historyBranchPopup) {
      if (_historyBranchPopup._docHandler) {
        document.removeEventListener('mousedown', _historyBranchPopup._docHandler, true);
      }
      if (_historyBranchPopup.parentNode) _historyBranchPopup.parentNode.removeChild(_historyBranchPopup);
      _historyBranchPopup = null;
    }
    _historyBranchPopupNodeId = null;
    _historyBranchPopupHighlight = 0;
  }

  function _showHistoryBranchPopup(branchNodeId) {
    _dismissHistoryBranchPopup();
    var node = _historyNodes[branchNodeId];
    if (!node) return;

    var hasBranches = node.children.length >= 2;
    var hasRedo = node.children.length >= 1;

    var popup = document.createElement('div');
    popup.className = 'live-wysiwyg-history-branch-popup';
    popup.setAttribute('tabindex', '-1');

    var header = document.createElement('div');
    header.className = 'live-wysiwyg-history-branch-header';
    var headerLabel = document.createElement('span');
    headerLabel.textContent = hasBranches ? 'Redo branches' : (hasRedo ? 'Redo' : 'End of history');
    header.appendChild(headerLabel);
    popup.appendChild(header);

    var list = document.createElement('div');
    list.className = 'live-wysiwyg-history-branch-list';
    var activeIdx = 0;
    for (var i = 0; i < node.children.length; i++) {
      var childId = node.children[i];
      var child = _historyNodes[childId];
      if (!child) continue;
      if (childId === node.activeChildId) activeIdx = i;
      var item = document.createElement('div');
      item.className = 'live-wysiwyg-history-branch-item';
      item.setAttribute('data-child-id', childId);
      if (childId === node.activeChildId) item.classList.add('active');

      var summarySpan = document.createElement('span');
      summarySpan.className = 'live-wysiwyg-history-branch-summary';
      summarySpan.textContent = child.summary || 'edit';
      item.appendChild(summarySpan);

      var snippetSpan = document.createElement('span');
      snippetSpan.className = 'live-wysiwyg-history-branch-snippet';
      snippetSpan.textContent = _getSnippetForNode(child);
      item.appendChild(snippetSpan);

      var timeSpan = document.createElement('span');
      timeSpan.className = 'live-wysiwyg-history-branch-time';
      timeSpan.textContent = _formatRelativeTime(child.timestamp);
      item.appendChild(timeSpan);

      list.appendChild(item);
    }
    if (!hasRedo) {
      activeIdx = 0;
    }

    var showAllItem = document.createElement('div');
    showAllItem.className = 'live-wysiwyg-history-branch-item show-all-history';
    showAllItem.setAttribute('data-child-id', 'show-all');
    var showAllIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    showAllIcon.setAttribute('width', '14');
    showAllIcon.setAttribute('height', '14');
    showAllIcon.setAttribute('viewBox', '0 0 14 14');
    showAllIcon.style.verticalAlign = 'middle';
    showAllIcon.style.marginRight = '6px';
    showAllIcon.style.flexShrink = '0';
    var iconPath1 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    iconPath1.setAttribute('d', 'M1 5 L1 1 L5 1');
    iconPath1.setAttribute('stroke', 'currentColor');
    iconPath1.setAttribute('stroke-width', '1.5');
    iconPath1.setAttribute('fill', 'none');
    iconPath1.setAttribute('stroke-linecap', 'round');
    iconPath1.setAttribute('stroke-linejoin', 'round');
    var iconPath2 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    iconPath2.setAttribute('d', 'M13 9 L13 13 L9 13');
    iconPath2.setAttribute('stroke', 'currentColor');
    iconPath2.setAttribute('stroke-width', '1.5');
    iconPath2.setAttribute('fill', 'none');
    iconPath2.setAttribute('stroke-linecap', 'round');
    iconPath2.setAttribute('stroke-linejoin', 'round');
    var iconLine1 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    iconLine1.setAttribute('x1', '1'); iconLine1.setAttribute('y1', '1');
    iconLine1.setAttribute('x2', '7'); iconLine1.setAttribute('y2', '7');
    iconLine1.setAttribute('stroke', 'currentColor');
    iconLine1.setAttribute('stroke-width', '1.5');
    iconLine1.setAttribute('stroke-linecap', 'round');
    var iconLine2 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    iconLine2.setAttribute('x1', '13'); iconLine2.setAttribute('y1', '13');
    iconLine2.setAttribute('x2', '7'); iconLine2.setAttribute('y2', '7');
    iconLine2.setAttribute('stroke', 'currentColor');
    iconLine2.setAttribute('stroke-width', '1.5');
    iconLine2.setAttribute('stroke-linecap', 'round');
    showAllIcon.appendChild(iconPath1);
    showAllIcon.appendChild(iconPath2);
    showAllIcon.appendChild(iconLine1);
    showAllIcon.appendChild(iconLine2);
    var showAllLabel = document.createElement('span');
    showAllLabel.className = 'live-wysiwyg-history-branch-summary';
    showAllLabel.appendChild(showAllIcon);
    showAllLabel.appendChild(document.createTextNode('Show All Redo History'));
    showAllItem.appendChild(showAllLabel);
    list.appendChild(showAllItem);

    popup.appendChild(list);

    _historyBranchPopupNodeId = branchNodeId;
    _historyBranchPopupHighlight = activeIdx;

    var caretRect = null;
    var sel = window.getSelection();
    if (sel && sel.rangeCount > 0) {
      var rng = sel.getRangeAt(0);
      caretRect = rng.getBoundingClientRect();
      if (caretRect.width === 0 && caretRect.height === 0) caretRect = null;
    }
    var popupW = 380;
    var popupH = 260;
    var posLeft, posTop;
    if (caretRect) {
      posLeft = caretRect.right + 12;
      posTop = caretRect.top - 20;
    } else {
      var editorRect = (wysiwygEditor && wysiwygEditor.editableArea)
        ? wysiwygEditor.editableArea.getBoundingClientRect()
        : { top: 100, right: window.innerWidth - 20 };
      posLeft = editorRect.right - popupW;
      posTop = editorRect.top;
    }
    if (posLeft + popupW > window.innerWidth - 8) posLeft = window.innerWidth - popupW - 8;
    if (posLeft < 8) posLeft = 8;
    if (posTop + popupH > window.innerHeight - 8) posTop = window.innerHeight - popupH - 8;
    if (posTop < 8) posTop = 8;
    popup.style.position = 'fixed';
    popup.style.left = posLeft + 'px';
    popup.style.top = posTop + 'px';
    popup.style.zIndex = '99999';

    var appendTarget = _focusOverlay || document.body;
    appendTarget.appendChild(popup);
    _historyBranchPopup = popup;

    _updateBranchPopupHighlight();

    popup.addEventListener('keydown', function (e) {
      if ((e.key === 'z' || e.key === 'y') && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        _dismissHistoryBranchPopup();
        if (e.key === 'y' || e.shiftKey) {
          _contentRedo();
        } else {
          _contentUndo();
        }
        return;
      }
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        var items = list.querySelectorAll('.live-wysiwyg-history-branch-item');
        _historyBranchPopupHighlight = Math.min(_historyBranchPopupHighlight + 1, items.length - 1);
        _updateBranchPopupHighlight();
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        _historyBranchPopupHighlight = Math.max(_historyBranchPopupHighlight - 1, 0);
        _updateBranchPopupHighlight();
      } else if (e.key === 'Tab' || e.key === 'Enter') {
        e.preventDefault();
        _confirmBranchPopupSelection();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        _dismissHistoryBranchPopup();
      }
    });

    list.addEventListener('click', function (e) {
      var item = e.target.closest('.live-wysiwyg-history-branch-item');
      if (!item) return;
      var items = list.querySelectorAll('.live-wysiwyg-history-branch-item');
      for (var j = 0; j < items.length; j++) {
        if (items[j] === item) { _historyBranchPopupHighlight = j; break; }
      }
      _updateBranchPopupHighlight();
      _confirmBranchPopupSelection();
    });

    var docHandler = function (ev) {
      if (popup.contains(ev.target)) return;
      _dismissHistoryBranchPopup();
    };
    popup._docHandler = docHandler;
    document.addEventListener('mousedown', docHandler, true);

    popup.focus();
  }

  function _updateBranchPopupHighlight() {
    if (!_historyBranchPopup) return;
    var items = _historyBranchPopup.querySelectorAll('.live-wysiwyg-history-branch-item');
    for (var i = 0; i < items.length; i++) {
      items[i].classList.toggle('highlighted', i === _historyBranchPopupHighlight);
    }
  }

  function _resetBranchPopupTimer() {
    // No-op: popup persists until typing or explicit dismiss
  }

  function _confirmBranchPopupSelection() {
    if (!_historyBranchPopup || _historyBranchPopupNodeId === null) return;
    var items = _historyBranchPopup.querySelectorAll('.live-wysiwyg-history-branch-item');
    var selectedItem = items[_historyBranchPopupHighlight];
    if (!selectedItem) { _dismissHistoryBranchPopup(); return; }
    if (selectedItem.classList.contains('show-all-history')) {
      _dismissHistoryBranchPopup();
      _enterHistoryMode();
      return;
    }
    var node = _historyNodes[_historyBranchPopupNodeId];
    if (!node) { _dismissHistoryBranchPopup(); return; }
    var selectedChildId = parseInt(selectedItem.getAttribute('data-child-id'), 10);
    if (selectedChildId === node.activeChildId) {
      _dismissHistoryBranchPopup();
      return;
    }
    _contentUndo();
    _switchHistoryBranch(_historyBranchPopupNodeId, selectedChildId);
    _dismissHistoryBranchPopup();
    _contentRedo();
  }

  // --- Way 2: History Mode — Full-Screen Document History Overlay (Layer 4) ---

  function _enterHistoryMode() {
    if (_historyModeActive) return;
    if (_mermaidModeActive) return;
    _historyModeActive = true;
    _historyPreviewCache = {};
    _historyDagSelectedNodeId = null;
    _historyDagExpandedGroups = {};
    _historyDagActiveBranchKey = null;
    _historyDagVtreeSelectedBranch = {};
    _historyDagAnimatingGroup = null;
    _historyDagViewMode = 'detailed';
    _buildHistoryOverlay();
  }

  function _exitHistoryMode() {
    if (!_historyModeActive) return;
    _historyModeActive = false;
    _dismissHistoryFullsizePreview();
    if (_historyOverlay && _historyOverlay.parentNode) {
      _historyOverlay.parentNode.removeChild(_historyOverlay);
    }
    _historyOverlay = null;
    _historyDagSelectedNodeId = null;
    _historyPreviewCache = {};
  }

  function _buildHistoryOverlay() {
    if (_historyOverlay) _exitHistoryMode();

    var overlay = document.createElement('div');
    overlay.className = 'live-wysiwyg-history-overlay';
    overlay.setAttribute('tabindex', '-1');

    var backdrop = document.createElement('div');
    backdrop.className = 'live-wysiwyg-history-backdrop';
    backdrop.addEventListener('click', function () { _exitHistoryMode(); });
    overlay.appendChild(backdrop);

    var modal = document.createElement('div');
    modal.className = 'live-wysiwyg-history-modal';

    var modalHeader = document.createElement('div');
    modalHeader.className = 'live-wysiwyg-history-modal-header';
    var title = document.createElement('h2');
    title.textContent = 'Document History';
    modalHeader.appendChild(title);
    var toggleBtn = document.createElement('button');
    toggleBtn.className = 'live-wysiwyg-history-toggle-view-btn';
    toggleBtn.textContent = _historyDagViewMode === 'organic' ? 'Detailed View' : 'Tree View';
    toggleBtn.title = 'Switch between detailed and compact tree view';
    toggleBtn.addEventListener('click', function () {
      _historyDagViewMode = _historyDagViewMode === 'organic' ? 'detailed' : 'organic';
      toggleBtn.textContent = _historyDagViewMode === 'organic' ? 'Detailed View' : 'Tree View';
      var dagC = modal.querySelector('.live-wysiwyg-history-dag-container');
      if (dagC) {
        dagC.classList.add('live-wysiwyg-dag-transitioning');
        _renderDag(dagC);
        setTimeout(function () { dagC.classList.remove('live-wysiwyg-dag-transitioning'); }, 350);
      }
    });
    modalHeader.appendChild(toggleBtn);

    var closeBtn = document.createElement('button');
    closeBtn.className = 'live-wysiwyg-history-close-btn';
    closeBtn.textContent = '\u00D7';
    closeBtn.title = 'Close';
    closeBtn.addEventListener('click', function () { _exitHistoryMode(); });
    modalHeader.appendChild(closeBtn);
    modal.appendChild(modalHeader);

    var body = document.createElement('div');
    body.className = 'live-wysiwyg-history-modal-body';

    var dagContainer = document.createElement('div');
    dagContainer.className = 'live-wysiwyg-history-dag-container';
    body.appendChild(dagContainer);

    var previewPanel = document.createElement('div');
    previewPanel.className = 'live-wysiwyg-history-preview-panel';
    body.appendChild(previewPanel);

    modal.appendChild(body);
    overlay.appendChild(modal);

    var appendTarget = _focusOverlay || document.body;
    appendTarget.appendChild(overlay);
    _historyOverlay = overlay;

    _renderDag(dagContainer);
    _attachHistoryOverlayKeyboard(overlay);
    overlay.focus();
  }

  // --- Container Detection & Grouping ---

  function _detectEditContainer(lines, diff) {
    if (!lines || !diff || !diff.ops || diff.ops.length === 0) return [];
    var editStart = Infinity, editEnd = -1;
    for (var i = 0; i < diff.ops.length; i++) {
      var op = diff.ops[i];
      var opLine = op.type === 'insert' ? (op.afterLine != null ? op.afterLine : 0) : (op.line || 0);
      if (opLine < editStart) editStart = opLine;
      var opEnd = opLine;
      if (op.type === 'replace') opEnd = opLine + Math.max(op.count, op['new'].length) - 1;
      else if (op.type === 'insert') opEnd = opLine + op.lines.length - 1;
      else if (op.type === 'delete') opEnd = opLine + op.count - 1;
      if (opEnd > editEnd) editEnd = opEnd;
    }
    if (editStart === Infinity) return [];

    var containers = [];
    var inFence = false, fenceStart = -1, fenceLang = '';
    var listStack = [];
    var admonitionStack = [];
    var blockquoteStart = -1, blockquoteActive = false;

    for (var L = 0; L < lines.length; L++) {
      var ln = lines[L];
      if (/^(`{3,}|~{3,})/.test(ln) && !inFence) {
        inFence = true;
        fenceStart = L;
        fenceLang = ln.replace(/^(`{3,}|~{3,})\s*/, '').split(/\s/)[0] || '';
        continue;
      }
      if (inFence && /^(`{3,}|~{3,})\s*$/.test(ln)) {
        if (editStart <= L && editEnd >= fenceStart) {
          var label = fenceLang === 'mermaid' ? 'mermaid diagram'
            : fenceLang ? fenceLang + ' code block' : 'code block';
          containers.push({ type: 'code', lang: fenceLang, label: label, startLine: fenceStart, endLine: L });
        }
        inFence = false;
        fenceStart = -1;
        fenceLang = '';
        continue;
      }
      if (inFence) continue;

      if (/^(!{3}|\?{3}\+?)\s/.test(ln)) {
        var admType = ln.replace(/^(?:!{3}|\?{3}\+?)\s+/, '').split(/\s/)[0] || 'note';
        var admEnd = L;
        for (var aL = L + 1; aL < lines.length; aL++) {
          if (/^\S/.test(lines[aL]) && !/^\s/.test(lines[aL])) break;
          if (lines[aL].trim() === '' && aL + 1 < lines.length && /^\S/.test(lines[aL + 1]) && !/^\s/.test(lines[aL + 1])) {
            admEnd = aL;
            break;
          }
          admEnd = aL;
        }
        if (editStart <= admEnd && editEnd >= L) {
          containers.push({ type: 'admonition', label: admType + ' admonition', startLine: L, endLine: admEnd });
        }
      }

      if (/^>\s/.test(ln)) {
        if (!blockquoteActive) {
          blockquoteStart = L;
          blockquoteActive = true;
        }
      } else if (blockquoteActive) {
        var bqEnd = L - 1;
        if (editStart <= bqEnd && editEnd >= blockquoteStart) {
          containers.push({ type: 'blockquote', label: 'blockquote', startLine: blockquoteStart, endLine: bqEnd });
        }
        blockquoteActive = false;
      }

      if (/^(\s*[-*+]|\s*\d+\.)\s/.test(ln)) {
        if (listStack.length === 0 || L > listStack[listStack.length - 1].end + 1) {
          listStack.push({ start: L, end: L });
        } else {
          listStack[listStack.length - 1].end = L;
        }
      } else if (listStack.length > 0 && ln.trim() !== '') {
        if (!/^\s/.test(ln)) {
          var lst = listStack[listStack.length - 1];
          if (editStart <= lst.end && editEnd >= lst.start) {
            containers.push({ type: 'list', label: 'list', startLine: lst.start, endLine: lst.end });
          }
          listStack = [];
        } else if (listStack.length > 0) {
          listStack[listStack.length - 1].end = L;
        }
      }
    }

    if (blockquoteActive) {
      var finalBqEnd = lines.length - 1;
      if (editStart <= finalBqEnd && editEnd >= blockquoteStart) {
        containers.push({ type: 'blockquote', label: 'blockquote', startLine: blockquoteStart, endLine: finalBqEnd });
      }
    }
    if (inFence) {
      if (editStart <= lines.length - 1 && editEnd >= fenceStart) {
        var pendingLabel = fenceLang === 'mermaid' ? 'mermaid diagram'
          : fenceLang ? fenceLang + ' code block' : 'code block';
        containers.push({ type: 'code', lang: fenceLang, label: pendingLabel, startLine: fenceStart, endLine: lines.length - 1 });
      }
    }
    for (var ls = 0; ls < listStack.length; ls++) {
      var lItem = listStack[ls];
      if (editStart <= lItem.end && editEnd >= lItem.start) {
        containers.push({ type: 'list', label: 'list', startLine: lItem.start, endLine: lItem.end });
      }
    }

    containers.sort(function (a, b) { return (a.startLine - b.startLine) || (b.endLine - a.endLine); });
    return containers;
  }

  function _computeContainerGroups(pathNodeIds) {
    if (!pathNodeIds || pathNodeIds.length === 0) return [];
    var result = [];
    var currentLines = _historyRootMd ? _historyRootMd.split('\n') : [];

    var pending = null;

    for (var i = 0; i < pathNodeIds.length; i++) {
      var nid = pathNodeIds[i];
      var node = _historyNodes[nid];
      if (!node) {
        if (pending) { result.push(pending); pending = null; }
        result.push({ type: null, label: null, nodeIds: [nid] });
        continue;
      }
      if (node.parentId === null) {
        if (pending) { result.push(pending); pending = null; }
        result.push({ type: null, label: null, nodeIds: [nid] });
        if (node.diff) currentLines = _applyDiff(currentLines, node.diff);
        continue;
      }

      var containers = [];
      if (node.diff) {
        containers = _detectEditContainer(currentLines, node.diff);
      }

      var innermost = containers.length > 0 ? containers[containers.length - 1] : null;
      var containerKey = innermost ? (innermost.type + ':' + innermost.startLine) : null;

      var keyMatch = false;
      if (pending && containerKey && pending.type === innermost.type) {
        var prevStart = parseInt(pending.key.split(':')[1], 10);
        keyMatch = Math.abs(innermost.startLine - prevStart) <= 5;
      }

      if (pending && keyMatch) {
        pending.nodeIds.push(nid);
        pending.containers = containers;
        pending.key = containerKey;
      } else {
        if (pending) result.push(pending);
        if (containerKey) {
          pending = {
            type: innermost.type,
            label: innermost.label,
            key: containerKey,
            nodeIds: [nid],
            containers: containers
          };
        } else {
          pending = null;
          result.push({ type: null, label: null, nodeIds: [nid] });
        }
      }

      if (node.diff) currentLines = _applyDiff(currentLines, node.diff);
    }
    if (pending) result.push(pending);

    return result;
  }

  // --- DAG SVG Helpers ---

  function _createCrumpleSvg() {
    var ns = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(ns, 'svg');
    svg.setAttribute('width', '40');
    svg.setAttribute('height', '14');
    svg.setAttribute('viewBox', '0 0 40 14');
    svg.setAttribute('class', 'live-wysiwyg-dag-crumple-svg');
    var p = document.createElementNS(ns, 'path');
    p.setAttribute('d', 'M1 7 L6 2 L12 12 L18 2 L24 12 L30 2 L35 7 L39 7');
    p.setAttribute('stroke', 'currentColor');
    p.setAttribute('stroke-width', '2');
    p.setAttribute('stroke-linecap', 'round');
    p.setAttribute('stroke-linejoin', 'round');
    p.setAttribute('fill', 'none');
    svg.appendChild(p);
    return svg;
  }

  function _createVtreeForkSvg() {
    var ns = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(ns, 'svg');
    svg.setAttribute('width', '22');
    svg.setAttribute('height', '20');
    svg.setAttribute('viewBox', '0 0 22 20');
    svg.setAttribute('class', 'live-wysiwyg-dag-vtree-svg');
    var makeArrow = function (d) {
      var p = document.createElementNS(ns, 'path');
      p.setAttribute('d', d);
      p.setAttribute('stroke', 'currentColor');
      p.setAttribute('stroke-width', '1.5');
      p.setAttribute('stroke-linecap', 'round');
      p.setAttribute('stroke-dasharray', '3 2');
      p.setAttribute('fill', 'none');
      return p;
    };
    svg.appendChild(makeArrow('M1 10 L18 10'));
    svg.appendChild(makeArrow('M1 10 L14 3'));
    svg.appendChild(makeArrow('M1 10 L14 17'));
    var makeHead = function (x, y, angle) {
      var head = document.createElementNS(ns, 'path');
      var rad = angle * Math.PI / 180;
      var dx1 = -5 * Math.cos(rad) - 3 * Math.sin(rad);
      var dy1 = -5 * Math.sin(rad) + 3 * Math.cos(rad);
      var dx2 = -5 * Math.cos(rad) + 3 * Math.sin(rad);
      var dy2 = -5 * Math.sin(rad) - 3 * Math.cos(rad);
      head.setAttribute('d', 'M' + (x + dx1) + ' ' + (y + dy1) + ' L' + x + ' ' + y + ' L' + (x + dx2) + ' ' + (y + dy2));
      head.setAttribute('stroke', 'currentColor');
      head.setAttribute('stroke-width', '1.5');
      head.setAttribute('stroke-linecap', 'round');
      head.setAttribute('stroke-linejoin', 'round');
      head.setAttribute('fill', 'none');
      return head;
    };
    svg.appendChild(makeHead(18, 10, 0));
    svg.appendChild(makeHead(14, 3, -28));
    svg.appendChild(makeHead(14, 17, 28));
    return svg;
  }

  // --- DAG Layout Algorithm ---

  function _countSubtreeNodes(nodeId) {
    var node = _historyNodes[nodeId];
    if (!node) return 0;
    var count = 1;
    for (var i = 0; i < node.children.length; i++) {
      count += _countSubtreeNodes(node.children[i]);
    }
    return count;
  }

  function _computeDagLayout() {
    var rootId = null;
    var ids = Object.keys(_historyNodes);
    for (var i = 0; i < ids.length; i++) {
      var n = _historyNodes[ids[i]];
      if (n.parentId === null) { rootId = n.id; break; }
    }
    if (rootId === null) return { nodes: [], edges: [], width: 0, height: 0, groups: [] };

    var NODE_W = 300;
    var NODE_H = 60;
    var CRUMPLE_H = 40;
    var H_GAP = 28;
    var V_GAP = 20;

    // === PHASE 1: Full tree layout (bottom-to-top) ===

    // 1a. Build active path: root → current → latest active leaf
    // First, find path from root to _historyCurrentId
    var rootToCurrent = [];
    var walkBack = _historyCurrentId;
    while (walkBack !== null && _historyNodes[walkBack]) {
      rootToCurrent.push(walkBack);
      walkBack = _historyNodes[walkBack].parentId;
    }
    rootToCurrent.reverse();

    // Then extend forward from current via activeChildId
    var activePath = {};
    var activePathList = rootToCurrent.slice();
    for (var rtc = 0; rtc < rootToCurrent.length; rtc++) {
      activePath[rootToCurrent[rtc]] = true;
    }
    var fwdId = _historyCurrentId;
    if (_historyNodes[fwdId]) {
      fwdId = _historyNodes[fwdId].activeChildId || null;
    }
    while (fwdId !== null && _historyNodes[fwdId]) {
      if (!activePath[fwdId]) {
        activePath[fwdId] = true;
        activePathList.push(fwdId);
      }
      fwdId = _historyNodes[fwdId].activeChildId || null;
    }

    // 1b. Assign rows to active path: root=row 0 (bottom), latest leaf=highest row (top)
    var activeLen = activePathList.length;
    var fullPositions = {};
    for (var ap = 0; ap < activeLen; ap++) {
      fullPositions[activePathList[ap]] = { col: 0, row: ap };
    }

    // 1c. Lay out all branch subtrees vertically
    var maxCol = { val: 0 };
    var colOccupied = {};
    for (var apb = 0; apb < activeLen; apb++) {
      var bpNode = _historyNodes[activePathList[apb]];
      if (!bpNode) continue;
      var nonActiveKids = [];
      for (var bc = 0; bc < bpNode.children.length; bc++) {
        if (!activePath[bpNode.children[bc]]) nonActiveKids.push(bpNode.children[bc]);
      }
      if (nonActiveKids.length === 0) continue;
      var forkRow = fullPositions[activePathList[apb]].row;
      for (var nk = 0; nk < nonActiveKids.length; nk++) {
        _layoutBranchVertical(nonActiveKids[nk], 1, forkRow, fullPositions, maxCol, colOccupied);
      }
    }

    // === PHASE 2: Crumple zones (overlay on full tree) ===

    var groups = _computeContainerGroups(activePathList);
    var hiddenByZone = {};
    var crumpleZones = [];
    for (var gi = 0; gi < groups.length; gi++) {
      var grp = groups[gi];
      if (!grp.type || grp.nodeIds.length < 2) continue;
      var groupKey = 'g-' + grp.nodeIds[0];
      var groupExpanded = !!_historyDagExpandedGroups[groupKey];
      if (!groupExpanded) {
        crumpleZones.push({
          key: groupKey, type: grp.type, label: grp.label,
          nodeIds: grp.nodeIds, repId: grp.nodeIds[0]
        });
        for (var gh = 1; gh < grp.nodeIds.length; gh++) {
          hiddenByZone[grp.nodeIds[gh]] = groupKey;
        }
      }
    }

    // Build branch metadata for collapsed branch display
    var branchMeta = {};
    for (var apbm = 0; apbm < activeLen; apbm++) {
      var bmNode = _historyNodes[activePathList[apbm]];
      if (!bmNode) continue;
      for (var bmc = 0; bmc < bmNode.children.length; bmc++) {
        var bmChildId = bmNode.children[bmc];
        if (!activePath[bmChildId]) {
          branchMeta[activePathList[apbm] + '-' + bmChildId] = {
            parentId: activePathList[apbm],
            childId: bmChildId,
            subtreeCount: _countSubtreeNodes(bmChildId)
          };
        }
      }
    }

    // Build synthetic nodes for collapsed branches
    var syntheticId = -100;
    var syntheticNodes = {};
    var branchPoints = [];

    for (var apbp = 0; apbp < activeLen; apbp++) {
      var bpNd = _historyNodes[activePathList[apbp]];
      if (!bpNd || bpNd.children.length <= 1) continue;
      var nacList = [];
      for (var nac = 0; nac < bpNd.children.length; nac++) {
        if (!activePath[bpNd.children[nac]]) nacList.push(bpNd.children[nac]);
      }
      if (nacList.length === 0) continue;
      var bpKey = 'bp-' + activePathList[apbp];
      var parentRow = fullPositions[activePathList[apbp]].row;
      branchPoints.push({
        parentId: activePathList[apbp], parentRow: parentRow,
        children: nacList, isVtree: nacList.length >= 2, bpKey: bpKey
      });
    }

    // Determine visible rows for compact rendering
    var visibleRows = {};
    for (var vap = 0; vap < activeLen; vap++) {
      var vapId = activePathList[vap];
      if (!hiddenByZone[vapId]) {
        visibleRows[fullPositions[vapId].row] = true;
      }
    }
    for (var vz = 0; vz < crumpleZones.length; vz++) {
      visibleRows[fullPositions[crumpleZones[vz].repId].row] = true;
    }

    // For expanded branches, mark their rows visible
    for (var bpi = 0; bpi < branchPoints.length; bpi++) {
      var bpInfo = branchPoints[bpi];
      var isExpanded = false;
      if (bpInfo.isVtree) {
        if (_historyDagActiveBranchKey === bpInfo.bpKey) isExpanded = true;
      } else {
        var sKey = bpInfo.parentId + '-' + bpInfo.children[0];
        if (_historyDagActiveBranchKey === sKey) isExpanded = true;
      }
      if (isExpanded) {
        var expandChild = bpInfo.isVtree
          ? (_historyDagVtreeSelectedBranch[bpInfo.bpKey] || null)
          : bpInfo.children[0];
        if (expandChild && fullPositions[expandChild]) {
          var stack = [expandChild];
          while (stack.length > 0) {
            var sid = stack.pop();
            if (fullPositions[sid]) visibleRows[fullPositions[sid].row] = true;
            var snd = _historyNodes[sid];
            if (snd) {
              for (var sc = 0; sc < snd.children.length; sc++) stack.push(snd.children[sc]);
            }
          }
        }
      }
    }

    // Also mark synthetic node rows and vtree option rows
    for (var bpi2 = 0; bpi2 < branchPoints.length; bpi2++) {
      var bp2 = branchPoints[bpi2];
      visibleRows[bp2.parentRow] = true;
      if (bp2.isVtree && _historyDagActiveBranchKey === bp2.bpKey && !_historyDagVtreeSelectedBranch[bp2.bpKey]) {
        for (var vopt = 0; vopt < bp2.children.length; vopt++) {
          visibleRows[bp2.parentRow + vopt + 1] = true;
        }
      }
    }

    // Compact row mapping: map full rows to compact sequential rows, skipping hidden
    var allRows = Object.keys(visibleRows).map(Number).sort(function (a, b) { return a - b; });
    var compactMap = {};
    for (var cr = 0; cr < allRows.length; cr++) {
      compactMap[allRows[cr]] = cr;
    }
    var totalCompactRows = allRows.length;

    // Build synthetic positioned nodes
    for (var bps = 0; bps < branchPoints.length; bps++) {
      var bpsInfo = branchPoints[bps];
      var synRow2 = bpsInfo.parentRow;
      if (bpsInfo.isVtree) {
        var vtreeId = syntheticId--;
        syntheticNodes[vtreeId] = {
          isVtreeFork: true,
          vtreeParentId: bpsInfo.parentId,
          vtreeChildIds: bpsInfo.children,
          vtreeBpKey: bpsInfo.bpKey
        };
        fullPositions[vtreeId] = { col: 1, row: synRow2 };
        if (1 > maxCol.val) maxCol.val = 1;

        var selectedChildId = _historyDagVtreeSelectedBranch[bpsInfo.bpKey] || null;
        var isThisActive = (_historyDagActiveBranchKey === bpsInfo.bpKey);
        if (isThisActive && !selectedChildId) {
          for (var vci = 0; vci < bpsInfo.children.length; vci++) {
            var pickerId = syntheticId--;
            syntheticNodes[pickerId] = {
              isVtreeOption: true,
              vtreeBpKey: bpsInfo.bpKey,
              optionChildId: bpsInfo.children[vci],
              optionSummary: _historyNodes[bpsInfo.children[vci]]
                ? (_historyNodes[bpsInfo.children[vci]].summary || 'edit')
                : 'edit',
              optionCount: branchMeta[bpsInfo.parentId + '-' + bpsInfo.children[vci]]
                ? branchMeta[bpsInfo.parentId + '-' + bpsInfo.children[vci]].subtreeCount
                : 1
            };
            fullPositions[pickerId] = { col: 2, row: synRow2 + vci + 1 };
            if (2 > maxCol.val) maxCol.val = 2;
          }
        }
      } else {
        var brChild = bpsInfo.children[0];
        var singleKey = bpsInfo.parentId + '-' + brChild;
        var singleId = syntheticId--;
        syntheticNodes[singleId] = {
          isBranchCrumple: true,
          branchKey: singleKey,
          branchChildId: brChild,
          branchCount: branchMeta[singleKey] ? branchMeta[singleKey].subtreeCount : 1
        };
        fullPositions[singleId] = { col: 1, row: synRow2 };
        if (1 > maxCol.val) maxCol.val = 1;
      }
    }

    // === PHASE 3: Build layout nodes and edges ===

    var layoutNodes = [];
    var edges = [];
    var posKeys = Object.keys(fullPositions);

    for (var p = 0; p < posKeys.length; p++) {
      var lnid = parseInt(posKeys[p], 10);
      var pos = fullPositions[lnid];
      var nd = _historyNodes[lnid];
      var syn = syntheticNodes[lnid] || null;
      var isOnActive = !!activePath[lnid];
      var isHidden = !!hiddenByZone[lnid];

      // Check if this branch node is in an expanded branch
      var isBranchNodeVisible = false;
      if (!isOnActive && nd && !syn) {
        for (var ebp = 0; ebp < branchPoints.length; ebp++) {
          var ebInfo = branchPoints[ebp];
          var ebExpanded = false;
          var ebChildRoot = null;
          if (ebInfo.isVtree) {
            if (_historyDagActiveBranchKey === ebInfo.bpKey) {
              ebChildRoot = _historyDagVtreeSelectedBranch[ebInfo.bpKey] || null;
              ebExpanded = !!ebChildRoot;
            }
          } else {
            var ebKey = ebInfo.parentId + '-' + ebInfo.children[0];
            if (_historyDagActiveBranchKey === ebKey) {
              ebChildRoot = ebInfo.children[0];
              ebExpanded = true;
            }
          }
          if (ebExpanded && ebChildRoot) {
            var checkStack = [ebChildRoot];
            while (checkStack.length > 0) {
              var checkId = checkStack.pop();
              if (checkId === lnid) { isBranchNodeVisible = true; break; }
              var checkNd = _historyNodes[checkId];
              if (checkNd) {
                for (var csc = 0; csc < checkNd.children.length; csc++) checkStack.push(checkNd.children[csc]);
              }
            }
            if (isBranchNodeVisible) break;
          }
        }
      }

      var skipRender = isHidden || (!isOnActive && !syn && !isBranchNodeVisible);
      if (skipRender && !syn) continue;

      var compactRow = compactMap[pos.row];
      if (compactRow === undefined) compactRow = pos.row;
      var displayRow = totalCompactRows - 1 - compactRow;

      var isCrumpleNode = false;
      var crInfo = null;
      for (var czi = 0; czi < crumpleZones.length; czi++) {
        if (crumpleZones[czi].repId === lnid) {
          isCrumpleNode = true;
          crInfo = crumpleZones[czi];
          break;
        }
      }

      var nodeH = (isCrumpleNode || (syn && (syn.isBranchCrumple || syn.isVtreeFork || syn.isVtreeOption))) ? CRUMPLE_H : NODE_H;

      layoutNodes.push({
        id: lnid,
        x: pos.col * (NODE_W + H_GAP) + NODE_W / 2,
        y: displayRow * (NODE_H + V_GAP) + NODE_H / 2,
        row: pos.row,
        displayRow: displayRow,
        col: pos.col,
        onActivePath: isOnActive,
        isCurrent: lnid === _historyCurrentId,
        isBranch: (nd && nd.children.length > 1),
        isCrumple: isCrumpleNode,
        crumpleKey: crInfo ? crInfo.key : null,
        crumpleType: crInfo ? crInfo.type : null,
        crumpleLabel: crInfo ? crInfo.label : null,
        crumpleCount: crInfo ? crInfo.nodeIds.length : 0,
        crumpleNodeIds: crInfo ? crInfo.nodeIds : null,
        isVtreeFork: syn ? !!syn.isVtreeFork : false,
        vtreeParentId: syn ? syn.vtreeParentId || null : null,
        vtreeChildIds: syn ? syn.vtreeChildIds || null : null,
        vtreeBpKey: syn ? syn.vtreeBpKey || null : null,
        isVtreeOption: syn ? !!syn.isVtreeOption : false,
        optionChildId: syn ? syn.optionChildId || null : null,
        optionSummary: syn ? syn.optionSummary || null : null,
        optionCount: syn ? syn.optionCount || 0 : 0,
        isBranchCrumple: syn ? !!syn.isBranchCrumple : false,
        branchKey: syn ? syn.branchKey || null : null,
        branchChildId: syn ? syn.branchChildId || null : null,
        branchCount: syn ? syn.branchCount || 0 : 0,
        isSynthetic: !!syn
      });
    }

    layoutNodes.sort(function (a, b) { return a.displayRow - b.displayRow; });

    // Proper Y positioning with row height awareness
    var rowMaxH = {};
    for (var rhi = 0; rhi < layoutNodes.length; rhi++) {
      var rhLn = layoutNodes[rhi];
      var rhH = (rhLn.isCrumple || rhLn.isBranchCrumple || rhLn.isVtreeFork || rhLn.isVtreeOption) ? CRUMPLE_H : NODE_H;
      if (rowMaxH[rhLn.displayRow] === undefined || rhH > rowMaxH[rhLn.displayRow]) {
        rowMaxH[rhLn.displayRow] = rhH;
      }
    }
    var sortedDisplayRows = Object.keys(rowMaxH).map(Number).sort(function (a, b) { return a - b; });
    var yAccum = 0;
    var rowYMap = {};
    for (var sri = 0; sri < sortedDisplayRows.length; sri++) {
      var rNum = sortedDisplayRows[sri];
      var rH = rowMaxH[rNum];
      if (sri > 0) yAccum += V_GAP;
      yAccum += rH / 2;
      rowYMap[rNum] = yAccum;
      yAccum += rH / 2;
    }
    for (var yi = 0; yi < layoutNodes.length; yi++) {
      var lnY = layoutNodes[yi];
      lnY.y = rowYMap[lnY.displayRow] !== undefined ? rowYMap[lnY.displayRow] : lnY.y;
    }

    // Build lookup for edge drawing
    var lnById = {};
    for (var lni = 0; lni < layoutNodes.length; lni++) {
      lnById[layoutNodes[lni].id] = layoutNodes[lni];
    }

    // Draw edges between visible parent-child pairs (children are above parents)
    for (var ei = 0; ei < layoutNodes.length; ei++) {
      var eln = layoutNodes[ei];
      var eNd = _historyNodes[eln.id];
      if (!eNd) continue;
      for (var eci = 0; eci < eNd.children.length; eci++) {
        var childLn = lnById[eNd.children[eci]];
        if (!childLn) continue;
        var yOff1 = (eln.isCrumple || eln.isBranchCrumple) ? 14 : 18;
        var yOff2 = (childLn.isCrumple || childLn.isBranchCrumple) ? 14 : 18;
        edges.push({
          x1: eln.x, y1: eln.y - yOff1,
          x2: childLn.x, y2: childLn.y + yOff2,
          active: eln.onActivePath && childLn.onActivePath,
          collapsed: false
        });
      }
    }

    // Edges from synthetic nodes (upward: synthetic → options/branch children above)
    for (var sei = 0; sei < layoutNodes.length; sei++) {
      var seln = layoutNodes[sei];
      if (seln.isVtreeFork) {
        for (var voi = 0; voi < layoutNodes.length; voi++) {
          var voLn = layoutNodes[voi];
          if (voLn.isVtreeOption && voLn.vtreeBpKey === seln.vtreeBpKey) {
            edges.push({ x1: seln.x, y1: seln.y - 14, x2: voLn.x, y2: voLn.y + 14, active: false, collapsed: false });
          }
        }
        var vtreeSelChild = _historyDagVtreeSelectedBranch[seln.vtreeBpKey];
        if (vtreeSelChild && lnById[vtreeSelChild]) {
          var selLn = lnById[vtreeSelChild];
          edges.push({ x1: seln.x, y1: seln.y - 14, x2: selLn.x, y2: selLn.y + 18, active: false, collapsed: false });
        }
      }
      if (seln.isBranchCrumple && _historyDagActiveBranchKey === seln.branchKey) {
        var brFirstLn = lnById[seln.branchChildId];
        if (brFirstLn) {
          edges.push({ x1: seln.x, y1: seln.y - 14, x2: brFirstLn.x, y2: brFirstLn.y + 18, active: false, collapsed: false });
        }
      }
    }

    // Edges from active-path fork points to synthetic branch entries
    for (var bpe = 0; bpe < branchPoints.length; bpe++) {
      var bpeInfo = branchPoints[bpe];
      var parentLn = lnById[bpeInfo.parentId];
      if (!parentLn) {
        for (var czl = 0; czl < crumpleZones.length; czl++) {
          for (var czn = 0; czn < crumpleZones[czl].nodeIds.length; czn++) {
            if (crumpleZones[czl].nodeIds[czn] === bpeInfo.parentId) {
              parentLn = lnById[crumpleZones[czl].repId];
              break;
            }
          }
          if (parentLn) break;
        }
      }
      if (!parentLn) continue;
      var entryLn = null;
      for (var eli2 = 0; eli2 < layoutNodes.length; eli2++) {
        var cand = layoutNodes[eli2];
        if (bpeInfo.isVtree && cand.isVtreeFork && cand.vtreeBpKey === bpeInfo.bpKey) { entryLn = cand; break; }
        if (!bpeInfo.isVtree && cand.isBranchCrumple && cand.branchKey === (bpeInfo.parentId + '-' + bpeInfo.children[0])) { entryLn = cand; break; }
      }
      if (entryLn) {
        edges.push({ x1: parentLn.x, y1: parentLn.y, x2: entryLn.x, y2: entryLn.y, active: false, collapsed: false });
      }
    }

    // Active-path edge continuity through crumple zones
    var visibleApIds = [];
    for (var vapi = 0; vapi < activeLen; vapi++) {
      if (lnById[activePathList[vapi]]) visibleApIds.push(activePathList[vapi]);
    }
    for (var vapei = 0; vapei < visibleApIds.length - 1; vapei++) {
      var vapFrom = visibleApIds[vapei];
      var vapTo = visibleApIds[vapei + 1];
      var vapNd = _historyNodes[vapFrom];
      var isDirect = false;
      if (vapNd) {
        for (var vdc = 0; vdc < vapNd.children.length; vdc++) {
          if (vapNd.children[vdc] === vapTo) { isDirect = true; break; }
        }
      }
      if (isDirect) continue;
      var fLn = lnById[vapFrom];
      var tLn = lnById[vapTo];
      if (fLn && tLn) {
        var fOff = (fLn.isCrumple || fLn.isBranchCrumple) ? 14 : 18;
        var tOff = (tLn.isCrumple || tLn.isBranchCrumple) ? 14 : 18;
        edges.push({ x1: fLn.x, y1: fLn.y - fOff, x2: tLn.x, y2: tLn.y + tOff, active: true, collapsed: false });
      }
    }

    var maxY = 0;
    for (var myi = 0; myi < layoutNodes.length; myi++) {
      var my = layoutNodes[myi].y + NODE_H / 2;
      if (my > maxY) maxY = my;
    }
    var totalW = (maxCol.val + 1) * (NODE_W + H_GAP);
    var totalH = maxY + V_GAP;

    return { nodes: layoutNodes, edges: edges, width: totalW, height: totalH, groups: groups };
  }

  function _layoutBranchVertical(nodeId, preferCol, forkRow, positions, maxCol, colOccupied) {
    var subtree = [];
    var stack = [nodeId];
    while (stack.length > 0) {
      var sid = stack.pop();
      var snd = _historyNodes[sid];
      if (!snd) continue;
      subtree.push(sid);
      for (var sc = snd.children.length - 1; sc >= 0; sc--) {
        stack.push(snd.children[sc]);
      }
    }
    var col = preferCol;
    var hasCollision = true;
    while (hasCollision) {
      hasCollision = false;
      for (var ci = 0; ci < subtree.length; ci++) {
        var testRow = forkRow + 1 + ci;
        var key = col + ':' + testRow;
        if (colOccupied[key]) { hasCollision = true; break; }
      }
      if (hasCollision) col++;
    }
    if (col > maxCol.val) maxCol.val = col;
    for (var pi = 0; pi < subtree.length; pi++) {
      var r = forkRow + 1 + pi;
      positions[subtree[pi]] = { col: col, row: r };
      colOccupied[col + ':' + r] = true;
    }
  }

  function _computeYahRoute(startX, startY, layoutNodes, currentNodeId, maxX, maxY) {
    var PAD = 14;
    var rects = [];
    for (var i = 0; i < layoutNodes.length; i++) {
      var ln = layoutNodes[i];
      if (ln.id === currentNodeId) continue;
      var hw = 150;
      var hh = (ln.isCrumple || ln.isBranchCrumple || ln.isVtreeFork || ln.isVtreeOption) ? 18 : 24;
      rects.push({ l: ln.x - hw, r: ln.x + hw, t: ln.y - hh, b: ln.y + hh });
    }

    var endX = Math.max(maxX - 80, startX + 100);
    var pts = [{ x: startX, y: startY }];
    var curY = startY;

    var rightRects = [];
    for (var ri = 0; ri < rects.length; ri++) {
      if (rects[ri].r > startX && rects[ri].l < endX) rightRects.push(rects[ri]);
    }
    rightRects.sort(function (a, b) { return a.l - b.l; });

    for (var oi = 0; oi < rightRects.length; oi++) {
      var obs = rightRects[oi];
      if (curY < obs.t - PAD || curY > obs.b + PAD) continue;

      var aboveY = obs.t - PAD - 8;
      var belowY = obs.b + PAD + 8;
      var newY;
      if (aboveY < 10) newY = belowY;
      else if (belowY > maxY - 10) newY = aboveY;
      else newY = (Math.abs(curY - aboveY) <= Math.abs(curY - belowY)) ? aboveY : belowY;

      var approachX = Math.max(obs.l - PAD - 20, startX + 10);
      pts.push({ x: approachX, y: curY });
      pts.push({ x: (obs.l + obs.r) / 2, y: newY });
      pts.push({ x: obs.r + PAD + 20, y: newY });
      curY = newY;
    }

    pts.push({ x: endX, y: curY });
    return { points: pts, endY: curY };
  }

  function _yahPointsToPath(pts) {
    if (pts.length < 2) return '';
    var d = 'M' + pts[0].x.toFixed(1) + ' ' + pts[0].y.toFixed(1);
    for (var i = 1; i < pts.length; i++) {
      var p = pts[i - 1], c = pts[i];
      if (Math.abs(p.y - c.y) < 1) {
        d += ' L' + c.x.toFixed(1) + ' ' + c.y.toFixed(1);
      } else {
        var mx = (p.x + c.x) / 2;
        d += ' C' + mx.toFixed(1) + ' ' + p.y.toFixed(1) + ', ' +
          mx.toFixed(1) + ' ' + c.y.toFixed(1) + ', ' +
          c.x.toFixed(1) + ' ' + c.y.toFixed(1);
      }
    }
    return d;
  }

  function _computeOrganicLayout() {
    var rootId = null;
    var ids = Object.keys(_historyNodes);
    for (var i = 0; i < ids.length; i++) {
      if (_historyNodes[ids[i]].parentId === null) { rootId = _historyNodes[ids[i]].id; break; }
    }
    if (rootId === null) return { nodes: [], edges: [], width: 0, height: 0 };

    var DOT_R = 5;
    var DOT_GAP = 6;
    var STEP = DOT_R * 2 + DOT_GAP;

    var rootToCurrent = [];
    var walkBack = _historyCurrentId;
    while (walkBack !== null && _historyNodes[walkBack]) {
      rootToCurrent.push(walkBack);
      walkBack = _historyNodes[walkBack].parentId;
    }
    rootToCurrent.reverse();

    var activePath = {};
    var activePathList = rootToCurrent.slice();
    for (var rtc = 0; rtc < rootToCurrent.length; rtc++) {
      activePath[rootToCurrent[rtc]] = true;
    }
    var fwdId = _historyCurrentId;
    if (_historyNodes[fwdId]) {
      fwdId = _historyNodes[fwdId].activeChildId || null;
    }
    while (fwdId !== null && _historyNodes[fwdId]) {
      if (!activePath[fwdId]) {
        activePath[fwdId] = true;
        activePathList.push(fwdId);
      }
      fwdId = _historyNodes[fwdId].activeChildId || null;
    }

    var positions = {};
    var allNodes = [];
    var edges = [];
    var centerX = 200;
    var activeLen = activePathList.length;

    for (var ap = 0; ap < activeLen; ap++) {
      var row = activeLen - 1 - ap;
      positions[activePathList[ap]] = { x: centerX, y: row * STEP + STEP };
      allNodes.push(activePathList[ap]);
    }

    var branchQueue = [];
    for (var apb = 0; apb < activeLen; apb++) {
      var bpNode = _historyNodes[activePathList[apb]];
      if (!bpNode) continue;
      var leftNext = true;
      for (var bc = 0; bc < bpNode.children.length; bc++) {
        if (!activePath[bpNode.children[bc]]) {
          branchQueue.push({
            nodeId: bpNode.children[bc],
            parentPos: positions[activePathList[apb]],
            side: leftNext ? -1 : 1,
            depth: 1
          });
          leftNext = !leftNext;
        }
      }
    }

    while (branchQueue.length > 0) {
      var item = branchQueue.shift();
      var nd = _historyNodes[item.nodeId];
      if (!nd || positions[item.nodeId]) continue;
      var xOff = item.side * item.depth * STEP;
      var yOff = -STEP;
      positions[item.nodeId] = {
        x: item.parentPos.x + xOff,
        y: item.parentPos.y + yOff
      };
      allNodes.push(item.nodeId);
      var childSide = item.side;
      for (var cc = 0; cc < nd.children.length; cc++) {
        branchQueue.push({
          nodeId: nd.children[cc],
          parentPos: positions[item.nodeId],
          side: childSide,
          depth: 1
        });
        childSide = -childSide;
      }
    }

    var layoutNodes = [];
    var minX = Infinity, maxX = 0, minY = Infinity, maxY = 0;
    for (var an = 0; an < allNodes.length; an++) {
      var nid = allNodes[an];
      var pos = positions[nid];
      if (!pos) continue;
      var nd2 = _historyNodes[nid];
      layoutNodes.push({
        id: nid,
        x: pos.x,
        y: pos.y,
        onActivePath: !!activePath[nid],
        isCurrent: nid === _historyCurrentId,
        summary: nd2 ? (nd2.summary || (nd2.parentId === null ? 'initial' : 'edit')) : 'edit'
      });
      if (pos.x < minX) minX = pos.x;
      if (pos.x > maxX) maxX = pos.x;
      if (pos.y < minY) minY = pos.y;
      if (pos.y > maxY) maxY = pos.y;

      if (nd2) {
        for (var ec = 0; ec < nd2.children.length; ec++) {
          var cpos = positions[nd2.children[ec]];
          if (cpos) {
            edges.push({
              x1: pos.x, y1: pos.y,
              x2: cpos.x, y2: cpos.y,
              active: !!activePath[nid] && !!activePath[nd2.children[ec]]
            });
          }
        }
      }
    }

    var pad = 30;
    for (var shi = 0; shi < layoutNodes.length; shi++) {
      layoutNodes[shi].x -= (minX - pad);
      layoutNodes[shi].y -= (minY - pad);
    }
    for (var she = 0; she < edges.length; she++) {
      edges[she].x1 -= (minX - pad);
      edges[she].y1 -= (minY - pad);
      edges[she].x2 -= (minX - pad);
      edges[she].y2 -= (minY - pad);
    }

    return {
      nodes: layoutNodes,
      edges: edges,
      width: maxX - minX + pad * 2,
      height: maxY - minY + pad * 2
    };
  }

  function _renderOrganicDag(container) {
    container.innerHTML = '';
    var layout = _computeOrganicLayout();
    if (layout.nodes.length === 0) {
      container.textContent = 'No history';
      return;
    }

    var wrapper = document.createElement('div');
    wrapper.className = 'live-wysiwyg-organic-wrapper';
    wrapper.style.position = 'relative';
    wrapper.style.width = Math.max(layout.width, 400) + 'px';
    wrapper.style.height = layout.height + 'px';
    wrapper.style.minWidth = '100%';

    var svgNs = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(svgNs, 'svg');
    svg.setAttribute('class', 'live-wysiwyg-organic-svg');
    svg.setAttribute('width', Math.max(layout.width, 400));
    svg.setAttribute('height', layout.height);
    svg.style.position = 'absolute';
    svg.style.top = '0';
    svg.style.left = '0';

    for (var e = 0; e < layout.edges.length; e++) {
      var edge = layout.edges[e];
      var ePath = document.createElementNS(svgNs, 'path');
      var d;
      if (Math.abs(edge.x1 - edge.x2) < 1) {
        d = 'M' + edge.x1 + ' ' + edge.y1 + ' L' + edge.x2 + ' ' + edge.y2;
      } else {
        var eMidY = (edge.y1 + edge.y2) / 2;
        d = 'M' + edge.x1 + ' ' + edge.y1 +
          ' C' + edge.x1 + ' ' + eMidY + ', ' + edge.x2 + ' ' + eMidY + ', ' + edge.x2 + ' ' + edge.y2;
      }
      ePath.setAttribute('d', d);
      ePath.setAttribute('class', edge.active ? 'live-wysiwyg-organic-edge-active' : 'live-wysiwyg-organic-edge');
      svg.appendChild(ePath);
    }
    wrapper.appendChild(svg);

    for (var ni = 0; ni < layout.nodes.length; ni++) {
      var ln = layout.nodes[ni];
      var dot = document.createElement('div');
      dot.className = 'live-wysiwyg-organic-dot';
      if (ln.onActivePath) dot.classList.add('active-path');
      if (ln.isCurrent) dot.classList.add('current');
      dot.style.position = 'absolute';
      dot.style.left = (ln.x - 5) + 'px';
      dot.style.top = (ln.y - 5) + 'px';
      dot.setAttribute('data-node-id', ln.id);
      dot.title = ln.summary;

      (function (nodeId) {
        dot.addEventListener('click', function (ev) {
          if (ev.detail === 2) return;
          _selectDagNode(nodeId);
        });
        dot.addEventListener('dblclick', function () {
          _restoreToHistoryNode(nodeId);
          _exitHistoryMode();
        });
      })(ln.id);

      wrapper.appendChild(dot);
    }

    container.appendChild(wrapper);

    var currentDot = container.querySelector('.live-wysiwyg-organic-dot.current');
    if (currentDot) {
      currentDot.scrollIntoView({ block: 'center', inline: 'center', behavior: 'auto' });
    }
  }

  function _renderDag(container, opts) {
    if (_historyDagViewMode === 'organic') {
      _renderOrganicDag(container);
      return;
    }
    var skipAutoScroll = opts && opts.skipAutoScroll;
    container.innerHTML = '';
    var layout = _computeDagLayout();
    if (layout.nodes.length === 0) {
      container.textContent = 'No history';
      return;
    }

    var yahLabelExtra = 180;
    var wrapperW = Math.max(layout.width + yahLabelExtra, 400);

    var wrapper = document.createElement('div');
    wrapper.style.position = 'relative';
    wrapper.style.width = wrapperW + 'px';
    wrapper.style.height = layout.height + 'px';
    wrapper.style.minWidth = '100%';

    var svgNs = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(svgNs, 'svg');
    svg.setAttribute('class', 'live-wysiwyg-history-dag-svg');
    svg.setAttribute('width', wrapperW);
    svg.setAttribute('height', layout.height);
    svg.style.position = 'absolute';
    svg.style.top = '0';
    svg.style.left = '0';

    for (var e = 0; e < layout.edges.length; e++) {
      var edge = layout.edges[e];
      if (edge.collapsed) continue;
      var ePath = document.createElementNS(svgNs, 'path');
      var d;
      if (Math.abs(edge.x1 - edge.x2) < 1) {
        d = 'M' + edge.x1 + ' ' + edge.y1 + ' L' + edge.x2 + ' ' + edge.y2;
      } else {
        var eMidY = (edge.y1 + edge.y2) / 2;
        d = 'M' + edge.x1 + ' ' + edge.y1 +
          ' C' + edge.x1 + ' ' + eMidY + ', ' + edge.x2 + ' ' + eMidY + ', ' + edge.x2 + ' ' + edge.y2;
      }
      ePath.setAttribute('d', d);
      ePath.setAttribute('class', edge.active ? 'live-wysiwyg-dag-edge-active' : 'live-wysiwyg-dag-edge');
      svg.appendChild(ePath);
    }
    wrapper.appendChild(svg);

    var currentLn = null;
    for (var ci = 0; ci < layout.nodes.length; ci++) {
      if (layout.nodes[ci].isCurrent) { currentLn = layout.nodes[ci]; break; }
    }
    var yahRoute = null;
    if (currentLn) {
      var yahStartX = currentLn.x + 150 + 4;
      var yahStartY = currentLn.y;
      var svgW = parseInt(svg.getAttribute('width'), 10) || layout.width;
      var svgH = parseInt(svg.getAttribute('height'), 10) || layout.height;
      yahRoute = _computeYahRoute(yahStartX, yahStartY, layout.nodes, currentLn.id, svgW, svgH);

      var yahPathD = _yahPointsToPath(yahRoute.points);
      if (yahPathD) {
        var yahPath = document.createElementNS(svgNs, 'path');
        yahPath.setAttribute('d', yahPathD);
        yahPath.setAttribute('class', 'live-wysiwyg-dag-yah-path');
        svg.appendChild(yahPath);

        var arrowSize = 14;
        var arrowTip = yahRoute.points[0];
        var arrowD = 'M' + (arrowTip.x - 2).toFixed(1) + ' ' + arrowTip.y.toFixed(1) +
          ' L' + (arrowTip.x + arrowSize).toFixed(1) + ' ' + (arrowTip.y - arrowSize * 0.55).toFixed(1) +
          ' L' + (arrowTip.x + arrowSize).toFixed(1) + ' ' + (arrowTip.y + arrowSize * 0.55).toFixed(1) + ' Z';
        var yahArrow = document.createElementNS(svgNs, 'path');
        yahArrow.setAttribute('d', arrowD);
        yahArrow.setAttribute('class', 'live-wysiwyg-dag-yah-arrowhead');
        svg.appendChild(yahArrow);
      }
    }

    var nodesLayer = document.createElement('div');
    nodesLayer.className = 'live-wysiwyg-history-dag-nodes';
    nodesLayer.style.position = 'absolute';
    nodesLayer.style.top = '0';
    nodesLayer.style.left = '0';

    var animatingKey = _historyDagAnimatingGroup;
    _historyDagAnimatingGroup = null;
    var animIdx = 0;

    for (var ni = 0; ni < layout.nodes.length; ni++) {
      var ln = layout.nodes[ni];
      var nodeData = _historyNodes[ln.id];
      var el;

      if (ln.isCrumple) {
        el = document.createElement('div');
        el.className = 'live-wysiwyg-dag-crumple';
        if (ln.crumpleType) el.setAttribute('data-container-type', ln.crumpleType);
        el.style.position = 'absolute';
        el.style.left = (ln.x - 150) + 'px';
        el.style.top = (ln.y - 18) + 'px';
        el.appendChild(_createCrumpleSvg());
        var crLabel = document.createElement('span');
        crLabel.className = 'live-wysiwyg-dag-crumple-label';
        crLabel.textContent = ln.crumpleLabel + ' (' + ln.crumpleCount + ' edits)';
        el.appendChild(crLabel);
        (function (key, dagContainer) {
          el.addEventListener('click', function (ev) {
            ev.stopPropagation();
            _historyDagAnimatingGroup = key;
            _historyDagExpandedGroups[key] = true;
            _renderDag(dagContainer);
          });
        })(ln.crumpleKey, container);
        nodesLayer.appendChild(el);
        continue;
      }

      if (ln.isVtreeFork) {
        el = document.createElement('div');
        el.className = 'live-wysiwyg-dag-vtree-fork';
        el.style.position = 'absolute';
        el.style.left = (ln.x - 150) + 'px';
        el.style.top = (ln.y - 18) + 'px';
        el.appendChild(_createVtreeForkSvg());
        var vtLabel = document.createElement('span');
        vtLabel.className = 'live-wysiwyg-dag-vtree-label';
        vtLabel.textContent = 'Multiple histories (' + (ln.vtreeChildIds ? ln.vtreeChildIds.length : 0) + ')';
        el.appendChild(vtLabel);
        (function (bpKey, dagContainer) {
          el.addEventListener('click', function (ev) {
            ev.stopPropagation();
            if (_historyDagActiveBranchKey === bpKey) {
              _historyDagActiveBranchKey = null;
              _historyDagVtreeSelectedBranch[bpKey] = null;
            } else {
              _historyDagActiveBranchKey = bpKey;
              _historyDagVtreeSelectedBranch[bpKey] = null;
            }
            _renderDag(dagContainer);
          });
        })(ln.vtreeBpKey, container);
        if (_historyDagActiveBranchKey === ln.vtreeBpKey) el.classList.add('active');
        nodesLayer.appendChild(el);
        continue;
      }

      if (ln.isVtreeOption) {
        el = document.createElement('div');
        el.className = 'live-wysiwyg-dag-vtree-option';
        el.style.position = 'absolute';
        el.style.left = (ln.x - 150) + 'px';
        el.style.top = (ln.y - 18) + 'px';
        var optIcon = _createCrumpleSvg();
        el.appendChild(optIcon);
        var optLabel = document.createElement('span');
        optLabel.className = 'live-wysiwyg-dag-vtree-option-label';
        optLabel.textContent = ln.optionSummary + ' (' + ln.optionCount + ' edits)';
        el.appendChild(optLabel);
        (function (bpKey, childId, dagContainer) {
          el.addEventListener('click', function (ev) {
            ev.stopPropagation();
            _historyDagVtreeSelectedBranch[bpKey] = childId;
            _historyDagAnimatingGroup = bpKey;
            _renderDag(dagContainer);
          });
        })(ln.vtreeBpKey, ln.optionChildId, container);
        nodesLayer.appendChild(el);
        continue;
      }

      if (ln.isBranchCrumple) {
        el = document.createElement('div');
        el.className = 'live-wysiwyg-dag-crumple branch-crumple';
        el.style.position = 'absolute';
        el.style.left = (ln.x - 150) + 'px';
        el.style.top = (ln.y - 18) + 'px';
        el.appendChild(_createCrumpleSvg());
        var brLabel = document.createElement('span');
        brLabel.className = 'live-wysiwyg-dag-crumple-label';
        var brChildNode = _historyNodes[ln.branchChildId];
        brLabel.textContent = (brChildNode ? (brChildNode.summary || 'edit') : 'edit') + ' (' + ln.branchCount + ' edits)';
        el.appendChild(brLabel);
        (function (brKey, dagContainer) {
          el.addEventListener('click', function (ev) {
            ev.stopPropagation();
            if (_historyDagActiveBranchKey === brKey) {
              _historyDagActiveBranchKey = null;
            } else {
              _historyDagActiveBranchKey = brKey;
            }
            _historyDagAnimatingGroup = brKey;
            _renderDag(dagContainer);
          });
        })(ln.branchKey, container);
        if (_historyDagActiveBranchKey === ln.branchKey) el.classList.add('active');
        nodesLayer.appendChild(el);
        continue;
      }

      el = document.createElement('div');
      el.className = 'live-wysiwyg-history-dag-node';
      if (ln.isCurrent) el.classList.add('current');
      if (ln.onActivePath) el.classList.add('active-path');
      if (ln.isBranch) el.classList.add('branch-point');
      if (ln.id === _historyDagSelectedNodeId) el.classList.add('selected');
      el.setAttribute('data-node-id', ln.id);
      el.style.position = 'absolute';
      el.style.left = (ln.x - 150) + 'px';
      el.style.top = (ln.y - 24) + 'px';

      if (animatingKey && ln.crumpleKey === undefined && !ln.isSynthetic) {
        var isInAnimGroup = false;
        for (var agi = 0; agi < layout.groups.length; agi++) {
          var ag = layout.groups[agi];
          var agKey = 'g-' + ag.nodeIds[0];
          if (agKey === animatingKey) {
            for (var agn = 0; agn < ag.nodeIds.length; agn++) {
              if (ag.nodeIds[agn] === ln.id) { isInAnimGroup = true; break; }
            }
            break;
          }
        }
        if (isInAnimGroup) {
          el.classList.add('group-enter');
          el.style.animationDelay = (animIdx * 50) + 'ms';
          animIdx++;
        }
      }

      var dot = document.createElement('span');
      dot.className = 'live-wysiwyg-dag-dot';
      el.appendChild(dot);

      var info = document.createElement('span');
      info.className = 'live-wysiwyg-dag-info';
      var summaryText = nodeData ? (nodeData.summary || (nodeData.parentId === null ? 'initial content' : 'edit')) : 'edit';
      info.textContent = summaryText;
      el.appendChild(info);

      var ts = document.createElement('span');
      ts.className = 'live-wysiwyg-dag-time';
      ts.textContent = nodeData ? _formatRelativeTime(nodeData.timestamp) : '';
      el.appendChild(ts);

      (function (nodeId, nodeEl) {
        var hoverTimer = null;
        nodeEl.addEventListener('mouseenter', function () {
          hoverTimer = setTimeout(function () {
            _showDagHoverPreview(nodeId, nodeEl);
          }, 200);
        });
        nodeEl.addEventListener('mouseleave', function () {
          if (hoverTimer) clearTimeout(hoverTimer);
          _dismissDagHoverPreview();
        });
        nodeEl.addEventListener('click', function (ev) {
          if (ev.detail === 2) return;
          _selectDagNode(nodeId);
        });
        nodeEl.addEventListener('dblclick', function () {
          _restoreToHistoryNode(nodeId);
          _exitHistoryMode();
        });
      })(ln.id, el);

      nodesLayer.appendChild(el);
    }

    // Block context dotted outlines for all container groups
    if (layout.groups) {
      for (var ogi = 0; ogi < layout.groups.length; ogi++) {
        var og = layout.groups[ogi];
        if (!og.type) continue;
        var isActiveGroup = false;
        for (var ogn = 0; ogn < og.nodeIds.length; ogn++) {
          if (og.nodeIds[ogn] === _historyCurrentId) { isActiveGroup = true; break; }
        }
        var outlineTop = Infinity, outlineBottom = 0;
        var outlineLeftX = Infinity;
        for (var oli = 0; oli < layout.nodes.length; oli++) {
          var oln = layout.nodes[oli];
          if (oln.col !== 0) continue;
          var isInGroup = false;
          for (var oin = 0; oin < og.nodeIds.length; oin++) {
            if (og.nodeIds[oin] === oln.id) { isInGroup = true; break; }
          }
          if (isInGroup || oln.isCrumple) {
            if (oln.isCrumple && oln.crumpleNodeIds) {
              var crumpOverlap = false;
              for (var coi = 0; coi < oln.crumpleNodeIds.length; coi++) {
                for (var coj = 0; coj < og.nodeIds.length; coj++) {
                  if (oln.crumpleNodeIds[coi] === og.nodeIds[coj]) { crumpOverlap = true; break; }
                }
                if (crumpOverlap) break;
              }
              if (!crumpOverlap) continue;
            }
            var nodeTop2 = oln.y - 24;
            var nodeBot2 = oln.y + 24;
            if (nodeTop2 < outlineTop) outlineTop = nodeTop2;
            if (nodeBot2 > outlineBottom) outlineBottom = nodeBot2;
            var nodeLeft = oln.x - 150;
            if (nodeLeft < outlineLeftX) outlineLeftX = nodeLeft;
          }
        }
        if (outlineTop < outlineBottom) {
          var outlineEl = document.createElement('div');
          outlineEl.className = 'live-wysiwyg-dag-block-outline';
          if (!isActiveGroup) outlineEl.classList.add('inactive');
          if (og.type) outlineEl.setAttribute('data-container-type', og.type);
          outlineEl.style.position = 'absolute';
          outlineEl.style.left = (outlineLeftX - 8) + 'px';
          outlineEl.style.top = (outlineTop - 6) + 'px';
          outlineEl.style.width = '316px';
          outlineEl.style.height = (outlineBottom - outlineTop + 12) + 'px';
          var outlineTitle = document.createElement('span');
          outlineTitle.className = 'live-wysiwyg-dag-block-outline-title';
          outlineTitle.textContent = og.label;
          outlineEl.appendChild(outlineTitle);
          nodesLayer.insertBefore(outlineEl, nodesLayer.firstChild);
        }
      }
    }

    wrapper.appendChild(nodesLayer);
    container.appendChild(wrapper);

    if (yahRoute) {
      var yahEndPt = yahRoute.points[yahRoute.points.length - 1];
      var yahLabel = document.createElement('div');
      yahLabel.className = 'live-wysiwyg-dag-you-are-here-label';
      yahLabel.style.position = 'absolute';
      yahLabel.style.top = (yahEndPt.y - 12) + 'px';
      yahLabel.style.left = (yahEndPt.x + 4) + 'px';
      var yahArrowIcon = document.createElementNS(svgNs, 'svg');
      yahArrowIcon.setAttribute('width', '10');
      yahArrowIcon.setAttribute('height', '12');
      yahArrowIcon.setAttribute('viewBox', '0 0 10 12');
      var yahTriIcon = document.createElementNS(svgNs, 'path');
      yahTriIcon.setAttribute('d', 'M9 1 L1 6 L9 11Z');
      yahTriIcon.setAttribute('fill', 'currentColor');
      yahArrowIcon.appendChild(yahTriIcon);
      yahLabel.appendChild(yahArrowIcon);
      var yahTxt = document.createElement('span');
      yahTxt.textContent = 'You Are Here';
      yahLabel.appendChild(yahTxt);
      wrapper.appendChild(yahLabel);

      var yahSvgPath = svg.querySelector('.live-wysiwyg-dag-yah-path');
      var yahDefaultLeft = yahEndPt.x + 4;
      var yahLabelW = 130;
      (function (lbl, svgPathEl, routePts, defLeft, lblW, dagCont) {
        function clampYah() {
          var visRight = dagCont.scrollLeft + dagCont.clientWidth - 8;
          var newEndX = visRight - lblW - 4;
          if (newEndX >= defLeft) newEndX = defLeft;
          if (newEndX < routePts[0].x + 20) newEndX = routePts[0].x + 20;
          lbl.style.left = (newEndX + 4) + 'px';

          if (svgPathEl) {
            var truncPts = [];
            for (var ti = 0; ti < routePts.length - 1; ti++) {
              if (routePts[ti].x <= newEndX) truncPts.push(routePts[ti]);
              else break;
            }
            truncPts.push({ x: newEndX, y: truncPts.length > 0 ? truncPts[truncPts.length - 1].y : routePts[0].y });
            svgPathEl.setAttribute('d', _yahPointsToPath(truncPts));
          }
        }
        dagCont.addEventListener('scroll', clampYah);
        var resObs = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(clampYah) : null;
        if (resObs) resObs.observe(dagCont);
        clampYah();
      })(yahLabel, yahSvgPath, yahRoute.points, yahDefaultLeft, yahLabelW, container);
    }

    if (!skipAutoScroll) {
      var currentEl = container.querySelector('.live-wysiwyg-history-dag-node.current');
      if (currentEl) {
        currentEl.scrollIntoView({ block: 'center', inline: 'center', behavior: 'auto' });
      }
    }
  }

  // --- Hover Preview ---

  var _dagHoverPreviewEl = null;

  function _dismissDagHoverPreview() {
    if (_dagHoverPreviewEl && _dagHoverPreviewEl.parentNode) {
      _dagHoverPreviewEl.parentNode.removeChild(_dagHoverPreviewEl);
    }
    _dagHoverPreviewEl = null;
  }

  function _showDagHoverPreview(nodeId, anchorEl) {
    _dismissDagHoverPreview();
    var md = _historyPreviewCache[nodeId];
    if (!md) {
      md = _reconstructContentAtNode(nodeId);
      if (md !== null) _historyPreviewCache[nodeId] = md;
    }
    if (md === null) return;

    var tooltip = document.createElement('div');
    tooltip.className = 'live-wysiwyg-history-hover-preview';

    var snippetEl = document.createElement('div');
    snippetEl.className = 'live-wysiwyg-history-hover-snippet';
    var snippetBody = _stripFrontmatterForPreview(md);
    var snippetLines = snippetBody.split('\n').slice(0, 3).join('\n');
    snippetEl.textContent = snippetLines;
    tooltip.appendChild(snippetEl);

    var rendered = document.createElement('div');
    rendered.className = 'live-wysiwyg-history-hover-rendered';
    rendered.innerHTML = _renderMarkdownPreview(md);
    tooltip.appendChild(rendered);

    var fullBtn = document.createElement('button');
    fullBtn.className = 'live-wysiwyg-history-hover-fullscreen-btn';
    fullBtn.textContent = 'Full Screen';
    fullBtn.addEventListener('click', function (ev) {
      ev.stopPropagation();
      _showHistoryFullsizePreview(nodeId);
    });
    tooltip.appendChild(fullBtn);

    var rect = anchorEl.getBoundingClientRect();
    tooltip.style.position = 'fixed';
    tooltip.style.left = (rect.right + 8) + 'px';
    tooltip.style.top = rect.top + 'px';
    tooltip.style.zIndex = '99999';

    if (rect.right + 320 > window.innerWidth) {
      tooltip.style.left = '';
      tooltip.style.right = (window.innerWidth - rect.left + 8) + 'px';
    }

    var appendTarget = _historyOverlay || _focusOverlay || document.body;
    appendTarget.appendChild(tooltip);
    _dagHoverPreviewEl = tooltip;
  }

  // --- Click Selection & Preview Panel ---

  function _selectDagNode(nodeId) {
    _historyDagSelectedNodeId = nodeId;
    if (_historyOverlay) {
      var allNodes = _historyOverlay.querySelectorAll('.live-wysiwyg-history-dag-node');
      for (var i = 0; i < allNodes.length; i++) {
        allNodes[i].classList.toggle('selected', parseInt(allNodes[i].getAttribute('data-node-id'), 10) === nodeId);
      }
    }
    _updatePreviewPanel(nodeId);
  }

  function _updatePreviewPanel(nodeId) {
    if (!_historyOverlay) return;
    var panel = _historyOverlay.querySelector('.live-wysiwyg-history-preview-panel');
    if (!panel) return;
    var wasAlreadyOpen = panel.classList.contains('open');
    panel.innerHTML = '';

    var md = _historyPreviewCache[nodeId];
    if (!md) {
      md = _reconstructContentAtNode(nodeId);
      if (md !== null) _historyPreviewCache[nodeId] = md;
    }
    if (md === null) {
      panel.textContent = 'Cannot reconstruct content';
      panel.classList.add('open');
      return;
    }
    panel.classList.add('open');

    if (!wasAlreadyOpen) {
      var dagC = _historyOverlay.querySelector('.live-wysiwyg-history-dag-container');
      if (dagC) {
        var onTransEnd = function (ev) {
          if (ev.target !== panel) return;
          panel.removeEventListener('transitionend', onTransEnd);
          _renderDag(dagC, { skipAutoScroll: true });
        };
        panel.addEventListener('transitionend', onTransEnd);
      }
    }

    var nodeData = _historyNodes[nodeId];
    var panelHeader = document.createElement('div');
    panelHeader.className = 'live-wysiwyg-history-preview-header';
    var summaryEl = document.createElement('span');
    summaryEl.textContent = (nodeData ? (nodeData.summary || 'edit') : 'edit') +
      (nodeData ? ' \u2014 ' + _formatRelativeTime(nodeData.timestamp) : '');
    panelHeader.appendChild(summaryEl);

    var fullBtn = document.createElement('button');
    fullBtn.className = 'live-wysiwyg-history-preview-fullscreen-btn';
    fullBtn.textContent = 'Full Screen';
    fullBtn.addEventListener('click', function () {
      _showHistoryFullsizePreview(nodeId);
    });
    panelHeader.appendChild(fullBtn);

    var restoreBtn = document.createElement('button');
    restoreBtn.className = 'live-wysiwyg-history-preview-restore-btn';
    restoreBtn.textContent = 'Restore';
    restoreBtn.addEventListener('click', function () {
      _restoreToHistoryNode(nodeId);
      _exitHistoryMode();
    });
    panelHeader.appendChild(restoreBtn);
    panel.appendChild(panelHeader);

    var content = document.createElement('div');
    content.className = 'live-wysiwyg-history-preview-content';
    content.setAttribute('contenteditable', 'false');
    var panelBody = _stripFrontmatterForPreview(md);
    if (wysiwygEditor && wysiwygEditor._markdownToHtml) {
      content.innerHTML = wysiwygEditor._markdownToHtml(panelBody);
    } else {
      content.innerHTML = _renderMarkdownPreview(md);
    }
    _enhancePreviewContent(content);
    _applyDiffHighlightToPreview(content, nodeData, md);
    panel.appendChild(content);
  }

  function _applyDiffHighlightToPreview(contentEl, nodeData, md) {
    if (!nodeData || !nodeData.diff || !nodeData.diff.ops) return;
    var body = _stripFrontmatterForPreview(md);
    var bodyLines = body.split('\n');
    var changedLines = {};
    var diff = nodeData.diff;
    var fmOffset = md.length - body.length > 0 ? md.substring(0, md.length - body.length).split('\n').length - 1 : 0;

    for (var oi = 0; oi < diff.ops.length; oi++) {
      var op = diff.ops[oi];
      if (op.type === 'insert') {
        var insStart = op.afterLine - fmOffset;
        for (var il = 0; il < op.lines.length; il++) {
          changedLines[insStart + il] = true;
        }
      } else if (op.type === 'replace') {
        var repStart = op.line - fmOffset;
        for (var rl = 0; rl < op['new'].length; rl++) {
          changedLines[repStart + rl] = true;
        }
      }
    }

    var hasChanges = false;
    for (var k in changedLines) { hasChanges = true; break; }
    if (!hasChanges) return;

    // Map markdown lines to top-level block elements
    var blocks = [];
    for (var ci = 0; ci < contentEl.children.length; ci++) {
      var child = contentEl.children[ci];
      if (child.nodeType === 1) blocks.push(child);
    }

    var mdLine = 0;
    for (var bi = 0; bi < blocks.length; bi++) {
      var block = blocks[bi];
      var blockText = block.textContent || '';
      var blockLineCount = (blockText.match(/\n/g) || []).length + 1;

      // Scan past blank lines between blocks
      while (mdLine < bodyLines.length && bodyLines[mdLine] !== undefined && bodyLines[mdLine].trim() === '') {
        mdLine++;
      }

      var blockStart = mdLine;
      // Estimate how many markdown source lines this block spans
      var srcLines = 0;
      var tmpLine = mdLine;
      while (tmpLine < bodyLines.length && srcLines < blockLineCount + 4) {
        if (bodyLines[tmpLine].trim() === '' && srcLines >= blockLineCount) break;
        tmpLine++;
        srcLines++;
      }
      var blockEnd = tmpLine;
      mdLine = blockEnd;

      // Check if any changed line overlaps this block's source range
      var overlaps = false;
      for (var cl = blockStart; cl < blockEnd; cl++) {
        if (changedLines[cl]) { overlaps = true; break; }
      }
      if (overlaps) {
        block.classList.add('live-wysiwyg-diff-highlight');
      }
    }
  }

  // --- Way 3: Full-Size Readonly Preview ---

  function _dismissHistoryFullsizePreview() {
    if (_historyFullsizePreview && _historyFullsizePreview.parentNode) {
      _historyFullsizePreview.parentNode.removeChild(_historyFullsizePreview);
    }
    _historyFullsizePreview = null;
    if (_historyOverlay) _historyOverlay.focus();
  }

  function _enhancePreviewContent(container) {
    var pres = container.querySelectorAll('pre');
    for (var i = 0; i < pres.length; i++) {
      var pre = pres[i];
      var codeEl = pre.querySelector('code');
      if (!codeEl) continue;
      var langClass = (codeEl.className || '').match(/language-(\S+)/);
      var lang = langClass ? langClass[1] : '';
      if (lang === 'mermaid') {
        var mermaidCode = codeEl.textContent || '';
        if (mermaidCode.trim()) {
          var mWrapper = document.createElement('div');
          mWrapper.className = 'md-mermaid-block';
          mWrapper.setAttribute('contenteditable', 'false');
          var mPreview = document.createElement('div');
          mPreview.className = 'md-mermaid-preview';
          mWrapper.appendChild(mPreview);
          pre.parentNode.insertBefore(mWrapper, pre);
          pre.style.display = 'none';
          mWrapper.appendChild(pre);
          (function (pv, code) {
            _loadMermaidJs(function () { _renderMermaidPreview(pv, code); });
          })(mPreview, mermaidCode);
        }
      } else if (lang) {
        pre.setAttribute('data-lang', lang);
        var codeBlockWrapper = document.createElement('div');
        codeBlockWrapper.className = 'md-code-block';
        var langBar = document.createElement('div');
        langBar.className = 'md-code-lang';
        langBar.setAttribute('contenteditable', 'false');
        langBar.textContent = lang;
        codeBlockWrapper.appendChild(langBar);
        pre.parentNode.insertBefore(codeBlockWrapper, pre);
        codeBlockWrapper.appendChild(pre);
      }
    }
    var admonitions = container.querySelectorAll('.admonition');
    for (var a = 0; a < admonitions.length; a++) {
      admonitions[a].removeAttribute('contenteditable');
    }
    var btns = container.querySelectorAll('.md-admonition-settings-btn, .md-mermaid-expand-btn, .md-code-block .md-code-lang[contenteditable]');
    for (var b = 0; b < btns.length; b++) {
      if (btns[b].classList.contains('md-admonition-settings-btn') ||
          btns[b].classList.contains('md-mermaid-expand-btn')) {
        btns[b].parentNode.removeChild(btns[b]);
      } else {
        btns[b].setAttribute('contenteditable', 'false');
      }
    }
    var editables = container.querySelectorAll('[contenteditable="true"]');
    for (var e = 0; e < editables.length; e++) {
      editables[e].setAttribute('contenteditable', 'false');
    }
  }

  function _showHistoryFullsizePreview(nodeId) {
    _dismissHistoryFullsizePreview();
    _dismissDagHoverPreview();

    var md = _historyPreviewCache[nodeId];
    if (!md) {
      md = _reconstructContentAtNode(nodeId);
      if (md !== null) _historyPreviewCache[nodeId] = md;
    }
    if (md === null) return;

    var nodeData = _historyNodes[nodeId];
    var preview = document.createElement('div');
    preview.className = 'live-wysiwyg-history-fullsize-preview';
    preview.setAttribute('tabindex', '-1');

    var fsHeader = document.createElement('div');
    fsHeader.className = 'live-wysiwyg-history-fullsize-header';
    var fsTitle = document.createElement('span');
    fsTitle.textContent = 'Preview: ' + (nodeData ? (nodeData.summary || 'edit') : 'edit') +
      (nodeData ? ' \u2014 ' + _formatRelativeTime(nodeData.timestamp) : '');
    fsHeader.appendChild(fsTitle);

    var fsRestoreBtn = document.createElement('button');
    fsRestoreBtn.className = 'live-wysiwyg-history-fullsize-restore-btn';
    fsRestoreBtn.textContent = 'Restore to this point';
    fsRestoreBtn.addEventListener('click', function () {
      _restoreToHistoryNode(nodeId);
      _dismissHistoryFullsizePreview();
      _exitHistoryMode();
    });
    fsHeader.appendChild(fsRestoreBtn);

    var fsCloseBtn = document.createElement('button');
    fsCloseBtn.className = 'live-wysiwyg-history-fullsize-close-btn';
    fsCloseBtn.textContent = 'Close';
    fsCloseBtn.addEventListener('click', function () {
      _dismissHistoryFullsizePreview();
    });
    fsHeader.appendChild(fsCloseBtn);
    preview.appendChild(fsHeader);

    var fsBody = document.createElement('div');
    fsBody.className = 'live-wysiwyg-history-fullsize-body';
    var fsContent = document.createElement('div');
    fsContent.className = 'live-wysiwyg-history-fullsize-content';
    fsContent.setAttribute('contenteditable', 'false');
    var previewBody = _stripFrontmatterForPreview(md);
    if (wysiwygEditor && wysiwygEditor._markdownToHtml) {
      fsContent.innerHTML = wysiwygEditor._markdownToHtml(previewBody);
    } else {
      fsContent.innerHTML = _renderMarkdownPreview(md);
    }
    _enhancePreviewContent(fsContent);
    fsBody.appendChild(fsContent);
    preview.appendChild(fsBody);

    preview.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') {
        e.preventDefault(); e.stopPropagation();
        _dismissHistoryFullsizePreview();
      } else if (e.key === 'Enter') {
        e.preventDefault(); e.stopPropagation();
        _restoreToHistoryNode(nodeId);
        _dismissHistoryFullsizePreview();
        _exitHistoryMode();
      }
    });

    var appendTarget = _historyOverlay || _focusOverlay || document.body;
    appendTarget.appendChild(preview);
    _historyFullsizePreview = preview;
    preview.focus();
  }

  // --- Content Restoration from DAG ---

  function _restoreToHistoryNode(nodeId) {
    _flushHistoryCapture();
    var md = _reconstructContentAtNode(nodeId);
    if (md === null) return;
    var node = _historyNodes[nodeId];
    _historyCurrentId = nodeId;
    _historySetContent(md, node ? node.htmlSnapshot : null);
    _historyLastMd = wysiwygEditor ? (wysiwygEditor.getValue() || md) : md;
    if (node && node.cursor) {
      _restoreHistoryCursor(node.cursor, node.diff, md, false, !!(node && node.htmlSnapshot));
    }
    _autoSaveAndPersistHistory();
  }

  // --- DAG Overlay Keyboard ---

  function _attachHistoryOverlayKeyboard(overlay) {
    overlay.addEventListener('keydown', function (e) {
      if (_historyFullsizePreview) return;
      if (e.key === 'Escape') {
        e.preventDefault(); e.stopPropagation();
        _exitHistoryMode();
        return;
      }
      if (e.key === 'Enter' && _historyDagSelectedNodeId !== null) {
        e.preventDefault(); e.stopPropagation();
        _restoreToHistoryNode(_historyDagSelectedNodeId);
        _exitHistoryMode();
        return;
      }
      if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
        e.preventDefault();
        _navigateDag(e.key);
      }
    });
  }

  function _navigateDag(key) {
    var startId = _historyDagSelectedNodeId !== null ? _historyDagSelectedNodeId : _historyCurrentId;
    var node = _historyNodes[startId];
    if (!node) return;
    var targetId = null;
    if (key === 'ArrowUp' && node.parentId !== null) {
      targetId = node.parentId;
    } else if (key === 'ArrowDown') {
      if (node.activeChildId) targetId = node.activeChildId;
      else if (node.children.length > 0) targetId = node.children[0];
    } else if (key === 'ArrowLeft' || key === 'ArrowRight') {
      var parent = node.parentId !== null ? _historyNodes[node.parentId] : null;
      if (parent && parent.children.length > 1) {
        var idx = parent.children.indexOf(startId);
        if (key === 'ArrowLeft' && idx > 0) targetId = parent.children[idx - 1];
        if (key === 'ArrowRight' && idx < parent.children.length - 1) targetId = parent.children[idx + 1];
      }
    }
    if (targetId !== null) {
      _selectDagNode(targetId);
      var selectedEl = _historyOverlay ? _historyOverlay.querySelector('[data-node-id="' + targetId + '"]') : null;
      if (selectedEl) selectedEl.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
    }
  }

  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 ea = wysiwygEditor.editableArea;
      var mdOffset = _estimateMdOffsetFromWysiwyg(ea);
      var sem = captureSemanticSelection(ea);
      var sel = window.getSelection();
      var blockChildIndex = -1;
      var innerOffset = 0;
      if (sel && sel.rangeCount > 0) {
        var r = sel.getRangeAt(0);
        var node = r.startContainer;
        innerOffset = r.startOffset;
        var block = node;
        while (block && block.parentNode !== ea) {
          block = block.parentNode;
        }
        if (block && block.parentNode === ea) {
          for (var ci = 0; ci < ea.childNodes.length; ci++) {
            if (ea.childNodes[ci] === block) { blockChildIndex = ci; break; }
          }
          if (node !== block) {
            var w = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, null, false);
            var tn, tpos = 0;
            while ((tn = w.nextNode())) {
              if (tn === node) { innerOffset = tpos + r.startOffset; break; }
              tpos += tn.textContent.length;
            }
          }
        }
      }
      return {
        mode: 'wysiwyg',
        start: mdOffset,
        end: mdOffset,
        semantic: sem,
        blockChildIndex: blockChildIndex,
        innerOffset: innerOffset
      };
    }
    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, hasHtmlSnapshot) {
    if (!wysiwygEditor) return;
    if (hasHtmlSnapshot && cursor && cursor.mode === 'wysiwyg' && wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
      var ea = wysiwygEditor.editableArea;
      ea.focus();
      if (cursor.blockChildIndex >= 0 && cursor.blockChildIndex < ea.childNodes.length) {
        var targetBlock = ea.childNodes[cursor.blockChildIndex];
        try {
          var range = document.createRange();
          var w = document.createTreeWalker(targetBlock, NodeFilter.SHOW_TEXT, null, false);
          var tn, tpos = 0, placed = false;
          while ((tn = w.nextNode())) {
            if (tpos + tn.textContent.length >= cursor.innerOffset) {
              range.setStart(tn, Math.min(cursor.innerOffset - tpos, tn.textContent.length));
              range.collapse(true);
              placed = true;
              break;
            }
            tpos += tn.textContent.length;
          }
          if (!placed) {
            range.setStart(targetBlock, 0);
            range.collapse(true);
          }
          var sel = window.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
          return;
        } catch (ex) { /* fall through */ }
      }
      if (cursor.semantic && restoreSelectionFromSemantic(ea, cursor.semantic)) {
        return;
      }
      if (cursor.start !== undefined) {
        _placeCursorAtMdOffset(cursor.start, null);
        return;
      }
      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];
    var parentSnapshot = parent ? parent.htmlSnapshot : null;
    _historyCurrentId = current.parentId;

    _historySetContent(parentMd, parentSnapshot);
    _historyLastMd = wysiwygEditor.getValue() || parentMd;
    _restoreHistoryCursor(parent ? parent.cursor : null, undoDiff, parentMd, false, !!parentSnapshot);
    _autoSaveAndPersistHistory();
  }

  function _contentRedo() {
    if (_historyCurrentId === null) return;

    var preRedoNodeId = _historyCurrentId;
    _flushHistoryCapture();

    var current = _historyNodes[_historyCurrentId];
    if (!current || !current.activeChildId) {
      _showHistoryBranchPopup(_historyCurrentId);
      return;
    }

    var isBranchPoint = current.children.length > 1;

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

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

    var childSnapshot = child.htmlSnapshot || null;
    _historyCurrentId = child.id;

    _historySetContent(childMd, childSnapshot);
    _historyLastMd = wysiwygEditor.getValue() || childMd;
    _restoreHistoryCursor(child.cursor, child.diff, childMd, true, !!childSnapshot);
    _autoSaveAndPersistHistory();

    if (isBranchPoint) {
      _showHistoryBranchPopup(preRedoNodeId);
    }
  }

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

  function _persistContentHistory() {
    var srcPath = _getCurrentSrcPath();
    if (!srcPath) return;
    try {
      sessionStorage.setItem('live_wysiwyg_undo_dag', JSON.stringify({
        srcPath: srcPath,
        nodes: _historyNodes,
        currentId: _historyCurrentId,
        rootMd: _historyRootMd,
        nextId: _historyNextId,
        lastMd: _historyLastMd
      }));
    } catch (e) { /* quota */ }
  }

  function _autoSaveAndPersistHistory() {
    _persistContentHistory();
    if (isFocusModeActive && wysiwygEditor && wysiwygEditor._isDocDirty && wysiwygEditor._isDocDirty()) {
      _doFocusSaveBackground();
    }
  }

  function _restoreContentHistory() {
    try {
      var raw = sessionStorage.getItem('live_wysiwyg_undo_dag');
      if (!raw) return false;
      var dag = JSON.parse(raw);
      if (!dag || dag.srcPath !== _getCurrentSrcPath()) return false;
      if (!dag.nodes || dag.rootMd == null) return false;

      _historyNodes = dag.nodes;
      _historyCurrentId = dag.currentId;
      _historyRootMd = dag.rootMd;
      _historyNextId = dag.nextId;
      _historyLastMd = dag.lastMd;

      var ta = document.querySelector('.live-edit-source');
      if (ta && ta.value !== _historyLastMd) {
        _historyLastMd = ta.value;
      }
      return true;
    } catch (e) { return false; }
  }

  // --- 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 siteGearBtn = document.createElement('button');
    siteGearBtn.type = 'button';
    siteGearBtn.textContent = '\u2699';
    siteGearBtn.title = 'Site settings';
    siteGearBtn.className = 'live-wysiwyg-nav-settings-gear live-wysiwyg-nav-site-gear';
    siteGearBtn.addEventListener('click', function (e) {
      e.stopPropagation();
      e.preventDefault();
      _showSiteSettingsGear(siteGearBtn);
    });
    navTitle.appendChild(siteGearBtn);

    var siteTitleText = _extractSiteName(_virtualMkdocsYml) ||
      (document.title ? document.title.split(' - ').pop().trim() : 'Navigation');
    var siteTitleSpan = document.createElement('span');
    siteTitleSpan.className = 'live-wysiwyg-nav-site-title';
    siteTitleSpan.textContent = siteTitleText;
    navTitle.appendChild(siteTitleSpan);

    navTitle.addEventListener('mouseenter', function () {
      navTitle.classList.add('live-wysiwyg-nav-title-hover');
    });
    navTitle.addEventListener('mouseleave', function () {
      if (!document.querySelector('.live-wysiwyg-nav-settings-dropdown')) {
        navTitle.classList.remove('live-wysiwyg-nav-title-hover');
      }
    });

    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;
  }

  var _ASSET_IMAGE_EXTS = {'.png':1,'.jpg':1,'.jpeg':1,'.gif':1,'.svg':1,'.webp':1,'.ico':1,'.bmp':1,'.avif':1};
  var _ASSET_TEXT_EXTS = {'.txt':1,'.csv':1,'.json':1,'.yaml':1,'.yml':1,'.xml':1,'.html':1,'.css':1,'.js':1,'.ts':1,'.py':1,'.sh':1,'.conf':1,'.cfg':1,'.ini':1,'.toml':1,'.env':1,'.log':1,'.sql':1,'.graphql':1,'.tf':1,'.hcl':1,'.rst':1,'.tex':1,'.lua':1,'.rb':1,'.go':1,'.rs':1,'.kt':1,'.java':1,'.c':1,'.cpp':1,'.h':1,'.hpp':1,'.cs':1,'.swift':1,'.bat':1,'.ps1':1,'.dockerfile':1,'.properties':1,'.gradle':1};

  function _getAssetPreviewType(ext) {
    if (!ext) return null;
    var lower = ext.toLowerCase();
    if (_ASSET_IMAGE_EXTS[lower]) return 'image';
    if (_ASSET_TEXT_EXTS[lower]) return 'text';
    return null;
  }

  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 _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);

        {
          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;

        {
          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._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 {
                _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';
        }

        {
          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 || '');
        var _assetPreviewType = _getAssetPreviewType(item.extension);
        if (_assetPreviewType) assetSpan.style.cursor = 'pointer';
        if (_assetPreviewType === 'image') assetSpan.draggable = true;
        (function (aLi, aLink, navItem, prevType) {
          aLink.addEventListener('mouseenter', function () { _showNavItemControls(aLi); });
          aLink.addEventListener('mouseleave', function () { _scheduleNavItemHide(aLi); });
          if (prevType === 'image') {
            aLink.addEventListener('dragstart', function (e) {
              if (_hasAnyNavSelected()) { e.preventDefault(); return; }
              e.dataTransfer.setData('application/x-live-wysiwyg-asset', JSON.stringify({
                _uid: navItem._uid, src_path: navItem.src_path,
                extension: navItem.extension, title: navItem.title
              }));
              e.dataTransfer.setData('text/plain', navItem.src_path);
              e.dataTransfer.effectAllowed = 'copy';
            });
          }
          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;
            }
            if (prevType) {
              e.preventDefault();
              e.stopPropagation();
              _showAssetPreviewPopup(aLi, navItem);
            }
          });
        })(li, assetSpan, item, _assetPreviewType);

        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';

    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);
    });

    controls.appendChild(upBtn);
    controls.appendChild(leftBtn);
    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;
      }
    }

    var allMoved = [focal].concat(effectiveItems.filter(function (e) { return e !== focal; }));
    for (var ai = 0; ai < allMoved.length; ai++) {
      var _gItem = allMoved[ai];
      if (_gItem.type === 'section' && !_getItemSrcPath(_gItem)) {
        var _gFd = _getSectionFolderDir(_gItem);
        if (!_gFd) continue;
        var _gPath = _gFd + '/index.md';
        var _gTitle = _gItem.title || _gFd.split('/').pop().replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
        var _gIndex = {
          type: 'page', src_path: _gPath, title: _gTitle,
          isIndex: true, retitled: true, empty: true, weight: 100,
          _fm: { title: _gTitle, retitled: true, empty: true, weight: 100 },
          _new: true, _uid: _generateUid()
        };
        _gItem.children = _gItem.children || [];
        _gItem.children.splice(0, 0, _gIndex);
        _gItem.src_path = _gPath;
        _gItem.index_meta = { weight: 100, headless: false, retitled: true, empty: true };
        var _gDir = isUp ? 'up' : 'down';
        var _gLoc = _gItem._uid ? _findNavItemInTree(_gItem._uid) : null;
        if (_gLoc) _updateInMemoryWeightFromDom(_gItem, _gDir);
        _gIndex.weight = _gItem.index_meta.weight;
        _gIndex._fm.weight = _gItem.index_meta.weight;
        var _gContent = '---\ntitle: ' + _fmSerialize(_gTitle) +
          '\nretitled: true\nempty: true\nweight: ' + _gItem.index_meta.weight + '\n---\n';
        _navBatchQueue.push({ type: 'create-page', path: _gPath, content: _gContent });
        if (_batchClaimedPaths) _batchClaimedPaths.add(_gPath);
        _addNavBadge({
          className: 'live-wysiwyg-nav-normalize-badge',
          text: 'Create index for "' + _gTitle + '"'
        });
      }
    }

    _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 (_ymlHasNavKey(_virtualMkdocsYml)) {
      _seedNavKeyMigrationWarning();
      _pushNavKeyItemWarning(item);
      return;
    }

    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 _autoCreatedIndex = null;
    if (item.type === 'section' && !_getItemSrcPath(item)) {
      var _aiFd = _getSectionFolderDir(item);
      if (_aiFd) {
        var _aiPath = _aiFd + '/index.md';
        var _aiTitle = item.title || _aiFd.split('/').pop().replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
        _autoCreatedIndex = {
          type: 'page', src_path: _aiPath, title: _aiTitle,
          isIndex: true, retitled: true, empty: true, weight: 100,
          _fm: { title: _aiTitle, retitled: true, empty: true, weight: 100 },
          _new: true, _uid: _generateUid()
        };
        item.children = item.children || [];
        item.children.splice(0, 0, _autoCreatedIndex);
        item.src_path = _aiPath;
        item.index_meta = { weight: 100, headless: false, retitled: true, empty: true };
      }
    }

    var moveDir = isUp ? 'up' : isDown ? 'down' : isLeft ? 'up' : 'down';
    var loc = item._uid ? _findNavItemInTree(item._uid) : null;
    if (loc) {
      _updateInMemoryWeightFromDom(item, moveDir);
    }

    if (_autoCreatedIndex) {
      var _aiW = item.index_meta.weight;
      _autoCreatedIndex.weight = _aiW;
      _autoCreatedIndex._fm.weight = _aiW;
      var _aiContent = '---\ntitle: ' + _fmSerialize(_autoCreatedIndex.title) +
        '\nretitled: true\nempty: true\nweight: ' + _aiW + '\n---\n';
      _navBatchQueue.push({ type: 'create-page', path: _autoCreatedIndex.src_path, content: _aiContent });
      if (_batchClaimedPaths) _batchClaimedPaths.add(_autoCreatedIndex.src_path);
      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge',
        text: 'Create index for "' + _autoCreatedIndex.title + '"'
      });
    }

    _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; } };
  }
  window._attachDialogKeyboard = _attachDialogKeyboard;

  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') {
            copy[k] = JSON.parse(JSON.stringify(item[k]));
          } else if (k === '_warnings' && Array.isArray(item[k])) {
            copy[k] = item[k].map(function (w) {
              var entry = { reason: w.reason, renames: w.renames || 0 };
              if (w._actionData != null) {
                entry._actionData = JSON.parse(JSON.stringify(w._actionData));
              }
              return entry;
            });
          } 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 (!_navCleanSnapshot) {
      _navCleanSnapshot = _takeNavSnapshot();
    }
    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);
    }
    _rebuildNavMenuForEditMode();
  }

  

  function _exitNavEditMode(restoreCursor) {
    if (!_navEditMode) return;
    _navEditMode = false;
    _clearNavFocus();
    _clearNavGroup();

    _navEditActionsEl = null;

    if (_navSidebarEl) {
      _navSidebarEl.classList.remove('live-wysiwyg-nav-edit-mode');
      _buildNavMenu(_navSidebarEl);
    }

    if (_navSnapshots.length >= 2 && _navSidebarEl) {
      _addNavEditActions(_navSidebarEl);
      _updateUndoRedoBtns();
    }

    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 _exitNavEditModeDestructive(restoreCursor) {
    if (!_navEditMode) return;
    _navEditMode = false;
    _clearNavFocus();
    _clearNavGroup();

    _navBatchQueue = [];
    if (_batchClaimedPaths) _batchClaimedPaths.clear();
    _batchRenamedPaths = {};
    _batchDeletedPaths = {};
    _navBadges = [];
    _navMigrationPending = false;
    _navTopWarnings = [];
    var diskIdx = _navDiskSnapshotIndex >= 0 ? _navDiskSnapshotIndex : 0;
    if (restoreCursor && _navSnapshots.length > 0 && _navSnapshots[diskIdx]) {
      _applySnapshotToGlobals(_navSnapshots[diskIdx]);
    }
    _navSnapshotIndex = (_navSnapshots.length > 0 && diskIdx < _navSnapshots.length) ? diskIdx : -1;
    _navCleanSnapshot = null;
    _persistNavSnapshots();

    if (_navEditActionsEl && _navEditActionsEl.parentNode) {
      _navEditActionsEl.parentNode.removeChild(_navEditActionsEl);
    }
    _navEditActionsEl = null;

    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.generatedMkdocsYml || '',
      snap.migrationPending ? '1' : '0',
      snap.pendingFolderDelete ? JSON.stringify(snap.pendingFolderDelete) : ''
    ];
    return _djb2Hash(parts.join('\x00'));
  }

  var _diskStateHashReplacer = function (key, value) {
    if (key === '_warnings' || key === '_deadLinks' || key === '_expanded' ||
        key === '_focused' || key === '_selected' || key === '_groupMode' ||
        key === '_uid' || key === '_indexContent' || key === 'setContent' ||
        key === 'url' || key === '_new' || key === '_renamed' || key === '_originalPath' ||
        key === 'isIndex' || key === 'empty' || key === 'retitled') return undefined;
    return value;
  };

  function _computeDiskStateHash(snap) {
    var parts = [
      JSON.stringify(snap.navData, _diskStateHashReplacer),
      snap.mkdocsYml || '',
      snap.generatedMkdocsYml || ''
    ];
    return _djb2Hash(parts.join('\x00'));
  }

  var _NAV_SNAPSHOT_CAP = 100;
  var _NAV_SNAPSHOT_LS_KEY = 'live_wysiwyg_nav_snapshots';

  function _stripSnapshotForStorage(snap) {
    var navData = _deepCloneNavData(snap.navData);
    (function strip(items) {
      for (var i = 0; i < items.length; i++) {
        if (items[i]._indexContent != null) items[i]._indexContent = null;
        if (items[i].setContent != null) items[i].setContent = null;
        if (items[i].children) strip(items[i].children);
      }
    })(navData);
    var copy = {};
    for (var k in snap) {
      if (snap.hasOwnProperty(k)) copy[k] = snap[k];
    }
    copy.navData = navData;
    return copy;
  }

  function _persistNavSnapshots() {
    try {
      var snaps = _navSnapshots;
      var idx = _navSnapshotIndex;
      var diskIdx = _navDiskSnapshotIndex;

      if (snaps.length > _NAV_SNAPSHOT_CAP) {
        var trimCount = snaps.length - _NAV_SNAPSHOT_CAP;
        if (trimCount > idx) trimCount = idx;
        if (trimCount > 0) {
          snaps = snaps.slice(trimCount);
          idx -= trimCount;
          diskIdx = Math.max(0, diskIdx - trimCount);
          _navSnapshots = snaps;
          _navSnapshotIndex = idx;
          _navDiskSnapshotIndex = diskIdx;
        }
      }

      var stripped = [];
      for (var i = 0; i < snaps.length; i++) {
        stripped.push(_stripSnapshotForStorage(snaps[i]));
      }
      var payload = JSON.stringify({
        snapshots: stripped,
        snapshotIndex: idx,
        diskSnapshotIndex: diskIdx,
        uidCounter: _uidCounter
      });
      localStorage.setItem(_NAV_SNAPSHOT_LS_KEY, payload);
    } catch (e) {
      if (e && e.name === 'QuotaExceededError') {
        _trimAndRetryPersist();
      }
    }
  }

  function _trimAndRetryPersist() {
    var minKeep = 10;
    var snaps = _navSnapshots;
    var idx = _navSnapshotIndex;
    var diskIdx = _navDiskSnapshotIndex;
    for (var attempt = 0; attempt < 5; attempt++) {
      if (snaps.length <= minKeep) break;
      var trimCount = Math.max(1, Math.floor(snaps.length / 4));
      if (trimCount > idx) trimCount = idx;
      if (trimCount <= 0) break;
      snaps = snaps.slice(trimCount);
      idx -= trimCount;
      diskIdx = Math.max(0, diskIdx - trimCount);
      try {
        var stripped = [];
        for (var i = 0; i < snaps.length; i++) {
          stripped.push(_stripSnapshotForStorage(snaps[i]));
        }
        var payload = JSON.stringify({
          snapshots: stripped,
          snapshotIndex: idx,
          diskSnapshotIndex: diskIdx,
          uidCounter: _uidCounter
        });
        localStorage.setItem(_NAV_SNAPSHOT_LS_KEY, payload);
        _navSnapshots = snaps;
        _navSnapshotIndex = idx;
        _navDiskSnapshotIndex = diskIdx;
        return;
      } catch (e2) {
        if (!e2 || e2.name !== 'QuotaExceededError') return;
      }
    }
    try { localStorage.removeItem(_NAV_SNAPSHOT_LS_KEY); } catch (_) {}
  }

  function _restoreNavSnapshots() {
    try {
      var raw = localStorage.getItem(_NAV_SNAPSHOT_LS_KEY);
      if (!raw) return null;
      var data = JSON.parse(raw);
      if (!data || !Array.isArray(data.snapshots) || data.snapshots.length === 0) return null;
      if (typeof data.snapshotIndex !== 'number' || typeof data.diskSnapshotIndex !== 'number') return null;
      if (data.snapshotIndex < 0 || data.snapshotIndex >= data.snapshots.length) return null;
      if (data.diskSnapshotIndex < 0 || data.diskSnapshotIndex >= data.snapshots.length) return null;
      return data;
    } catch (e) {
      return null;
    }
  }

  function _clearPersistedNavSnapshots() {
    try { localStorage.removeItem(_NAV_SNAPSHOT_LS_KEY); } catch (_) {}
  }

  function _snapshotHasSaveableChanges() {
    if (_navSnapshotIndex < 0) return false;
    var activeHash = _navSnapshots[_navSnapshotIndex].contentHash;
    if (_navCleanSnapshot && _navCleanSnapshot.contentHash !== activeHash) return true;
    if (_navDiskSnapshotIndex >= 0 && _navDiskSnapshotIndex < _navSnapshots.length) {
      return _navSnapshots[_navDiskSnapshotIndex].contentHash !== activeHash;
    }
    return false;
  }

  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,
      topWarnings: _navTopWarnings.slice(),
      mkdocsYml: _virtualMkdocsYml,
      generatedMkdocsYml: _virtualGeneratedMkdocsYml,
      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;
    _navTopWarnings = snapshot.topWarnings ? snapshot.topWarnings.slice() : [];
    _virtualMkdocsYml = snapshot.mkdocsYml != null ? snapshot.mkdocsYml : null;
    _virtualGeneratedMkdocsYml = snapshot.generatedMkdocsYml != null ? snapshot.generatedMkdocsYml : 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 _cloneSnapshot(snap) {
    var nwc = snap.navWeightConfig;
    return {
      navData: _deepCloneNavData(snap.navData),
      contentHash: snap.contentHash,
      batchQueue: snap.batchQueue.map(function (op) {
        var c = {}; for (var k in op) { if (op.hasOwnProperty(k)) c[k] = op[k]; } return c;
      }),
      badges: snap.badges.slice(),
      migrationPending: snap.migrationPending,
      topWarnings: snap.topWarnings ? snap.topWarnings.slice() : [],
      mkdocsYml: snap.mkdocsYml,
      generatedMkdocsYml: snap.generatedMkdocsYml,
      hasNavKey: snap.hasNavKey,
      navWeightConfig: nwc ? { installed: nwc.installed, enabled: nwc.enabled, default_page_weight: nwc.default_page_weight, frontmatter_defaults: nwc.frontmatter_defaults } : null
    };
  }

  function _commitNavSnapshot() {
    if (_navSnapshotIndex >= 0 && _navSnapshotIndex < _navDiskSnapshotIndex && _navDiskSnapshotIndex >= 0) {
      _navSnapshots.push(_cloneSnapshot(_navSnapshots[_navSnapshotIndex]));
      _navSnapshotIndex = _navSnapshots.length - 1;
    } else if (_navSnapshotIndex >= 0 && _navSnapshotIndex < _navSnapshots.length - 1) {
      _navSnapshots.splice(_navSnapshotIndex + 1);
    }
    _navSnapshots.push(_takeNavSnapshot());
    _navSnapshotIndex = _navSnapshots.length - 1;
    _renderNavFromSnapshot();
    _navAutoExitCheck();
    _persistNavSnapshots();
  }

  function _debouncedWarningSnapshot() {
    if (_warningSnapshotTimer) clearTimeout(_warningSnapshotTimer);
    _warningSnapshotTimer = setTimeout(function () {
      _warningSnapshotTimer = null;
      _commitNavSnapshot();
    }, 200);
  }

  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) {
      var hasDirtyContent = _navCleanSnapshot && snap.contentHash !== _navCleanSnapshot.contentHash;
      if (_snapshotHasNavEditState(snap) || hasDirtyContent) {
        _navCleanSnapshot = _takeNavSnapshot();
        _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();
    _persistNavSnapshots();
  }

  function _navRedo() {
    if (_navSnapshotIndex >= _navSnapshots.length - 1) return;
    _navSnapshotIndex++;
    _ensureNavEditModeForSnapshot();
    _renderNavFromSnapshot();
    _navAutoExitCheck();
    _persistNavSnapshots();
  }

  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;
  }

  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) {
        var entry = { path: srcPath, reasons: item._warnings.map(function (w) { return w.reason; }), renames: item._warnings[0].renames || 0 };
        var adMap = null;
        for (var w = 0; w < item._warnings.length; w++) {
          if (item._warnings[w]._actionData != null) {
            if (!adMap) adMap = {};
            adMap[item._warnings[w].reason] = item._warnings[w]._actionData;
          }
        }
        if (adMap) entry.actionData = adMap;
        result.push(entry);
      }
      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) {
          var wEntry = { reason: cp.reasons[r], renames: cp.renames || 0 };
          if (cp.actionData && cp.actionData[cp.reasons[r]] != null) {
            wEntry._actionData = cp.actionData[cp.reasons[r]];
          }
          item._warnings.push(wEntry);
        }
      }
    }
    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 _removeNavWarningReasonFromAll(items, reason) {
    items = items || (typeof liveWysiwygNavData !== 'undefined' ? liveWysiwygNavData : []);
    for (var i = 0; i < items.length; i++) {
      _removeNavWarningReason(items[i], reason);
      if (items[i].children) _removeNavWarningReasonFromAll(items[i].children, reason);
    }
  }

  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 diskIdx = _navDiskSnapshotIndex >= 0 ? _navDiskSnapshotIndex : 0;
    var origFlat = _flattenNavTree(_navSnapshots[diskIdx].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 _isNavSaveable() {
    return _navEditMode && _navSnapshotIndex >= 0 && _navDiskSnapshotIndex >= 0 &&
      _navSnapshotIndex !== _navDiskSnapshotIndex;
  }

  function _confirmNavSave() {
    _proceedWithNavSave();
  }

  function _proceedWithNavSave() {
    _executeNavBatchSave();
  }

  function _confirmNavDiscard() {
    var diskIdx = _navDiskSnapshotIndex >= 0 ? _navDiskSnapshotIndex : 0;
    if (diskIdx >= _navSnapshots.length) { _exitNavEditMode(true); return; }
    _navSnapshotIndex = diskIdx;
    _applySnapshotToGlobals(_navSnapshots[diskIdx]);
    _navCleanSnapshot = null;
    _persistNavSnapshots();
    _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;

      var newDesiredPath = _computeDesiredItemPath(uid, currFlat, _resolveDesiredDir) || newE.srcPath;

      if (newE.itemType === 'asset') {
        items.push({
          uid: uid, diskPath: null, desiredPath: newDesiredPath,
          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: newDesiredPath,
        itemType: 'page',
        desiredFm: newE.item._fm || {}, origFm: {},
        setContent: typeof newE.item.setContent === 'string' ? newE.item.setContent : null,
        createContent: createContent,
        isNew: true, isDeleted: false,
        isIndex: newDesiredPath.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 mkdocsYmlPluginOps = [];
    var mkdocsYmlOps = [];
    var origChanged = currentSnap.mkdocsYml != null && currentSnap.mkdocsYml !== originalSnap.mkdocsYml;
    var genChanged = currentSnap.generatedMkdocsYml != null && currentSnap.generatedMkdocsYml !== originalSnap.generatedMkdocsYml;
    if (origChanged || genChanged) {
      var origHasNav = _ymlHasNavKey(originalSnap.mkdocsYml);
      var currHasNav = _ymlHasNavKey(currentSnap.mkdocsYml);
      var navWasRemoved = origHasNav && !currHasNav;
      var hasOriginalPath = typeof liveWysiwygOriginalMkdocsYml === 'string' && liveWysiwygOriginalMkdocsYml;

      if (navWasRemoved) {
        var strippedOrig = _removeNavKeyFromYaml(originalSnap.mkdocsYml);
        if (strippedOrig !== currentSnap.mkdocsYml) {
          var intermediateOrig = _yamlDeepMerge(strippedOrig, currentSnap.mkdocsYml, originalSnap.mkdocsYml);
          if (intermediateOrig !== originalSnap.mkdocsYml) {
            if (hasOriginalPath) {
              mkdocsYmlPluginOps.push({ type: 'write-mkdocs-yml', path: liveWysiwygOriginalMkdocsYml, content: intermediateOrig });
              if (currentSnap.generatedMkdocsYml != null) {
                var strippedGenOrig = _removeNavKeyFromYaml(originalSnap.generatedMkdocsYml || '');
                var intermediateGen = _yamlDeepMerge(strippedGenOrig, currentSnap.generatedMkdocsYml, originalSnap.generatedMkdocsYml || '');
                mkdocsYmlPluginOps.push({ type: 'write-mkdocs-yml', path: '../mkdocs.yml', content: intermediateGen });
              }
            } else {
              mkdocsYmlPluginOps.push({ type: 'write-mkdocs-yml', path: '../mkdocs.yml', content: intermediateOrig });
            }
          }
        }
        if (hasOriginalPath) {
          mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: liveWysiwygOriginalMkdocsYml, content: currentSnap.mkdocsYml });
          if (currentSnap.generatedMkdocsYml != null) {
            mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: '../mkdocs.yml', content: currentSnap.generatedMkdocsYml });
          }
        } else {
          mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: '../mkdocs.yml', content: currentSnap.mkdocsYml });
        }
      } else {
        if (hasOriginalPath) {
          if (origChanged) {
            mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: liveWysiwygOriginalMkdocsYml, content: currentSnap.mkdocsYml });
          }
          if (genChanged) {
            mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: '../mkdocs.yml', content: currentSnap.generatedMkdocsYml });
          }
        } else {
          if (origChanged) {
            mkdocsYmlOps.push({ type: 'write-mkdocs-yml', path: '../mkdocs.yml', content: currentSnap.mkdocsYml });
          }
        }
      }
    }

    return {
      items: items,
      sections: sections,
      convertOps: convertOps,
      createFolderOps: createFolderOps,
      mkdocsYmlPluginOps: mkdocsYmlPluginOps,
      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 = {};

    console.log('[DEBUG-SAVE] dirMoves:', JSON.stringify(Object.keys(dirMoves).map(function(k) {
      return k + ' → ' + JSON.stringify(Object.keys(dirMoves[k]).map(function(dk) { return dk + '(' + dirMoves[k][dk].length + ')'; }));
    })));
    console.log('[DEBUG-SAVE] filesByDiskDir:', JSON.stringify(Object.keys(filesByDiskDir).map(function(k) {
      return k + '(' + filesByDiskDir[k].length + '): ' + filesByDiskDir[k].map(function(f) { return f.uid + ':' + f.diskPath + '→' + f.desiredPath; }).join(', ');
    })));

    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;
    });

    console.log('[DEBUG-SAVE] folderRenames:', JSON.stringify(folderRenames));
    console.log('[DEBUG-SAVE] coveredByFolderRename UIDs:', Object.keys(coveredByFolderRename));

    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 fmChanged = !_fmDeepEqual(dFm, oFm);
      if (fmChanged || 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 _finalBatch2 = [].concat(batch2DeleteFiles, batch2MoveFiles, convertOps, createFolderOps, batch2CreateFiles, batch2ContentMigration);
    return {
      batch1: batch1,
      batch2: _finalBatch2,
      mkdocsYmlPluginOps: desiredState.mkdocsYmlPluginOps || [],
      mkdocsYmlOps: desiredState.mkdocsYmlOps || [],
      precomputedRenames: precomputedRenames
    };
  }

  // ======================================================================
  // NAV MENU - Batch save execution
  // ======================================================================
  function _executeNavBatchSave() {
    var contentEl = document.querySelector('.live-wysiwyg-focus-content');
    if (!contentEl) { _exitNavEditModeDestructive(false); return; }

    if (_navSnapshots.length < 2 || _navSnapshotIndex < 0) {
      _exitNavEditModeDestructive(false);
      return;
    }

    var originalSnap = _navSnapshots[_navDiskSnapshotIndex >= 0 ? _navDiskSnapshotIndex : 0];
    var activeSnap = _navSnapshots[_navSnapshotIndex];

    var desiredState = _computeSavePlan(originalSnap, activeSnap);
    var plan = _planDiskOperations(desiredState);

    var orderedOps = [];
    if (plan.mkdocsYmlPluginOps.length) {
      orderedOps = orderedOps.concat(plan.mkdocsYmlPluginOps);
      orderedOps.push({ type: 'wait-for-rebuild' });
    }
    if (plan.mkdocsYmlOps.length || plan.batch1.length) {
      orderedOps = orderedOps.concat(plan.mkdocsYmlOps);
      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 currentPath = _getCurrentSrcPath();
    var reloadPath = currentPath;
    if (desiredState && desiredState.items) {
      for (var dsi = 0; dsi < desiredState.items.length; dsi++) {
        if (desiredState.items[dsi].diskPath === currentPath && !desiredState.items[dsi].isDeleted) {
          reloadPath = desiredState.items[dsi].desiredPath || currentPath;
          break;
        }
      }
    }

    if (activeSnap.migrationPending) {
      _setSetting('live_wysiwyg_migration_result', 'success');
      _setSetting('live_wysiwyg_migration_normalize', '1');
    }
    _persistWarningsFromSnapshot();

    console.log('[DEBUG-SAVE] desiredState items (diskPath→desiredPath):');
    (desiredState.items || []).forEach(function(it) {
      if (it.isDeleted) console.log('  DEL', it.uid, it.diskPath);
      else if (it.isNew) console.log('  NEW', it.uid, it.desiredPath);
      else if (it.diskPath !== it.desiredPath) console.log('  MOVE', it.uid, it.diskPath, '→', it.desiredPath);
    });
    console.log('[DEBUG-SAVE] desiredState sections:');
    (desiredState.sections || []).forEach(function(s) {
      console.log('  SEC', s.uid, 'disk:', s.diskDir, 'desired:', s.desiredDir, s.isNew ? 'NEW' : '', s.isDeleted ? 'DEL' : '');
    });
    console.log('[DEBUG-SAVE] orderedOps (' + orderedOps.length + '):');
    orderedOps.forEach(function(op, idx) {
      if (op.type === 'rename-folder') console.log('  ' + idx + ': rename-folder', op.oldFolder, '→', op.newFolder);
      else if (op.type === 'rename-page') console.log('  ' + idx + ': rename-page', op.oldPath, '→', op.newPath);
      else if (op.type === 'create-page') console.log('  ' + idx + ': create-page', op.path);
      else if (op.type === 'delete-page') console.log('  ' + idx + ': delete-page', op.path);
      else if (op.type === 'set-frontmatter') console.log('  ' + idx + ': set-frontmatter', op.src_path);
      else if (op.type === 'rewrite-links') console.log('  ' + idx + ': rewrite-links', Object.keys(op.renameMap || {}).length, 'renames');
      else console.log('  ' + idx + ':', op.type, op.path || op.folder || '');
    });
    console.log('[DEBUG-SAVE] precomputedRenames:', JSON.stringify(plan.precomputedRenames || {}));

    var savedSnapshotIndex = _navSnapshotIndex;
    _exitNavEditModeDestructive(false);
    _navSnapshotIndex = savedSnapshotIndex;
    _warningDirectMode = true;
    _runBatchOps(contentEl, orderedOps, reloadPath, { 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 === 'rename-folder') console.log('[DEBUG-EXEC] rename-folder', op.oldFolder, '→', op.newFolder);
    else if (op.type === 'rename-page') console.log('[DEBUG-EXEC] rename-page', op.oldPath, '→', op.newPath);
    else if (op.type === 'create-page') console.log('[DEBUG-EXEC] create-page', op.path);
    else if (op.type === 'delete-page') console.log('[DEBUG-EXEC] delete-page', op.path);
    else if (op.type === 'set-frontmatter') console.log('[DEBUG-EXEC] set-frontmatter', op.src_path);
    else console.log('[DEBUG-EXEC]', op.type, op.path || op.folder || op.oldPath || '');
    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);
    if (op.type === 'merge-mkdocs-yml') {
      return _wsGetContents(op.path).then(function (diskContent) {
        diskContent = diskContent || '';
        var merged = _yamlDeepMerge(op.base, op.source, diskContent);
        if (merged === diskContent) return;
        return _wsSetContents(op.path, merged);
      });
    }
    if (op.type === 'rewrite-heading-anchor') return _executeRewriteHeadingAnchorOp([op]);
    return Promise.resolve();
  }

  function _runBatchOps(contentEl, orderedOps, reloadPath, options) {
    options = options || {};
    if (!orderedOps.length) {
      _finishBatchSave(contentEl, [], reloadPath, 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...');
      return _waitForRebuildAndReconnect();
    }).then(function () {
      _finishBatchSave(statusContainer, failures, reloadPath, options);
    }).catch(function (err) {
      _finishBatchSave(statusContainer, failures, reloadPath, options);
    });
  }

  function _finishBatchSave(container, failures, reloadPath, 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');

    var keepTo = _navDiskSnapshotIndex >= 0 ? _navDiskSnapshotIndex + 1 : 1;
    _navSnapshots.splice(keepTo);
    _navSnapshotIndex = _navSnapshots.length - 1;
    _navDiskSnapshotIndex = _navSnapshotIndex;
    _persistNavSnapshots();

    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(reloadPath); }
      });
    } 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(reloadPath);
      }, 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(reloadPath) {
    _flushHistoryCapture();
    _persistContentHistory();
    var ta = document.querySelector('.live-edit-source');
    if (ta && reloadPath) {
      try {
        sessionStorage.setItem('live_wysiwyg_content_backup',
          JSON.stringify({ srcPath: reloadPath, content: ta.value }));
      } catch (e) { /* quota */ }
    }
    var ov = document.querySelector('.live-wysiwyg-nav-transition-overlay') || _showFullScreenTransition('Reloading...');
    _setSetting('live_wysiwyg_focus_nav', '1');
    _fadeOverlayToOpaque(ov, function () {
      var targetUrl = _srcPathToUrl(reloadPath || _getCurrentSrcPath());
      if (targetUrl === window.location.pathname || targetUrl === window.location.pathname + window.location.search) {
        window.location.reload();
      } else {
        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); });
    var nwCfg = typeof liveWysiwygNavWeightConfig !== 'undefined' ? liveWysiwygNavWeightConfig : {};
    var nwDefaults = (nwCfg.enabled && nwCfg.frontmatter_defaults) ? nwCfg.frontmatter_defaults : {};
    var defaultIndexWeight = nwDefaults.index_weight !== undefined ? nwDefaults.index_weight
      : (nwCfg.index_weight !== undefined ? nwCfg.index_weight : -10);
    var defaultPageWeight = nwDefaults.weight !== undefined ? nwDefaults.weight : 0;
    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
        : (isIndex ? defaultIndexWeight : defaultPageWeight);
      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 sectionWeight = op.syntheticSection && op.syntheticSection.index_meta
      ? op.syntheticSection.index_meta.weight : null;
    if (sectionWeight == null) sectionWeight = 100;
    var indexContent = '---\ntitle: ' + _fmSerialize(op.folderTitle || op.folderName) +
      '\nretitled: true\nempty: true\nweight: ' + sectionWeight + '\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 == null) {
      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 scRaw = scParsed.hasBlock ? scParsed.raw : '';
        var newFm = _buildFrontmatterFromFm(mergedFm, op.isIndex, effectiveOrig, scRaw);
        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 rawFmText = parsed.hasBlock ? parsed.raw : '';
        var newFm = _buildFrontmatterFromFm(op.fm, op.isIndex, op.origFm, rawFmText);
        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()) {
      _doFocusSaveBackground();
    }
    _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);
        enhanceMermaidBlocks(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();
      _checkPendingHeadingConflict(srcPath, markdown);
      _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');
      if (_getSetting('live_wysiwyg_show_hidden') !== '1') 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 _doFocusSaveBackground() {
    var path = _getCurrentSrcPath();
    if (!path) return;

    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 : '';
    }

    if (!content) return;

    var savedContent = content;
    _bgSavePendingRebuild = true;
    _getOrCreateBulkWs().then(function () {
      return _wsSetContents(path, savedContent);
    }).then(function () {
      if (wysiwygEditor && wysiwygEditor._resetPristineContent) {
        wysiwygEditor._resetPristineContent(savedContent);
      }
    }).catch(function (err) {
      _bgSavePendingRebuild = false;
      console.error('[bg-save] failed:', err && err.message || err);
      var overlay = document.querySelector('.live-wysiwyg-focus-overlay');
      if (overlay) {
        var msg = document.createElement('div');
        msg.className = 'live-wysiwyg-bg-save-error';
        msg.textContent = 'Save failed: ' + (err && err.message || 'unknown error');
        msg.style.cssText = 'position:fixed;top:12px;left:50%;transform:translateX(-50%);' +
          'background:#d9534f;color:#fff;padding:8px 18px;border-radius:6px;z-index:1000001;' +
          'font-size:14px;box-shadow:0 2px 8px rgba(0,0,0,0.3);';
        document.body.appendChild(msg);
        setTimeout(function () { if (msg.parentNode) msg.parentNode.removeChild(msg); }, 5000);
      }
    });
  }

  // ======================================================================
  // 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' && !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 ((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 _showSiteSettingsGear(gearBtn) {
    var existing = document.querySelector('.live-wysiwyg-nav-settings-dropdown');
    if (existing) {
      existing.parentNode.removeChild(existing);
      if (gearBtn.parentNode) gearBtn.parentNode.classList.remove('live-wysiwyg-nav-title-hover');
      return;
    }

    var dropdown = document.createElement('div');
    dropdown.className = 'live-wysiwyg-nav-settings-dropdown';

    var row = document.createElement('div');
    row.className = 'live-wysiwyg-nav-settings-row live-wysiwyg-nav-settings-inline';
    var span = document.createElement('span');
    span.textContent = 'Site Title';
    span.style.flexShrink = '0';
    row.appendChild(span);
    var input = document.createElement('input');
    input.type = 'text';
    var currentName = _extractSiteName(_virtualMkdocsYml) ||
      (document.title ? document.title.split(' - ').pop().trim() : '');
    input.value = currentName;
    row.appendChild(input);
    dropdown.appendChild(row);

    var hiddenRow = document.createElement('div');
    hiddenRow.className = 'live-wysiwyg-nav-settings-row';
    var hiddenLabel = document.createElement('label');
    var hiddenCb = document.createElement('input');
    hiddenCb.type = 'checkbox';
    hiddenCb.checked = _getSetting('live_wysiwyg_show_hidden') === '1';
    hiddenCb.addEventListener('change', function () {
      _setSetting('live_wysiwyg_show_hidden', this.checked ? '1' : '0');
      _renderNavFromSnapshot();
    });
    hiddenLabel.appendChild(hiddenCb);
    hiddenLabel.appendChild(document.createTextNode(' Show hidden files'));
    hiddenRow.appendChild(hiddenLabel);
    dropdown.appendChild(hiddenRow);

    var btnRow = document.createElement('div');
    btnRow.className = 'live-wysiwyg-nav-settings-btn-row';
    var applyBtn = document.createElement('button');
    applyBtn.className = 'live-wysiwyg-nav-settings-normalize-btn';
    applyBtn.textContent = 'Apply';
    applyBtn.style.cssText = 'background:var(--md-primary-fg-color,#4051b5)';
    btnRow.appendChild(applyBtn);
    dropdown.appendChild(btnRow);

    dropdown._gearBtn = gearBtn;

    function doApply() {
      var newName = input.value.trim();
      if (!newName) return;
      _prefetchMkdocsYml().then(function () {
        _applyYmlTransform(function (y) { return _replaceSiteName(y, newName); });
        if (!_navBadges.some(function (b) { return b.text === 'Change mkdocs.yml site_name'; })) {
          _addNavBadge({
            className: 'live-wysiwyg-nav-normalize-badge',
            text: 'Change mkdocs.yml site_name'
          });
        }
        _commitNavSnapshot();
        if (!_navEditMode) _enterNavEditMode();
      });
    }

    applyBtn.addEventListener('click', function () {
      doApply();
      dismissSiteGear();
    });

    var titleEl = gearBtn.parentNode;

    function dismissSiteGear() {
      if (dropdown.parentNode) dropdown.parentNode.removeChild(dropdown);
      document.removeEventListener('click', siteCloseHandler, true);
      if (titleEl) titleEl.classList.remove('live-wysiwyg-nav-title-hover');
    }

    if (titleEl) titleEl.classList.add('live-wysiwyg-nav-title-hover');

    _attachDialogKeyboard(dropdown, {
      category: 'form',
      trackDirty: true,
      onConfirm: function () {
        doApply();
        dismissSiteGear();
      },
      onDismiss: function () { dismissSiteGear(); },
      autoFocus: function () { input.focus(); input.select(); }
    });

    dropdown.style.position = 'fixed';
    dropdown.style.visibility = 'hidden';
    document.body.appendChild(dropdown);
    _repositionDropdown(dropdown);
    dropdown.style.visibility = '';
    _attachContainerExpandBehavior(dropdown, {
      onResize: function () { _repositionDropdown(dropdown); }
    });

    var siteCloseHandler = function (e) {
      if (!dropdown.contains(e.target) && e.target !== gearBtn) {
        dismissSiteGear();
      }
    };
    setTimeout(function () { document.addEventListener('click', siteCloseHandler, 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
      });
      _commitNavSnapshot();
    });
    });
  }

  // ======================================================================
  // NAV MENU - Snapshot-driven top warnings
  // ======================================================================
  var _navTopWarningActions = {
    'start-migration': function () { _startMigrationFlow(); },
    'apply-default-weight': function (warn) { _applyDefaultPageWeight(warn._suggestedWeight); },
    'apply-mermaid-config': function () {
      if (!_navEditMode) _enterNavEditMode();
      _applyMermaidConfigFix();
      _removeNavTopWarning('mermaid-config-missing');
      _removeNavWarningReasonFromAll(null, MERMAID_CONFIG_REASON);
      _commitNavSnapshot();
    }
  };

  var _navCautionActions = {};

  function _seedNavTopWarnings() {
    _navTopWarnings = [];
  }

  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;
  }

  function _seedNavKeyMigrationWarning() {
    if (_hasNavTopWarning('nav-key-blocks-reorder')) return;
    _navTopWarnings.push({
      id: 'nav-key-blocks-reorder',
      text: 'The nav key in mkdocs.yml defines a static navigation structure. File reordering is not available until you migrate to mkdocs-nav-weight. Use Content \u203a Migrate to mkdocs-nav-weight.',
      icon: 'warning',
      title: 'Reordering blocked by nav key',
      actionId: 'start-migration',
      actionText: 'Migrate to mkdocs-nav-weight'
    });
    _ensureNavUncollapsed();
    _commitNavSnapshot();
  }

  function _pushNavKeyItemWarning(item) {
    var itemLi = _navSidebarEl ? _navSidebarEl.querySelector('li[data-uid="' + item._uid + '"]') : null;
    if (!itemLi) return;
    var existing = itemLi.querySelector('.live-wysiwyg-nav-key-hint');
    if (existing) existing.remove();
    var hint = document.createElement('span');
    hint.className = 'live-wysiwyg-nav-key-hint';
    hint.textContent = 'Reordering blocked \u2014 see warning above';
    hint.style.cssText = 'position:absolute;top:-1.4em;left:0;right:0;font-size:.65rem;color:var(--md-accent-fg-color,#ff6d00);white-space:nowrap;pointer-events:none;opacity:1;transition:opacity .6s ease-out;z-index:1';
    itemLi.style.position = 'relative';
    itemLi.appendChild(hint);
    setTimeout(function () { hint.style.opacity = '0'; }, 1800);
    setTimeout(function () { if (hint.parentNode) hint.parentNode.removeChild(hint); }, 2500);
  }

  // ======================================================================
  // NAV MENU - Warning / tip popups
  // ======================================================================

  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);
  }

  // ── Asset Preview Popup ────────────────────────────────────────────

  var _activeAssetPreviewPopup = null;
  var _activeAssetPreviewCloseHandler = null;
  var _activeAssetLightbox = null;

  function _dismissAssetPreviewPopup() {
    if (_activeAssetPreviewPopup && _activeAssetPreviewPopup.parentNode) {
      _activeAssetPreviewPopup.parentNode.removeChild(_activeAssetPreviewPopup);
    }
    if (_activeAssetPreviewCloseHandler) {
      document.removeEventListener('click', _activeAssetPreviewCloseHandler, true);
      _activeAssetPreviewCloseHandler = null;
    }
    _activeAssetPreviewPopup = null;
  }

  function _showAssetPreviewPopup(anchorEl, item) {
    _dismissAssetPreviewPopup();
    _dismissAllDropdowns();

    var previewType = _getAssetPreviewType(item.extension);
    if (!previewType) return;

    var popup = document.createElement('div');
    popup.className = 'live-wysiwyg-asset-preview-popup';

    var header = document.createElement('div');
    header.className = 'live-wysiwyg-asset-preview-header';
    var titleSpan = document.createElement('span');
    titleSpan.className = 'live-wysiwyg-asset-preview-title';
    titleSpan.textContent = item.title || item.src_path;
    header.appendChild(titleSpan);
    var expandBtn = document.createElement('button');
    expandBtn.textContent = 'Expand';
    expandBtn.className = 'live-wysiwyg-asset-preview-expand';
    header.appendChild(expandBtn);
    popup.appendChild(header);

    var body = document.createElement('div');
    body.className = 'live-wysiwyg-asset-preview-body';

    var cachedTextContent = null;

    if (previewType === 'image') {
      var img = document.createElement('img');
      img.className = 'live-wysiwyg-asset-preview-img';
      img.alt = item.title || '';
      img.src = '/' + item.src_path;
      img.addEventListener('error', function () {
        img.style.display = 'none';
        var err = document.createElement('div');
        err.textContent = 'Failed to load image';
        err.style.cssText = 'color:var(--md-default-fg-color--light,#999);font-style:italic;padding:12px;';
        body.appendChild(err);
      });
      body.appendChild(img);
    } else {
      var pre = document.createElement('pre');
      pre.className = 'live-wysiwyg-asset-preview-text';
      pre.textContent = 'Loading\u2026';
      body.appendChild(pre);
      fetch('/' + item.src_path).then(function (r) {
        if (!r.ok) throw new Error(r.status);
        return r.text();
      }).then(function (text) {
        cachedTextContent = text;
        var lines = text.split('\n');
        pre.textContent = lines.slice(0, 15).join('\n');
        if (lines.length > 15) {
          pre.textContent += '\n\u2026';
        }
      }).catch(function () {
        pre.textContent = 'Failed to load file';
        pre.style.fontStyle = 'italic';
        pre.style.color = 'var(--md-default-fg-color--light,#999)';
      });
    }

    popup.appendChild(body);

    expandBtn.addEventListener('click', function () {
      _dismissAssetPreviewPopup();
      _showAssetLightbox(item, previewType, cachedTextContent);
    });

    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 = '';

    _activeAssetPreviewPopup = popup;

    _attachDialogKeyboard(popup, {
      category: 'informational',
      onDismiss: function () { _dismissAssetPreviewPopup(); },
      onConfirm: function () { _dismissAssetPreviewPopup(); expandBtn.click(); },
      autoFocus: expandBtn
    });

    var closeHandler = function (e) {
      if (!popup.contains(e.target) && e.target !== anchorEl && !anchorEl.contains(e.target)) {
        _dismissAssetPreviewPopup();
      }
    };
    _activeAssetPreviewCloseHandler = closeHandler;
    setTimeout(function () { document.addEventListener('click', closeHandler, true); }, 0);
  }

  function _dismissAssetLightbox() {
    if (_activeAssetLightbox && _activeAssetLightbox.parentNode) {
      _activeAssetLightbox.parentNode.removeChild(_activeAssetLightbox);
    }
    _activeAssetLightbox = null;
  }

  function _showAssetLightbox(item, previewType, cachedTextContent) {
    _dismissAssetLightbox();

    var backdrop = document.createElement('div');
    backdrop.className = 'live-wysiwyg-asset-lightbox';

    var panel = document.createElement('div');
    panel.className = 'live-wysiwyg-asset-lightbox-panel';

    var header = document.createElement('div');
    header.className = 'live-wysiwyg-asset-lightbox-header';
    var titleSpan = document.createElement('span');
    titleSpan.className = 'live-wysiwyg-asset-lightbox-title';
    titleSpan.textContent = item.title || item.src_path;
    header.appendChild(titleSpan);
    var closeBtn = document.createElement('button');
    closeBtn.className = 'live-wysiwyg-asset-lightbox-close';
    closeBtn.textContent = '\u00D7';
    closeBtn.title = 'Close';
    header.appendChild(closeBtn);
    panel.appendChild(header);

    var body = document.createElement('div');
    body.className = 'live-wysiwyg-asset-lightbox-body';

    if (previewType === 'image') {
      var img = document.createElement('img');
      img.className = 'live-wysiwyg-asset-lightbox-img';
      img.alt = item.title || '';
      img.src = '/' + item.src_path;
      img.addEventListener('error', function () {
        img.style.display = 'none';
        var err = document.createElement('div');
        err.textContent = 'Failed to load image';
        err.style.cssText = 'color:#ccc;font-style:italic;padding:24px;text-align:center;';
        body.appendChild(err);
      });
      body.appendChild(img);
    } else {
      var pre = document.createElement('pre');
      pre.className = 'live-wysiwyg-asset-lightbox-text';
      if (cachedTextContent !== null) {
        pre.textContent = cachedTextContent;
      } else {
        pre.textContent = 'Loading\u2026';
        fetch('/' + item.src_path).then(function (r) {
          if (!r.ok) throw new Error(r.status);
          return r.text();
        }).then(function (text) {
          pre.textContent = text;
        }).catch(function () {
          pre.textContent = 'Failed to load file';
          pre.style.fontStyle = 'italic';
          pre.style.color = '#ccc';
        });
      }
      body.appendChild(pre);
    }

    panel.appendChild(body);
    backdrop.appendChild(panel);

    closeBtn.addEventListener('click', function () { _dismissAssetLightbox(); });
    backdrop.addEventListener('click', function (e) {
      if (e.target === backdrop) _dismissAssetLightbox();
    });

    document.body.appendChild(backdrop);
    _activeAssetLightbox = backdrop;

    _attachDialogKeyboard(backdrop, {
      category: 'informational',
      onDismiss: function () { _dismissAssetLightbox(); },
      autoFocus: closeBtn
    });
  }

  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 _headingSlugify(text) {
    var value = text.replace(/[^\w\s-]/g, '').trim().toLowerCase();
    return value.replace(/[-\s]+/g, '-');
  }

  function _getHeadingTextFromElement(el) {
    return (el.textContent || '').replace(/\u00b6/g, '').trim();
  }

  function _findHeadingAtSelection(editableArea) {
    var sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) return null;
    var el = sel.getRangeAt(0).commonAncestorContainer;
    if (el.nodeType === 3) el = el.parentNode;
    while (el && el !== editableArea) {
      if (/^H[1-6]$/.test(el.nodeName)) return el;
      el = el.parentNode;
    }
    return null;
  }

  function _rewriteSamePageAnchorsWysiwyg(editableArea, oldSlug, newSlug) {
    if (!editableArea) return;
    var anchors = editableArea.querySelectorAll('a[href^="#"]');
    for (var i = 0; i < anchors.length; i++) {
      var href = anchors[i].getAttribute('href');
      if (href === '#' + oldSlug) {
        anchors[i].setAttribute('href', '#' + newSlug);
      }
    }
  }

  function _rewriteSamePageAnchorsMarkdown(markdownArea, oldSlug, newSlug) {
    if (!markdownArea) return;
    var content = markdownArea.value;
    var zones = _findExclusionZones(content);
    var escaped = oldSlug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    var re = new RegExp('(\\]\\(#)' + escaped + '(\\))', 'g');
    var replacements = [];
    var m;
    while ((m = re.exec(content)) !== null) {
      if (_isInExclusionZone(m.index, zones)) continue;
      var start = m.index + m[1].length;
      var end = start + oldSlug.length;
      replacements.push({ start: start, end: end, replacement: newSlug });
    }
    if (!replacements.length) return;
    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);
    }
    markdownArea.value = result;
  }

  function _stageHeadingMigration(srcPath, oldSlug, newSlug, oldText, newText) {
    if (wysiwygEditor && wysiwygEditor.editableArea && wysiwygEditor.currentMode === 'wysiwyg') {
      _rewriteSamePageAnchorsWysiwyg(wysiwygEditor.editableArea, oldSlug, newSlug);
    } else if (wysiwygEditor && wysiwygEditor.markdownArea && wysiwygEditor.currentMode === 'markdown') {
      _rewriteSamePageAnchorsMarkdown(wysiwygEditor.markdownArea, oldSlug, newSlug);
    }

    _navBatchQueue.push({
      type: 'rewrite-heading-anchor',
      pageSrcPath: srcPath,
      oldSlug: oldSlug,
      newSlug: newSlug
    });

    var displayText = newText.length > 40 ? newText.substring(0, 37) + '...' : newText;
    _addNavBadge({
      className: 'live-wysiwyg-nav-normalize-badge',
      text: 'Migrate all content links for \u201c' + displayText + '\u201d'
    });

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

  function _checkHeadingTrackerExit() {
    if (!_headingTracker.active) return;
    var currentText = '';
    if (_headingTracker.element) {
      currentText = _getHeadingTextFromElement(_headingTracker.element);
    } else if (_headingTracker.lineIndex >= 0 && wysiwygEditor && wysiwygEditor.markdownArea) {
      var lines = wysiwygEditor.markdownArea.value.split('\n');
      if (_headingTracker.lineIndex < lines.length) {
        var lineMatch = lines[_headingTracker.lineIndex].match(/^#{1,6}\s+(.+)$/);
        currentText = lineMatch ? lineMatch[1].replace(/\s*#+\s*$/, '').trim() : '';
      }
    }
    var newSlug = _headingSlugify(currentText);
    var oldSlug = _headingTracker.originalSlug;
    if (oldSlug && newSlug && newSlug !== oldSlug) {
      _stageHeadingMigration(
        _headingTracker.srcPath, oldSlug, newSlug,
        _headingTracker.originalText, currentText
      );
    }
    _headingTracker.active = false;
    _headingTracker.element = null;
    _headingTracker.lineIndex = -1;
    _headingTracker.originalText = '';
    _headingTracker.originalSlug = '';
    _headingTracker.srcPath = '';
  }

  function _updateHeadingTrackerWysiwyg(editableArea) {
    var heading = _findHeadingAtSelection(editableArea);
    if (heading) {
      if (_headingTracker.active && _headingTracker.element === heading) return;
      if (_headingTracker.active) _checkHeadingTrackerExit();
      var text = _getHeadingTextFromElement(heading);
      var slug = _headingSlugify(text);
      if (slug) {
        _headingTracker.active = true;
        _headingTracker.element = heading;
        _headingTracker.lineIndex = -1;
        _headingTracker.originalText = text;
        _headingTracker.originalSlug = slug;
        _headingTracker.srcPath = _getCurrentSrcPath();
      }
    } else if (_headingTracker.active && _headingTracker.element) {
      _checkHeadingTrackerExit();
    }
  }

  function _getMarkdownCaretLineIndex(markdownArea) {
    var pos = markdownArea.selectionStart;
    var text = markdownArea.value.substring(0, pos);
    return text.split('\n').length - 1;
  }

  function _updateHeadingTrackerMarkdown(markdownArea) {
    var lineIdx = _getMarkdownCaretLineIndex(markdownArea);
    var lines = markdownArea.value.split('\n');
    var line = lineIdx < lines.length ? lines[lineIdx] : '';
    var headingMatch = line.match(/^#{1,6}\s+(.+)$/);

    if (headingMatch) {
      var text = headingMatch[1].replace(/\s*#+\s*$/, '').trim();
      if (_headingTracker.active && _headingTracker.lineIndex === lineIdx) return;
      if (_headingTracker.active) _checkHeadingTrackerExit();
      var slug = _headingSlugify(text);
      if (slug) {
        _headingTracker.active = true;
        _headingTracker.element = null;
        _headingTracker.lineIndex = lineIdx;
        _headingTracker.originalText = text;
        _headingTracker.originalSlug = slug;
        _headingTracker.srcPath = _getCurrentSrcPath();
      }
    } else if (_headingTracker.active && _headingTracker.lineIndex >= 0) {
      _checkHeadingTrackerExit();
    }
  }

  function _checkHeadingMigrationBeforeNavigate() {
    if (!_headingTracker.active) return;
    _checkHeadingTrackerExit();
  }

  function _resolveTargetWithFallbacks(pageDir, pathPart) {
    var allPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
    var knownPaths = {};
    for (var k = 0; k < allPaths.length; k++) knownPaths[allPaths[k]] = true;
    var absTarget = _resolvePath(pageDir, pathPart);
    if (absTarget === null) return null;
    if (knownPaths[absTarget]) return absTarget;
    if (knownPaths[absTarget + '.md']) return absTarget + '.md';
    if (knownPaths[absTarget + '/index.md']) return absTarget + '/index.md';
    var withoutMd = absTarget.replace(/\.md$/, '');
    if (withoutMd !== absTarget && knownPaths[withoutMd]) return withoutMd;
    return absTarget;
  }

  function _coalesceHeadingAnchorOps(ops) {
    var byPage = {};
    for (var i = 0; i < ops.length; i++) {
      var op = ops[i];
      if (op.type !== 'rewrite-heading-anchor') continue;
      var key = op.pageSrcPath;
      if (!byPage[key]) byPage[key] = {};
      var found = false;
      for (var old in byPage[key]) {
        if (byPage[key][old] === op.oldSlug) {
          byPage[key][old] = op.newSlug;
          found = true;
          break;
        }
      }
      if (!found) {
        byPage[key][op.oldSlug] = op.newSlug;
      }
    }
    return byPage;
  }

  function _rewriteHeadingAnchorsInPage(content, pageSrcPath, anchorMap, pageSrc) {
    var pageDir = _getDir(pageSrc);
    var zones = _findExclusionZones(content);
    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) {
        if (_isInExclusionZone(m.index, zones)) continue;
        var fullTarget = m[pat.group];
        if (!fullTarget || fullTarget.indexOf('http://') === 0 || fullTarget.indexOf('https://') === 0 ||
            fullTarget.indexOf('mailto:') === 0 || fullTarget.indexOf('data:') === 0) continue;
        if (fullTarget.charAt(0) === '#') continue;
        var anchorIdx = fullTarget.indexOf('#');
        if (anchorIdx < 0) continue;
        var pathPart = fullTarget.substring(0, anchorIdx);
        var afterHash = fullTarget.substring(anchorIdx + 1);
        var queryInFrag = afterHash.indexOf('?');
        var fragment = queryInFrag >= 0 ? afterHash.substring(0, queryInFrag) : afterHash;
        if (!pathPart || !fragment) continue;
        var decoded = decodeURIComponent(pathPart);
        var resolved = _resolveTargetWithFallbacks(pageDir, decoded);
        if (resolved === null) continue;
        var resolvedBase = resolved.replace(/\.md$/, '');
        var targetBase = pageSrcPath.replace(/\.md$/, '');
        var isIndex = pageSrcPath.endsWith('/index.md') || pageSrcPath === 'index.md';
        var targetDir = isIndex ? _getDir(pageSrcPath) : null;
        var match = (resolved === pageSrcPath || resolvedBase === targetBase);
        if (!match && isIndex && targetDir !== null) {
          var resolvedClean = resolved.replace(/\/$/, '');
          match = (resolvedClean === targetDir || resolved === targetDir + '/');
        }
        if (!match) continue;
        if (anchorMap[fragment]) {
          var fragStart = m.index + m[0].lastIndexOf('#' + fragment) + 1;
          replacements.push({ start: fragStart, end: fragStart + fragment.length, replacement: anchorMap[fragment] });
        }
      }
    }
    if (!replacements.length) return content;
    replacements.sort(function (a, b) { return b.start - a.start; });
    var seen = {};
    var result = content;
    for (var i = 0; i < replacements.length; i++) {
      var r = replacements[i];
      var rk = r.start + ':' + r.end;
      if (seen[rk]) continue;
      seen[rk] = true;
      result = result.substring(0, r.start) + r.replacement + result.substring(r.end);
    }
    return result;
  }

  function _executeRewriteHeadingAnchorOp(anchorOps) {
    var coalesced = _coalesceHeadingAnchorOps(anchorOps);
    var allPaths = typeof liveWysiwygAllMdSrcPaths !== 'undefined' ? liveWysiwygAllMdSrcPaths : [];
    var promises = [];
    var pageKeys = Object.keys(coalesced);

    function processPage(idx) {
      if (idx >= allPaths.length) return Promise.resolve();
      var pageSrc = allPaths[idx];
      if (_batchDeletedPaths && _batchDeletedPaths[pageSrc]) return processPage(idx + 1);

      return _wsGetContents(pageSrc).then(function (content) {
        if (!content) return processPage(idx + 1);
        var changed = false;
        for (var pk = 0; pk < pageKeys.length; pk++) {
          var targetPath = pageKeys[pk];
          var resolvedTarget = _resolveChainedRename ? _resolveChainedRename(targetPath) : targetPath;
          if (pageSrc === resolvedTarget) continue;
          var anchorMap = coalesced[targetPath];
          var newContent = _rewriteHeadingAnchorsInPage(content, resolvedTarget, anchorMap, pageSrc);
          if (newContent !== content) {
            content = newContent;
            changed = true;
          }
        }
        if (changed) {
          return _wsSetContents(pageSrc, content).then(function () {
            return processPage(idx + 1);
          });
        }
        return processPage(idx + 1);
      }).catch(function () { return processPage(idx + 1); });
    }

    return processPage(0);
  }

  function _checkPendingHeadingConflict(srcPath, markdown) {
    if (!_navBatchQueue || !_navBatchQueue.length) return;
    var anchorOps = [];
    for (var i = 0; i < _navBatchQueue.length; i++) {
      if (_navBatchQueue[i].type === 'rewrite-heading-anchor') anchorOps.push(_navBatchQueue[i]);
    }
    if (!anchorOps.length) return;
    var pageDir = _getDir(srcPath);
    var zones = _findExclusionZones(markdown);
    var linkRe = /(?<!!)\[([^\]]*)\]\(([^)]+)\)/g;
    var m;
    var hasConflict = false;
    while ((m = linkRe.exec(markdown)) !== null) {
      if (_isInExclusionZone(m.index, zones)) continue;
      var target = m[2];
      if (!target || target.charAt(0) === '#') continue;
      var anchorIdx = target.indexOf('#');
      if (anchorIdx < 0) continue;
      var pathPart = target.substring(0, anchorIdx);
      var afterHash = target.substring(anchorIdx + 1);
      var qIdx = afterHash.indexOf('?');
      var fragment = qIdx >= 0 ? afterHash.substring(0, qIdx) : afterHash;
      if (!pathPart || !fragment) continue;
      var resolved = _resolveTargetWithFallbacks(pageDir, pathPart);
      if (resolved === null) continue;
      for (var a = 0; a < anchorOps.length; a++) {
        var op = anchorOps[a];
        if (op.pageSrcPath === srcPath) continue;
        var resolvedBase = resolved.replace(/\.md$/, '');
        var targetBase = op.pageSrcPath.replace(/\.md$/, '');
        if ((resolved === op.pageSrcPath || resolvedBase === targetBase) && fragment === op.oldSlug) {
          hasConflict = true;
          break;
        }
      }
      if (hasConflict) break;
    }
    if (!hasConflict) return;

    var dialogOverlay = document.createElement('div');
    dialogOverlay.className = 'live-wysiwyg-dialog-overlay';
    var content = document.createElement('div');
    content.className = 'live-wysiwyg-dialog-content';
    var title = document.createElement('h3');
    title.textContent = 'Heading Rewrite Pending';
    title.style.margin = '0 0 .8rem';
    content.appendChild(title);
    var msg = document.createElement('p');
    msg.style.cssText = 'margin:0 0 .6rem;line-height:1.5';
    msg.textContent = 'This page contains links to a heading that was renamed. The heading anchor rewrite has not been saved yet.';
    content.appendChild(msg);
    var msg2 = document.createElement('p');
    msg2.style.cssText = 'margin:0 0 1rem;line-height:1.5';
    msg2.textContent = 'Editing this page may create conflicts with the pending migration. Please go back and save the nav menu to complete the heading rewrite first.';
    content.appendChild(msg2);
    var actions = document.createElement('div');
    actions.className = 'live-wysiwyg-dialog-actions';
    var goBackBtn = document.createElement('button');
    goBackBtn.className = 'live-wysiwyg-dialog-confirm';
    goBackBtn.textContent = 'Go Back';
    goBackBtn.addEventListener('click', function () {
      if (dialogOverlay.parentNode) dialogOverlay.parentNode.removeChild(dialogOverlay);
      history.back();
    });
    actions.appendChild(goBackBtn);
    content.appendChild(actions);
    dialogOverlay.appendChild(content);
    document.body.appendChild(dialogOverlay);
    _attachDialogKeyboard(dialogOverlay, {
      category: 'informational',
      onDismiss: function () {
        if (dialogOverlay.parentNode) dialogOverlay.parentNode.removeChild(dialogOverlay);
      }
    });
  }

  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 && items[i].type !== 'section') 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 && items[i].type !== 'section') 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++) {
      _applyYmlTransform(ymlTransforms[vt]);
    }

    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 : {};

      // Phase 0: Hard prerequisite — pip install check
      if (!cfg.installed) {
        _showNavDialogHtml(
          '<p style="margin:0 0 12px"><strong>mkdocs-nav-weight is not installed.</strong></p>' +
          '<p style="margin:0 0 8px">Install it first:</p>' +
          '<pre style="margin:4px 0 12px;padding:8px;background:rgba(0,0,0,.06);border-radius:4px;font-size:.83rem">pip install mkdocs-nav-weight</pre>' +
          '<p style="margin:0;font-size:.83rem">Migrating without this package causes mkdocs to crash on rebuild.</p>',
          [{ text: 'OK', value: 'ok' }]
        );
        return;
      }

      // Phase 0b: Already-active check
      var hasNavKey = _ymlHasNavKey(_virtualMkdocsYml);
      if (cfg.enabled && !hasNavKey) {
        _showNavDialog('Nav weights are already active. No migration needed.', [{ text: 'OK', value: 'ok' }]);
        return;
      }

      var pluginJustAdded = !cfg.enabled;

      if (hasNavKey) {
        _startMigrationFlowNavKey(cfg, pluginJustAdded);
      } else {
        _startMigrationFlowAlphabetical(cfg, pluginJustAdded);
      }
    });
  }

  function _startMigrationFlowNavKey(cfg, pluginJustAdded) {
    // Phase 1: Parse nav structure, check for duplicates
    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>';
      _showNavDialogHtml(html, [{ text: 'OK', value: 'ok' }]);
      return;
    }

    // Phase 2: Build link index (scan claimed index content)
    var tree = _migrationComputeTargetTree(navStructure);
    _scanClaimedIndexContent(tree.claimedIndexPaths).then(function () {

    // Phase 3/4/5/6/7 summary computation
    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');
      _removeNavTopWarning('nav-key-blocks-reorder');
      _addNavBadge({
        className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-migration-badge',
        text: 'Pending mkdocs.yml nav migration'
      });
      _commitNavSnapshot();
    });
    }); // _scanClaimedIndexContent.then
  }

  function _startMigrationFlowAlphabetical(cfg, pluginJustAdded) {
    // Phase 2: Scan content-bearing section indexes for splitting
    var splitCandidates = [];
    var fmMap = typeof liveWysiwygFrontmatterMap !== 'undefined' ? liveWysiwygFrontmatterMap : {};

    (function scanSections(items) {
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.type === 'section' && item.children) {
          var indexPage = null;
          for (var c = 0; c < item.children.length; c++) {
            if (item.children[c].type === 'page' && item.children[c].isIndex) {
              indexPage = item.children[c]; break;
            }
          }
          if (!indexPage && item.src_path) {
            indexPage = item;
          }
          if (indexPage && indexPage._indexContent) {
            splitCandidates.push({ section: item, indexPage: indexPage });
          } else if (indexPage && indexPage.src_path) {
            var pageFm = (indexPage._fm) ? indexPage._fm
              : (fmMap[indexPage.src_path] ? fmMap[indexPage.src_path] : null);
            if (pageFm && pageFm.retitled && pageFm.empty) {
              // Already a thin index, skip
            } else {
              splitCandidates.push({ section: item, indexPage: indexPage, needsContentFetch: true });
            }
          }
          scanSections(item.children);
        }
      }
    })(liveWysiwygNavData);

    var contentFetchPromises = [];
    for (var fc = 0; fc < splitCandidates.length; fc++) {
      if (splitCandidates[fc].needsContentFetch) {
        (function (cand) {
          contentFetchPromises.push(
            _wsGetContents(cand.indexPage.src_path).then(function (content) {
              if (content) {
                var bodyContent = _stripFrontmatter(content);
                if (bodyContent && bodyContent.trim()) {
                  cand.indexPage._indexContent = bodyContent;
                } else {
                  cand.skip = true;
                }
              } else {
                cand.skip = true;
              }
            }).catch(function () { cand.skip = true; })
          );
        })(splitCandidates[fc]);
      }
    }

    Promise.all(contentFetchPromises).then(function () {
      splitCandidates = splitCandidates.filter(function (c) { return !c.skip; });

      // Count all pages for weight assignment
      var totalPages = 0;
      (function countPages(items) {
        for (var i = 0; i < items.length; i++) {
          if (items[i].type === 'page') totalPages++;
          if (items[i].children) countPages(items[i].children);
        }
      })(liveWysiwygNavData);

      var summaryHtml = '<p style="margin:0 0 12px">This will enable mkdocs-nav-weight and assign frontmatter titles and weights to all pages based on their current filesystem order.</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>Enable <code>mkdocs-nav-weight</code> plugin in mkdocs.yml</li>';
      if (splitCandidates.length) summaryHtml += '<li>Split ' + splitCandidates.length + ' content-bearing index.md file' + (splitCandidates.length > 1 ? 's' : '') + '</li>';
      summaryHtml += '<li>Set titles and weights on ' + totalPages + ' page' + (totalPages > 1 ? 's' : '') + '</li>';
      summaryHtml += '<li>All pages remain visible (no headless marking)</li>';
      summaryHtml += '<li>No files will be moved</li>';
      summaryHtml += '</ul>';
      summaryHtml += '<p style="margin:0 0 12px;font-size:.83rem">Would you like to stage this migration?</p>';

      _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();
        _applyAlphabeticalMigration(splitCandidates);
        _navMigrationPending = true;
        _addNavBadge({
          className: 'live-wysiwyg-nav-normalize-badge live-wysiwyg-nav-migration-badge',
          text: 'Pending alphabetical migration to mkdocs-nav-weight'
        });
        _commitNavSnapshot();
      });
    });
  }

  function _applyAlphabeticalMigration(splitCandidates) {
    var fmMap = typeof liveWysiwygFrontmatterMap !== 'undefined' ? liveWysiwygFrontmatterMap : {};
    _navBatchQueue = [];

    // Phase 3: Split content-bearing section indexes
    for (var sc = 0; sc < splitCandidates.length; sc++) {
      var cand = splitCandidates[sc];
      var section = cand.section;
      var indexPage = cand.indexPage;
      var folderDir = _getSectionFolderDir(section);
      if (!folderDir) continue;

      var contentTitle = indexPage.title || section.title || folderDir.split('/').pop();
      var contentFilename = _generateFilename(contentTitle);
      var contentPath = folderDir + '/' + contentFilename;

      var splitFm = (indexPage._fm) ? Object.assign({}, indexPage._fm)
        : (fmMap[indexPage.src_path] ? Object.assign({}, fmMap[indexPage.src_path]) : {});
      splitFm.title = contentTitle;
      delete splitFm.retitled;
      delete splitFm.empty;

      var splitItem = {
        type: 'page',
        src_path: contentPath,
        title: contentTitle,
        _fm: splitFm,
        setContent: indexPage._indexContent,
        _new: true,
        _uid: _generateUid()
      };

      var insertIdx = -1;
      for (var ci = 0; ci < section.children.length; ci++) {
        if (section.children[ci] === indexPage || (section.children[ci].isIndex && section.children[ci].src_path === indexPage.src_path)) {
          insertIdx = ci + 1;
          break;
        }
      }
      if (insertIdx >= 0) {
        section.children.splice(insertIdx, 0, splitItem);
      } else {
        section.children.push(splitItem);
      }

      var thinFm = { title: section.title || contentTitle, empty: true, retitled: true };
      indexPage._fm = thinFm;
      indexPage.retitled = true;
      indexPage.empty = true;
      indexPage._indexContent = null;
    }

    // Phase 6: Assign titles and weights to all pages
    (function assignWeights(items) {
      var weightCounter = 100;
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.type === 'page') {
          if (!item._fm) {
            item._fm = fmMap[item.src_path] ? Object.assign({}, fmMap[item.src_path]) : {};
          }
          if (!item._fm.title) {
            item._fm.title = item.title || '';
          }
          if (!item.title) {
            item.title = item._fm.title;
          }
          if (!_isRootIndex(item)) {
            item._fm.weight = weightCounter;
            item.weight = weightCounter;
            weightCounter += 100;
          }
        } else if (item.type === 'section') {
          var indexChild = null;
          if (item.children) {
            for (var ci = 0; ci < item.children.length; ci++) {
              if (item.children[ci].type === 'page' && item.children[ci].isIndex) {
                indexChild = item.children[ci]; break;
              }
            }
          }
          if (indexChild) {
            if (!indexChild._fm) {
              indexChild._fm = fmMap[indexChild.src_path] ? Object.assign({}, fmMap[indexChild.src_path]) : {};
            }
            indexChild._fm.weight = weightCounter;
            indexChild.weight = weightCounter;
            if (!item.index_meta) item.index_meta = {};
            item.index_meta.weight = weightCounter;
          }
          weightCounter += 100;
          if (item.children) assignWeights(item.children);
        }
      }
    })(liveWysiwygNavData);
  }

  function _stripFrontmatter(content) {
    if (!content || typeof content !== 'string') return content;
    var match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
    if (match) return content.substring(match[0].length);
    return content;
  }

  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
      };
    }
    _applyYmlTransform(_insertNavWeightEntry);
    _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) {
    _applyYmlTransform(function (y) { return _replaceDefaultPageWeight(y, 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;
  }

  function _replaceSiteName(yml, newName) {
    var re = /^(site_name\s*:\s*).*$/m;
    if (re.test(yml)) return yml.replace(re, '$1' + newName);
    return 'site_name: ' + newName + '\n' + yml;
  }

  function _extractSiteName(yml) {
    if (!yml) return '';
    var m = yml.match(/^site_name\s*:\s*(.+)$/m);
    return m ? m[1].trim() : '';
  }

  // ======================================================================
  // 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'];
        var result = { path: entry.path || '', reasons: reasons, renames: entry.renames || 0 };
        if (entry.actionData && typeof entry.actionData === 'object') result.actionData = entry.actionData;
        return result;
      });
    } catch (e) { return []; }
  }

  function _setCautionPages(pages) {
    try { localStorage.setItem('live_wysiwyg_caution_pages', JSON.stringify(pages)); } catch (e) { /* private browsing */ }
  }

  function _addCautionPage(srcPath, reason, actionData) {
    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);
            if (actionData != null) {
              if (!pages[i].actionData) pages[i].actionData = {};
              pages[i].actionData[msg] = actionData;
            }
            _setCautionPages(pages);
            _ensureNavUncollapsed();
          }
          return;
        }
      }
      var entry = { path: actualPath, reasons: [msg], renames: 0 };
      if (actionData != null) entry.actionData = {};
      if (actionData != null) entry.actionData[msg] = actionData;
      pages.push(entry);
      _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;
    }
    var warningEntry = { reason: msg, renames: 0 };
    if (actionData != null) warningEntry._actionData = actionData;
    item._warnings.push(warningEntry);
    if (!_suppressWarningSnapshot) _debouncedWarningSnapshot();
    _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 hasResolveAll = totalCautionItems > 1;

    var actionBtns = [];
    reasons.forEach(function (reason) {
      var actionDef = _navCautionActions[reason];
      if (!actionDef) return;
      var warningEntry = null;
      for (var w = 0; w < (navItem._warnings || []).length; w++) {
        if (navItem._warnings[w].reason === reason) { warningEntry = navItem._warnings[w]; break; }
      }
      var fixBtn = document.createElement('button');
      fixBtn.textContent = actionDef.text;
      if (actionDef.primary) fixBtn.className = 'live-wysiwyg-nav-popup-primary';
      else if (actionDef.style) fixBtn.style.cssText = actionDef.style;
      fixBtn.addEventListener('click', function () {
        if (popup.parentNode) popup.parentNode.removeChild(popup);
        actionDef.handler(navItem, warningEntry);
      });
      actionBtns.push(fixBtn);
    });

    if (actionBtns.length && hasResolveAll) {
      var actionRow = document.createElement('div');
      actionRow.style.marginTop = '8px';
      actionBtns.forEach(function (b) { actionRow.appendChild(b); });
      popup.appendChild(actionRow);
    }

    var cautionBtnRow = document.createElement('div');
    cautionBtnRow.style.marginTop = '8px';
    var resolveBtn = document.createElement('button');
    resolveBtn.textContent = 'Resolve';
    resolveBtn.addEventListener('click', function () {
      popup.parentNode.removeChild(popup);
      delete navItem._warnings;
      delete navItem._deadLinks;
      _hideDeadLinkPanel();
      _commitNavSnapshot();
    });
    cautionBtnRow.appendChild(resolveBtn);

    if (actionBtns.length && !hasResolveAll) {
      actionBtns.forEach(function (b) { cautionBtnRow.appendChild(b); });
    }

    if (hasResolveAll) {
      var resolveAllBtn = document.createElement('button');
      resolveAllBtn.textContent = 'Resolve All';
      resolveAllBtn.addEventListener('click', function () {
        popup.parentNode.removeChild(popup);
        _clearAllNavWarnings();
        _hideDeadLinkPanel();
        _commitNavSnapshot();
      });
      cautionBtnRow.appendChild(resolveAllBtn);
    }
    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) _debouncedWarningSnapshot();
  }

  // ======================================================================
  // 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) {
              var fragment = hashIdx >= 0 ? target.substring(hashIdx + 1).split('?')[0] : '';
              allChecks.push({ type: 'internal', from: path, target: pathPart, fragment: fragment || undefined });
              checkMeta.push({ srcPath: path, text: text, target: fragment ? pathPart + '#' + fragment : pathPart, kind: 'internal', fragment: fragment || undefined });
            }
          }
        }
        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, error: result.error || ''
        });
      }
    }

    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, error: dl.internal[i].error || '' });
      }
    }
    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 = link.error && link.error.indexOf('Anchor') === 0 ? link.error : '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', 'live_wysiwyg_autolaunch');
    addCheckbox('Unicode emoji', 'live_wysiwyg_unicode_emoji');

    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 migrateSep = document.createElement('hr');
    migrateSep.style.cssText = 'border:none;border-top:1px solid rgba(128,128,128,.3);margin:4px 0';
    submenu.appendChild(migrateSep);

    var migrateBtn = document.createElement('button');
    migrateBtn.textContent = 'Migrate to mkdocs-nav-weight';
    migrateBtn.addEventListener('click', function () {
      _closeSubmenu();
      _startMigrationFlow();
    });
    submenu.appendChild(migrateBtn);

    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);

      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' : '');

      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 (bodyBg && bodyBgRgb) {
      colors['--md-code-bg-color'] = _isLight(bodyBgRgb)
        ? _darken(bodyBgRgb, 0.04) : _lighten(bodyBgRgb, 0.06);
    }
    if (bodyFg && bodyFgRgb) {
      colors['--md-code-fg-color'] = bodyFg;
    }

    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() {
    var css = '' +
      ':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 .3s 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:var(--_toolbar-h,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-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;' +
        'overflow:hidden;' +
      '}' +
      '.live-wysiwyg-focus-drawer-toolbar-wrap.focus-markdown-mode{' +
        'display:none;' +
      '}' +

      '.live-wysiwyg-focus-main{' +
        'flex:1;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;' +
      '}' +
      '.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);' +
        'transition:min-height .3s ease-in-out;' +
        '--_nav-extend:clamp(0px,(100vw - 61rem) / 2 - 2em,10rem);' +
        '--_toc-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 .2rem 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:calc(12.1rem + var(--_toc-extend,0px));flex-shrink:0;align-self:flex-start;' +
        'margin-right:calc(-1 * var(--_toc-extend,0px));' +
        'position:sticky;top:0;padding:1.2rem 0;' +
        'font-size:.7rem;line-height:1.3;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 .6rem .4rem;' +
      '}' +
      '.live-wysiwyg-focus-toc .md-nav__item{padding:0;}' +
      '.live-wysiwyg-focus-toc .md-nav__link{' +
        'display:block;padding:0 .6rem;margin-top:.625em;' +
        'color:var(--md-default-fg-color--light,#999);' +
        'text-decoration:none;cursor:pointer;position:relative;' +
        '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;' +
      '}' +
      '.live-wysiwyg-toc-copy-btn{' +
        'background:none;border:none;cursor:pointer;padding:0;line-height:1;' +
        'position:absolute;left:calc(.6rem - 13px);top:50%;transform:translateY(-50%);' +
        'color:inherit;opacity:0;pointer-events:none;transition:opacity .15s;' +
        'display:flex;align-items:center;' +
      '}' +
      '.live-wysiwyg-focus-toc .md-nav__link:hover .live-wysiwyg-toc-copy-btn{' +
        'opacity:.5;pointer-events:auto;' +
      '}' +
      '.live-wysiwyg-toc-copy-btn:hover{opacity:1!important;color:var(--md-accent-fg-color,#007bff)!important;}' +

      

      '@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;' +
      '}' +

      '.focus-mode-markdown .live-wysiwyg-focus-grid{' +
        'margin-top:0;min-height:100%;' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-content{' +
        'padding-top:0;margin-top:0;margin-bottom:0;' +
        'display:flex;flex-direction:column;' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-content .md-wysiwyg-editor-wrapper{' +
        'flex:1;display:flex;flex-direction:column;' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-content .md-editor-content-area{' +
        'flex:1;' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-content .md-markdown-editor-container{' +
        'height:auto!important;flex:1 1 0!important;min-height:0;' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-sidebar-left{' +
        'max-height:var(--_panel-h,calc(100vh - 2.4rem));' +
      '}' +
      '.focus-mode-markdown .live-wysiwyg-focus-toc{' +
        'max-height:var(--_panel-h,calc(100vh - 2.4rem));' +
      '}' +

      '@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);' +
        '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;' +
        'white-space:nowrap;' +
      '}' +
      '.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-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--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-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;}' +

      // --- 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;' +
      '}' +

      // --- Site settings gear in nav title ---
      '.live-wysiwyg-nav-site-gear{' +
        'display:none;position:absolute;left:calc(.6rem - 15px);top:50%;transform:translateY(-50%);' +
      '}' +
      '.live-wysiwyg-nav-title-hover .live-wysiwyg-nav-site-gear{' +
        'display:inline-block;' +
      '}' +
      '.live-wysiwyg-nav-site-title{' +
        'display:block;overflow:hidden;text-overflow:ellipsis;' +
      '}' +

      // --- Hidden (headless) pages in nav ---
      '.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;' +
      '}' +

      // --- Asset Preview Popup ---
      '.live-wysiwyg-asset-preview-popup{' +
        'position:fixed;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,.18);padding:0;max-width:340px;min-width:180px;' +
        'font-size:.75rem;color:var(--md-default-fg-color,#333);line-height:1.5;overflow:hidden;' +
      '}' +
      '.live-wysiwyg-asset-preview-header{' +
        'display:flex;align-items:center;justify-content:space-between;padding:8px 12px;' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#eee);gap:8px;' +
      '}' +
      '.live-wysiwyg-asset-preview-title{' +
        'font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0;' +
      '}' +
      '.live-wysiwyg-asset-preview-expand{' +
        '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;white-space:nowrap;flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-asset-preview-expand:hover{background:var(--md-default-bg-color--light,#f7f7f7);}' +
      '.live-wysiwyg-asset-preview-body{padding:8px 12px;}' +
      '.live-wysiwyg-asset-preview-img{' +
        'max-width:220px;max-height:160px;object-fit:contain;display:block;margin:0 auto;' +
        'border-radius:3px;' +
      '}' +
      '.live-wysiwyg-asset-preview-text{' +
        'max-width:320px;max-height:200px;overflow:hidden;margin:0;padding:6px 8px;' +
        'font-family:var(--md-code-font-family,SFMono-Regular,Consolas,monospace);font-size:.65rem;' +
        'background:var(--md-code-bg-color,#f5f5f5);border-radius:3px;white-space:pre-wrap;word-break:break-all;' +
        'line-height:1.4;color:var(--md-code-fg-color,#333);' +
      '}' +

      // --- Asset Lightbox ---
      '.live-wysiwyg-asset-lightbox{' +
        'position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,.65);' +
        'display:flex;align-items:center;justify-content:center;' +
      '}' +
      '.live-wysiwyg-asset-lightbox-panel{' +
        'background:var(--md-default-bg-color,#fff);border-radius:8px;max-width:90vw;max-height:90vh;' +
        'display:flex;flex-direction:column;overflow:hidden;box-shadow:0 8px 32px rgba(0,0,0,.3);' +
        'min-width:320px;' +
      '}' +
      '.live-wysiwyg-asset-lightbox-header{' +
        'display:flex;align-items:center;justify-content:space-between;padding:10px 16px;' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#eee);gap:12px;' +
      '}' +
      '.live-wysiwyg-asset-lightbox-title{' +
        'font-weight:600;font-size:.8rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0;' +
        'color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-asset-lightbox-close{' +
        'width:28px;height:28px;border:none;background:transparent;cursor:pointer;' +
        'font-size:1.2rem;line-height:1;color:var(--md-default-fg-color--light,#999);' +
        'border-radius:4px;display:flex;align-items:center;justify-content:center;flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-asset-lightbox-close:hover{background:var(--md-default-bg-color--light,#f0f0f0);color:var(--md-default-fg-color,#333);}' +
      '.live-wysiwyg-asset-lightbox-body{padding:16px;overflow:auto;flex:1;display:flex;align-items:center;justify-content:center;}' +
      '.live-wysiwyg-asset-lightbox-img{' +
        'max-width:88vw;max-height:82vh;object-fit:contain;border-radius:4px;' +
      '}' +
      '.live-wysiwyg-asset-lightbox-text{' +
        'max-height:80vh;overflow-y:auto;margin:0;padding:12px 16px;width:100%;' +
        'font-family:var(--md-code-font-family,SFMono-Regular,Consolas,monospace);font-size:.72rem;' +
        'background:var(--md-code-bg-color,#f5f5f5);border-radius:4px;white-space:pre-wrap;word-break:break-all;' +
        'line-height:1.5;color:var(--md-code-fg-color,#333);' +
      '}' +

      // --- Drag-and-drop feedback ---
      '.live-wysiwyg-drop-target{' +
        'outline:2px dashed var(--md-accent-fg-color,#448aff) !important;' +
        'outline-offset:-2px;' +
        'background:rgba(68,138,255,.04) !important;' +
      '}' +
      '.live-wysiwyg-nav-asset-link[draggable=true]{cursor:grab;}' +
      '.live-wysiwyg-nav-asset-link[draggable=true]:active{cursor:grabbing;}' +

      '.live-wysiwyg-help-overlay{' +
        'position:fixed;inset:0;z-index:100003;' +
        'display:flex;align-items:center;justify-content:center;' +
      '}' +
      '.live-wysiwyg-help-backdrop{' +
        'position:absolute;inset:0;' +
        'background:rgba(0,0,0,.45);' +
      '}' +
      '.live-wysiwyg-help-modal{' +
        'position:relative;' +
        'width:min(90vw,56rem);height:min(85vh,44rem);' +
        'display:flex;flex-direction:column;' +
        'background:var(--md-default-bg-color,#fff);' +
        'color:var(--md-default-fg-color,#1a1a1a);' +
        'border-radius:8px;' +
        'box-shadow:0 8px 32px rgba(0,0,0,.28);' +
        'overflow:hidden;' +
      '}' +
      '.live-wysiwyg-help-header{' +
        'display:flex;align-items:center;justify-content:space-between;' +
        'padding:.6rem 1rem;' +
        'background:var(--md-primary-fg-color,#4051b5);' +
        'color:var(--md-primary-bg-color,#fff);' +
        'font-size:.9rem;font-weight:700;' +
        'flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-help-close{' +
        'background:none;border:none;color:inherit;' +
        'cursor:pointer;font-size:1.1rem;padding:2px 6px;' +
        'opacity:.8;line-height:1;' +
      '}' +
      '.live-wysiwyg-help-close:hover{opacity:1;}' +
      '.live-wysiwyg-help-tabs{' +
        'display:flex;gap:0;' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#e0e0e0);' +
        'overflow-x:auto;flex-shrink:0;' +
        'background:var(--md-default-bg-color,#fff);' +
        'scrollbar-width:none;' +
      '}' +
      '.live-wysiwyg-help-tabs::-webkit-scrollbar{display:none;}' +
      '.live-wysiwyg-help-tab{' +
        'padding:.5rem 1rem;' +
        'background:none;border:none;' +
        'border-bottom:2px solid transparent;' +
        'color:var(--md-default-fg-color--light,#666);' +
        'font-size:.78rem;cursor:pointer;white-space:nowrap;' +
        'transition:color .15s,border-color .15s;' +
      '}' +
      '.live-wysiwyg-help-tab:hover{' +
        'color:var(--md-default-fg-color,#1a1a1a);' +
      '}' +
      '.live-wysiwyg-help-tab.active{' +
        'color:var(--md-primary-fg-color,#4051b5);' +
        'border-bottom-color:var(--md-primary-fg-color,#4051b5);' +
        'font-weight:600;' +
      '}' +
      '.live-wysiwyg-help-body{' +
        'flex:1;overflow-y:auto;padding:1rem 1.5rem;' +
        'font-size:.82rem;line-height:1.6;' +
      '}' +
      '.live-wysiwyg-help-body table{' +
        'width:100%;border-collapse:collapse;margin:.8rem 0;font-size:.78rem;' +
      '}' +
      '.live-wysiwyg-help-body th,.live-wysiwyg-help-body td{' +
        'padding:.4rem .6rem;text-align:left;' +
        'border:1px solid var(--md-default-fg-color--lightest,#e0e0e0);' +
      '}' +
      '.live-wysiwyg-help-body th{' +
        'background:var(--md-default-fg-color--lightest,#f5f5f5);' +
        'font-weight:600;' +
      '}' +
      '.live-wysiwyg-help-body code{' +
        'background:var(--md-code-bg-color,#f5f5f5);' +
        'padding:.1em .3em;border-radius:3px;font-size:.85em;' +
      '}' +
      '.live-wysiwyg-help-body pre{' +
        'background:var(--md-code-bg-color,#f5f5f5);' +
        'padding:.6rem .8rem;border-radius:4px;overflow-x:auto;' +
        'font-size:.8em;' +
      '}' +
      '.live-wysiwyg-help-body pre code{background:none;padding:0;}' +
      '.live-wysiwyg-help-body h3{' +
        'font-size:.88rem;margin:1.2rem 0 .4rem;' +
        'color:var(--md-default-fg-color,#1a1a1a);' +
      '}' +
      '.live-wysiwyg-help-body h4{' +
        'font-size:.82rem;margin:1rem 0 .3rem;' +
        'color:var(--md-default-fg-color--light,#666);' +
      '}' +
      '.live-wysiwyg-help-body ul,.live-wysiwyg-help-body ol{' +
        'padding-left:1.4em;margin:.4rem 0;' +
      '}' +
      '.live-wysiwyg-help-body li{margin:.2rem 0;}' +
      '.live-wysiwyg-help-body strong{font-weight:600;}' +
      '.live-wysiwyg-help-body hr{' +
        'border:none;border-top:1px solid var(--md-default-fg-color--lightest,#e0e0e0);' +
        'margin:1rem 0;' +
      '}' +
      '.live-wysiwyg-help-body .admonition,.live-wysiwyg-help-body details{' +
        'border-left:4px solid var(--md-primary-fg-color,#4051b5);' +
        'background:var(--md-admonition-bg-color,rgba(68,138,255,.05));' +
        'padding:.6rem .8rem;margin:.6rem 0;border-radius:2px;' +
      '}' +
      '.live-wysiwyg-help-body .admonition-title,.live-wysiwyg-help-body summary{' +
        'font-weight:600;margin-bottom:.3rem;' +
      '}' +
      '.live-wysiwyg-focus-help-btn{' +
        'background:none;border:none;color:inherit;' +
        'cursor:pointer;font-size:.95rem;padding:0 6px;' +
        'opacity:.7;display:flex;align-items:center;' +
      '}' +
      '.live-wysiwyg-focus-help-btn:hover{opacity:1;}' +

      '';

    if (_compat.engine === 'gecko') {
      css +=
        '.live-wysiwyg-focus-sidebar-left .md-nav__link{' +
          'margin-top:9px;' +
        '}' +
        '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested>.md-nav{' +
          'min-height:0;' +
        '}' +
        '.live-wysiwyg-focus-sidebar-left .md-nav__item--nested>.md-nav>.md-nav__list{' +
          'padding-bottom:.25rem;' +
        '}';
    }

    // --- History Mode (Layer 4) CSS ---
    css +=
      '.live-wysiwyg-history-branch-popup{' +
        'position:fixed;z-index:99999;' +
        '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);' +
        'min-width:260px;max-width:380px;padding:0;' +
        'font-family:var(--md-text-font-family,sans-serif);font-size:.8rem;' +
        'outline:none;' +
      '}' +
      '.live-wysiwyg-history-branch-header{' +
        'display:flex;align-items:center;justify-content:space-between;' +
        'padding:8px 12px;border-bottom:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'font-weight:600;color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-history-fullscreen-btn{' +
        'background:var(--md-primary-fg-color,#4051b5);color:#fff;' +
        'border:none;border-radius:4px;padding:3px 10px;cursor:pointer;font-size:.72rem;' +
      '}' +
      '.live-wysiwyg-history-fullscreen-btn:hover{opacity:.85;}' +
      '.live-wysiwyg-history-branch-list{padding:4px 0;}' +
      '.live-wysiwyg-history-branch-item{' +
        'display:flex;flex-direction:column;padding:6px 12px;cursor:pointer;' +
        'border-left:3px solid transparent;' +
        'transition:background .12s;' +
      '}' +
      '.live-wysiwyg-history-branch-item:hover,' +
      '.live-wysiwyg-history-branch-item.highlighted{' +
        'background:var(--md-accent-fg-color--transparent,rgba(82,108,254,.08));' +
      '}' +
      '.live-wysiwyg-history-branch-item.active{' +
        'border-left-color:var(--md-primary-fg-color,#4051b5);' +
      '}' +
      '.live-wysiwyg-history-branch-summary{' +
        'font-weight:500;color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-history-branch-snippet{' +
        'color:var(--md-default-fg-color--light,#666);font-size:.72rem;' +
        'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px;' +
      '}' +
      '.live-wysiwyg-history-branch-time{' +
        'color:var(--md-default-fg-color--lighter,#999);font-size:.68rem;margin-top:1px;' +
      '}' +

      // History Mode overlay
      '.live-wysiwyg-history-overlay{' +
        'position:fixed;inset:0;z-index:99995;display:flex;align-items:center;justify-content:center;' +
        'outline:none;' +
      '}' +
      '.live-wysiwyg-history-backdrop{' +
        'position:absolute;inset:0;background:rgba(0,0,0,.45);' +
      '}' +
      '.live-wysiwyg-history-modal{' +
        'position:relative;z-index:1;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border-radius:10px;box-shadow:0 8px 40px rgba(0,0,0,.25);' +
        'width:92vw;max-width:1200px;height:82vh;' +
        'display:flex;flex-direction:column;overflow:hidden;' +
      '}' +
      '.live-wysiwyg-history-modal-header{' +
        'display:flex;align-items:center;justify-content:space-between;' +
        'padding:12px 20px;border-bottom:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'flex-shrink:0;' +
      '}' +
      '.live-wysiwyg-history-modal-header h2{' +
        'margin:0;font-size:1.1rem;color:var(--md-default-fg-color,#333);' +
        'font-family:var(--md-text-font-family,sans-serif);' +
      '}' +
      '.live-wysiwyg-history-close-btn{' +
        'background:none;border:none;font-size:1.5rem;cursor:pointer;' +
        'color:var(--md-default-fg-color--light,#666);line-height:1;padding:0 4px;' +
      '}' +
      '.live-wysiwyg-history-close-btn:hover{color:var(--md-default-fg-color,#333);}' +
      '.live-wysiwyg-history-modal-body{' +
        'display:flex;flex:1;overflow:hidden;' +
      '}' +
      '.live-wysiwyg-history-dag-container{' +
        'flex:1;overflow:auto;padding:20px;position:relative;' +
        'background:var(--md-default-bg-color,#fff);' +
      '}' +

      // DAG SVG edges (smooth Bézier curves)
      '.live-wysiwyg-dag-edge{stroke:var(--md-default-fg-color--lightest,#ccc);stroke-width:2;fill:none;}' +
      '.live-wysiwyg-dag-edge-active{stroke:var(--md-primary-fg-color,#4051b5);stroke-width:3;fill:none;}' +

      // DAG nodes
      '.live-wysiwyg-history-dag-node{' +
        'width:300px;height:48px;display:flex;align-items:center;gap:8px;' +
        'padding:0 12px;border-radius:6px;cursor:pointer;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'transition:border-color .15s,box-shadow .15s;' +
        'font-family:var(--md-text-font-family,sans-serif);' +
        'position:relative;z-index:1;' +
      '}' +
      '.live-wysiwyg-history-dag-node:hover{' +
        'border-color:var(--md-accent-fg-color,#7c4dff);' +
        'box-shadow:0 2px 8px rgba(0,0,0,.1);' +
      '}' +
      '.live-wysiwyg-history-dag-node.selected{' +
        'border-color:var(--md-primary-fg-color,#4051b5);' +
        'box-shadow:0 0 0 2px var(--md-primary-fg-color--transparent,rgba(64,81,181,.25));' +
      '}' +
      '.live-wysiwyg-dag-dot{' +
        'width:12px;height:12px;border-radius:50%;flex-shrink:0;' +
        'background:var(--md-default-fg-color--lightest,#ccc);' +
      '}' +
      '.live-wysiwyg-history-dag-node.active-path .live-wysiwyg-dag-dot{' +
        'background:var(--md-primary-fg-color,#4051b5);' +
      '}' +
      '.live-wysiwyg-history-dag-node.current .live-wysiwyg-dag-dot{' +
        'background:var(--md-accent-fg-color,#7c4dff);' +
        'box-shadow:0 0 0 3px var(--md-accent-fg-color--transparent,rgba(124,77,255,.3));' +
      '}' +
      '.live-wysiwyg-history-dag-node.branch-point .live-wysiwyg-dag-dot{' +
        'border:2px solid var(--md-default-fg-color--light,#999);' +
      '}' +
      '.live-wysiwyg-dag-info{' +
        'flex:1;overflow:hidden;text-overflow:ellipsis;' +
        'display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;' +
        'font-size:.75rem;line-height:1.3;color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-dag-time{' +
        'font-size:.65rem;color:var(--md-default-fg-color--lighter,#999);white-space:nowrap;' +
      '}' +

      // "You Are Here" snaking SVG path + arrowhead + label
      '.live-wysiwyg-dag-yah-path{' +
        'fill:none;stroke:var(--md-accent-fg-color,#7c4dff);' +
        'stroke-width:3;stroke-dasharray:8 5;' +
        'pointer-events:none;' +
      '}' +
      '.live-wysiwyg-dag-yah-arrowhead{' +
        'fill:var(--md-accent-fg-color,#7c4dff);pointer-events:none;' +
      '}' +
      '.live-wysiwyg-dag-you-are-here-label{' +
        'display:flex;align-items:center;gap:4px;white-space:nowrap;' +
        'color:var(--md-accent-fg-color,#7c4dff);' +
        'font-weight:700;font-size:.73rem;' +
        'font-family:var(--md-text-font-family,sans-serif);' +
        'background:var(--md-default-bg-color,#fff);' +
        'padding:3px 12px 3px 6px;border-radius:12px;' +
        'border:2px solid var(--md-accent-fg-color,#7c4dff);' +
        'pointer-events:none;z-index:2;' +
      '}' +
      '.live-wysiwyg-dag-you-are-here-label svg{flex-shrink:0;}' +

      // Crumple icon (container groups + branch crumples)
      '.live-wysiwyg-dag-crumple{' +
        'width:300px;height:36px;display:flex;align-items:center;gap:8px;' +
        'padding:0 12px;border-radius:18px;cursor:pointer;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:1px dashed var(--md-primary-fg-color,#4051b5);' +
        'font-family:var(--md-text-font-family,sans-serif);' +
        'transition:background .15s,border-color .15s,box-shadow .15s;' +
        'position:relative;z-index:1;' +
      '}' +
      '.live-wysiwyg-dag-crumple:hover{' +
        'background:var(--md-primary-fg-color--transparent,rgba(64,81,181,.08));' +
        'box-shadow:0 2px 8px rgba(0,0,0,.08);' +
      '}' +
      '.live-wysiwyg-dag-crumple.active{' +
        'border-style:solid;' +
        'background:var(--md-primary-fg-color--transparent,rgba(64,81,181,.1));' +
      '}' +
      '.live-wysiwyg-dag-crumple-svg{flex-shrink:0;color:var(--md-primary-fg-color,#4051b5);}' +
      '.live-wysiwyg-dag-crumple-label{' +
        'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
        'font-size:.7rem;font-weight:600;color:var(--md-primary-fg-color,#4051b5);' +
      '}' +
      '.live-wysiwyg-dag-crumple[data-container-type="code"]{border-color:#0d7377;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="code"] .live-wysiwyg-dag-crumple-svg,' +
      '.live-wysiwyg-dag-crumple[data-container-type="code"] .live-wysiwyg-dag-crumple-label{color:#0d7377;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="code"]:hover{background:rgba(13,115,119,.08);}' +
      '.live-wysiwyg-dag-crumple[data-container-type="admonition"]{border-color:#bf6900;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="admonition"] .live-wysiwyg-dag-crumple-svg,' +
      '.live-wysiwyg-dag-crumple[data-container-type="admonition"] .live-wysiwyg-dag-crumple-label{color:#bf6900;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="admonition"]:hover{background:rgba(191,105,0,.08);}' +
      '.live-wysiwyg-dag-crumple[data-container-type="blockquote"]{border-color:#7b1fa2;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="blockquote"] .live-wysiwyg-dag-crumple-svg,' +
      '.live-wysiwyg-dag-crumple[data-container-type="blockquote"] .live-wysiwyg-dag-crumple-label{color:#7b1fa2;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="blockquote"]:hover{background:rgba(123,31,162,.08);}' +
      '.live-wysiwyg-dag-crumple[data-container-type="list"]{border-color:#2e7d32;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="list"] .live-wysiwyg-dag-crumple-svg,' +
      '.live-wysiwyg-dag-crumple[data-container-type="list"] .live-wysiwyg-dag-crumple-label{color:#2e7d32;}' +
      '.live-wysiwyg-dag-crumple[data-container-type="list"]:hover{background:rgba(46,125,50,.08);}' +
      '.live-wysiwyg-dag-crumple.branch-crumple{border-color:#b07d2b;}' +
      '.live-wysiwyg-dag-crumple.branch-crumple .live-wysiwyg-dag-crumple-svg,' +
      '.live-wysiwyg-dag-crumple.branch-crumple .live-wysiwyg-dag-crumple-label{color:#b07d2b;}' +
      '.live-wysiwyg-dag-crumple.branch-crumple:hover{background:rgba(176,125,43,.08);}' +
      '.live-wysiwyg-dag-crumple.branch-crumple.active{border-style:solid;background:rgba(176,125,43,.1);}' +

      // V-tree fork icon
      '.live-wysiwyg-dag-vtree-fork{' +
        'width:300px;height:36px;display:flex;align-items:center;gap:8px;' +
        'padding:0 12px;border-radius:18px;cursor:pointer;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:1px dashed #6d4c9f;' +
        'font-family:var(--md-text-font-family,sans-serif);' +
        'transition:background .15s,box-shadow .15s;' +
        'position:relative;z-index:1;' +
      '}' +
      '.live-wysiwyg-dag-vtree-fork:hover{background:rgba(109,76,159,.08);box-shadow:0 2px 8px rgba(0,0,0,.08);}' +
      '.live-wysiwyg-dag-vtree-fork.active{border-style:solid;background:rgba(109,76,159,.1);}' +
      '.live-wysiwyg-dag-vtree-svg{flex-shrink:0;color:#6d4c9f;}' +
      '.live-wysiwyg-dag-vtree-label{' +
        'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
        'font-size:.7rem;font-weight:600;color:#6d4c9f;' +
      '}' +

      // V-tree option (branch picker item)
      '.live-wysiwyg-dag-vtree-option{' +
        'width:300px;height:36px;display:flex;align-items:center;gap:8px;' +
        'padding:0 12px;border-radius:6px;cursor:pointer;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'font-family:var(--md-text-font-family,sans-serif);' +
        'transition:border-color .15s,box-shadow .15s;' +
        'position:relative;z-index:1;' +
      '}' +
      '.live-wysiwyg-dag-vtree-option:hover{border-color:#6d4c9f;box-shadow:0 2px 8px rgba(0,0,0,.08);}' +
      '.live-wysiwyg-dag-vtree-option .live-wysiwyg-dag-crumple-svg{color:#b07d2b;}' +
      '.live-wysiwyg-dag-vtree-option-label{' +
        'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +
        'font-size:.7rem;color:var(--md-default-fg-color,#333);' +
      '}' +

      // Block context dotted outline
      '.live-wysiwyg-dag-block-outline{' +
        'border:2px dashed var(--md-primary-fg-color,#4051b5);' +
        'border-radius:8px;z-index:0;pointer-events:none;' +
      '}' +
      '.live-wysiwyg-dag-block-outline[data-container-type="code"]{border-color:#0d7377;}' +
      '.live-wysiwyg-dag-block-outline[data-container-type="admonition"]{border-color:#bf6900;}' +
      '.live-wysiwyg-dag-block-outline[data-container-type="blockquote"]{border-color:#7b1fa2;}' +
      '.live-wysiwyg-dag-block-outline[data-container-type="list"]{border-color:#2e7d32;}' +
      '.live-wysiwyg-dag-block-outline.inactive{opacity:.35;}' +
      '.live-wysiwyg-dag-block-outline-title{' +
        'position:absolute;top:-9px;left:12px;' +
        'background:var(--md-default-bg-color,#fff);' +
        'padding:0 6px;font-size:.62rem;font-weight:600;' +
        'font-family:var(--md-text-font-family,sans-serif);' +
        'color:inherit;white-space:nowrap;' +
      '}' +

      // Unfold / entrance animation
      '.live-wysiwyg-history-dag-node.group-enter{' +
        'animation:liveWysiwygGroupEnter .3s ease-out both;' +
      '}' +
      '@keyframes liveWysiwygGroupEnter{' +
        '0%{transform:scaleY(0);opacity:0;}100%{transform:scaleY(1);opacity:1;}' +
      '}' +

      // Organic tree view
      '.live-wysiwyg-organic-wrapper{transition:opacity .3s ease-out;}' +
      '.live-wysiwyg-dag-transitioning .live-wysiwyg-organic-wrapper,' +
      '.live-wysiwyg-dag-transitioning > div{' +
        'animation:liveWysiwygDagFadeIn .3s ease-out both;' +
      '}' +
      '@keyframes liveWysiwygDagFadeIn{0%{opacity:0;}100%{opacity:1;}}' +
      '.live-wysiwyg-organic-svg{pointer-events:none;}' +
      '.live-wysiwyg-organic-edge{stroke:var(--md-default-fg-color--lightest,#ccc);stroke-width:1.5;fill:none;}' +
      '.live-wysiwyg-organic-edge-active{stroke:var(--md-primary-fg-color,#4051b5);stroke-width:2;fill:none;}' +
      '.live-wysiwyg-organic-dot{' +
        'width:10px;height:10px;border-radius:50%;cursor:pointer;' +
        'background:var(--md-default-fg-color--lightest,#ccc);' +
        'transition:transform .15s,box-shadow .15s;' +
        'z-index:1;' +
      '}' +
      '.live-wysiwyg-organic-dot:hover{' +
        'transform:scale(1.6);' +
        'box-shadow:0 0 6px rgba(0,0,0,.2);' +
      '}' +
      '.live-wysiwyg-organic-dot.active-path{' +
        'background:var(--md-primary-fg-color,#4051b5);' +
      '}' +
      '.live-wysiwyg-organic-dot.current{' +
        'width:14px;height:14px;margin:-2px 0 0 -2px;' +
        'background:var(--md-accent-fg-color,#7c4dff);' +
        'box-shadow:0 0 0 4px var(--md-accent-fg-color--transparent,rgba(124,77,255,.35)),' +
                  '0 0 12px var(--md-accent-fg-color--transparent,rgba(124,77,255,.25));' +
        'animation:liveWysiwygOrganicGlow 2s ease-in-out infinite;' +
      '}' +
      '@keyframes liveWysiwygOrganicGlow{' +
        '0%,100%{box-shadow:0 0 0 4px var(--md-accent-fg-color--transparent,rgba(124,77,255,.35)),0 0 12px var(--md-accent-fg-color--transparent,rgba(124,77,255,.25));}' +
        '50%{box-shadow:0 0 0 6px var(--md-accent-fg-color--transparent,rgba(124,77,255,.2)),0 0 18px var(--md-accent-fg-color--transparent,rgba(124,77,255,.15));}' +
      '}' +

      // Toggle view button
      '.live-wysiwyg-history-toggle-view-btn{' +
        'background:var(--md-primary-fg-color--transparent,rgba(64,81,181,.1));' +
        'border:1px solid var(--md-primary-fg-color,#4051b5);' +
        'border-radius:4px;padding:4px 12px;cursor:pointer;' +
        'font-size:.72rem;font-weight:600;' +
        'color:var(--md-primary-fg-color,#4051b5);' +
        'font-family:var(--md-text-font-family,sans-serif);' +
        'transition:background .15s;margin-right:8px;' +
      '}' +
      '.live-wysiwyg-history-toggle-view-btn:hover{' +
        'background:var(--md-primary-fg-color--transparent,rgba(64,81,181,.2));' +
      '}' +

      // "Show All Redo History" popup item
      '.live-wysiwyg-history-branch-item.show-all-history{' +
        'border-top:1px solid var(--md-default-fg-color--lightest,#eee);' +
        'margin-top:2px;padding-top:8px;' +
        'flex-direction:row;align-items:center;' +
      '}' +
      '.live-wysiwyg-history-branch-item.show-all-history .live-wysiwyg-history-branch-summary{' +
        'display:flex;align-items:center;' +
        'color:var(--md-primary-fg-color,#4051b5);font-weight:600;' +
      '}' +

      // Hover preview tooltip
      '.live-wysiwyg-history-hover-preview{' +
        'position:fixed;z-index:99999;' +
        'background:var(--md-default-bg-color,#fff);' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'border-radius:6px;box-shadow:0 4px 20px rgba(0,0,0,.15);' +
        'width:300px;max-height:280px;overflow:hidden;' +
        'font-family:var(--md-text-font-family,sans-serif);' +
      '}' +
      '.live-wysiwyg-history-hover-snippet{' +
        'padding:8px 10px;font-size:.7rem;font-family:var(--md-code-font-family,monospace);' +
        'color:var(--md-default-fg-color--light,#666);' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#eee);' +
        'white-space:pre;overflow:hidden;max-height:52px;' +
      '}' +
      '.live-wysiwyg-history-hover-rendered{' +
        'padding:8px 10px;font-size:.78rem;overflow:hidden;max-height:160px;' +
        'color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-history-hover-rendered h1,.live-wysiwyg-history-hover-rendered h2,' +
      '.live-wysiwyg-history-hover-rendered h3{font-size:.85rem;margin:.3em 0;}' +
      '.live-wysiwyg-history-hover-rendered p{margin:.3em 0;}' +
      '.live-wysiwyg-history-hover-rendered pre{' +
        'font-size:.68rem;background:var(--md-code-bg-color,#f5f5f5);padding:4px;border-radius:3px;overflow:hidden;' +
      '}' +
      '.live-wysiwyg-history-hover-fullscreen-btn{' +
        'display:block;width:100%;padding:5px;text-align:center;' +
        'border:none;border-top:1px solid var(--md-default-fg-color--lightest,#eee);' +
        'background:var(--md-default-bg-color,#fff);cursor:pointer;font-size:.7rem;' +
        'color:var(--md-primary-fg-color,#4051b5);' +
      '}' +
      '.live-wysiwyg-history-hover-fullscreen-btn:hover{' +
        'background:var(--md-accent-fg-color--transparent,rgba(82,108,254,.06));' +
      '}' +

      // Preview panel (right side of DAG overlay — hidden until a node is selected)
      '.live-wysiwyg-history-preview-panel{' +
        'width:0;min-width:0;overflow:hidden;display:flex;flex-direction:column;' +
        'background:var(--md-default-bg-color,#fff);' +
        'transition:width .3s ease,min-width .3s ease,border-width .3s ease;' +
        'border-left:0 solid var(--md-default-fg-color--lightest,#ddd);' +
      '}' +
      '.live-wysiwyg-history-preview-panel.open{' +
        'width:40%;min-width:280px;overflow-y:auto;' +
        'border-left-width:1px;' +
      '}' +
      '.live-wysiwyg-history-preview-header{' +
        'display:flex;align-items:center;gap:8px;padding:10px 14px;flex-shrink:0;' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#eee);' +
        'font-size:.78rem;color:var(--md-default-fg-color,#333);flex-wrap:wrap;' +
      '}' +
      '.live-wysiwyg-history-preview-fullscreen-btn,' +
      '.live-wysiwyg-history-preview-restore-btn{' +
        'border:none;border-radius:4px;padding:3px 10px;cursor:pointer;font-size:.72rem;' +
      '}' +
      '.live-wysiwyg-history-preview-fullscreen-btn{' +
        'background:var(--md-default-fg-color--lightest,#eee);color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-history-preview-restore-btn{' +
        'background:var(--md-primary-fg-color,#4051b5);color:#fff;' +
      '}' +
      '.live-wysiwyg-history-preview-content{' +
        'padding:14px;font-size:.85rem;overflow-y:auto;flex:1;' +
        'color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-history-preview-content h1,.live-wysiwyg-history-preview-content h2,' +
      '.live-wysiwyg-history-preview-content h3{margin:.5em 0;}' +
      '.live-wysiwyg-history-preview-content pre{' +
        'font-size:.78rem;background:var(--md-code-bg-color,#f5f5f5);padding:8px;border-radius:4px;overflow:auto;' +
      '}' +

      // Diff highlight overlay for changed/added blocks
      '.live-wysiwyg-diff-highlight{' +
        'position:relative;' +
      '}' +
      '.live-wysiwyg-diff-highlight::before{' +
        'content:"";position:absolute;inset:-2px -4px;' +
        'background:rgba(46,160,67,.13);' +
        'border-left:3px solid rgba(46,160,67,.6);' +
        'border-radius:3px;pointer-events:none;z-index:0;' +
      '}' +

      // Full-size readonly preview
      '.live-wysiwyg-history-fullsize-preview{' +
        'position:fixed;inset:0;z-index:99995;' +
        'background:var(--md-default-bg-color,#fff);' +
        'display:flex;flex-direction:column;outline:none;' +
      '}' +
      '.live-wysiwyg-history-fullsize-header{' +
        'display:flex;align-items:center;gap:10px;padding:10px 20px;flex-shrink:0;' +
        'border-bottom:1px solid var(--md-default-fg-color--lightest,#ddd);' +
        'font-family:var(--md-text-font-family,sans-serif);font-size:.85rem;' +
        'color:var(--md-default-fg-color,#333);' +
      '}' +
      '.live-wysiwyg-history-fullsize-header span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}' +
      '.live-wysiwyg-history-fullsize-restore-btn{' +
        'background:var(--md-primary-fg-color,#4051b5);color:#fff;' +
        'border:none;border-radius:4px;padding:5px 14px;cursor:pointer;font-size:.8rem;' +
      '}' +
      '.live-wysiwyg-history-fullsize-close-btn{' +
        'background:var(--md-default-fg-color--lightest,#eee);color:var(--md-default-fg-color,#333);' +
        'border:none;border-radius:4px;padding:5px 14px;cursor:pointer;font-size:.8rem;' +
      '}' +
      '.live-wysiwyg-history-fullsize-body{' +
        'flex:1;overflow-y:auto;padding:20px;' +
      '}' +
      '.live-wysiwyg-history-fullsize-content{' +
        'max-width:48rem;margin:0 auto;' +
        'font-family:var(--md-text-font-family,sans-serif);font-size:.95rem;' +
        'color:var(--md-default-fg-color,#333);line-height:1.6;' +
      '}' +
      '.live-wysiwyg-history-fullsize-content h1{font-size:1.6rem;margin:.8em 0 .4em;}' +
      '.live-wysiwyg-history-fullsize-content h2{font-size:1.3rem;margin:.7em 0 .3em;}' +
      '.live-wysiwyg-history-fullsize-content h3{font-size:1.1rem;margin:.6em 0 .3em;}' +
      '.live-wysiwyg-history-fullsize-content pre{' +
        'background:var(--md-code-bg-color,#f5f5f5);padding:12px;border-radius:4px;overflow:auto;' +
        'font-family:var(--md-code-font-family,monospace);font-size:.85rem;' +
      '}' +
      '.live-wysiwyg-history-fullsize-content code{' +
        'background:var(--md-code-bg-color,#f5f5f5);padding:.1em .3em;border-radius:3px;' +
        'font-family:var(--md-code-font-family,monospace);font-size:.85em;' +
      '}' +
      '.live-wysiwyg-history-fullsize-content pre code{background:none;padding:0;}' +
      '.live-wysiwyg-history-fullsize-content blockquote{' +
        'border-left:3px solid var(--md-default-fg-color--lightest,#ddd);' +
        'margin:0;padding:.5em 1em;color:var(--md-default-fg-color--light,#666);' +
      '}' +
      '.live-wysiwyg-history-fullsize-content img{max-width:100%;height:auto;}' +
      '.live-wysiwyg-history-fullsize-content table{' +
        'border-collapse:collapse;width:100%;margin:1em 0;' +
      '}' +
      '.live-wysiwyg-history-fullsize-content th,.live-wysiwyg-history-fullsize-content td{' +
        'border:1px solid var(--md-default-fg-color--lightest,#ddd);padding:6px 10px;text-align:left;' +
      '}' +
      '';

    return css;
  }

  function buildFocusToc(editableArea, tocListEl) {
    if (!tocListEl) return;
    var html = '';
    var copyIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><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>';
    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 slug = _headingSlugify(text);
        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;') + '">' +
          '<button class="live-wysiwyg-toc-copy-btn" type="button" title="Copy heading link" data-toc-slug="' + slug + '">' + copyIcon + '</button>' +
          '<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 slug = _headingSlugify(text);
        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;') + '">' +
          '<button class="live-wysiwyg-toc-copy-btn" type="button" title="Copy heading link" data-toc-slug="' + slug + '">' + copyIcon + '</button>' +
          '<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;
          if (_compat.engine === 'webkit' && sel.rangeCount === 0) {
            restored = false;
          }
        }
      } 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;
  }

  // ======================================================================
  // Help System (Layer 5)
  // ======================================================================

  function _parseHelpSections() {
    if (_helpSections) return _helpSections;
    if (typeof liveWysiwygHelpContent !== 'string' || !liveWysiwygHelpContent) {
      _helpSections = [];
      return _helpSections;
    }
    var raw = liveWysiwygHelpContent;
    var sections = [];
    var h2Pattern = /^## (.+)$/gm;
    var contextPattern = /<!--\s*context:\s*(content|nav|all)\s*-->/;
    var match;
    var lastTitle = null;
    var lastStart = -1;
    while ((match = h2Pattern.exec(raw)) !== null) {
      if (lastTitle !== null) {
        var chunk = raw.substring(lastStart, match.index).trim();
        var ctxMatch = chunk.match(contextPattern);
        var ctx = ctxMatch ? ctxMatch[1] : 'all';
        var body = chunk.replace(contextPattern, '').trim();
        sections.push({ title: lastTitle, context: ctx, markdown: body });
      }
      lastTitle = match[1].trim();
      lastStart = match.index + match[0].length;
    }
    if (lastTitle !== null) {
      var lastChunk = raw.substring(lastStart).trim();
      var lastCtxMatch = lastChunk.match(contextPattern);
      var lastCtx = lastCtxMatch ? lastCtxMatch[1] : 'all';
      var lastBody = lastChunk.replace(contextPattern, '').trim();
      sections.push({ title: lastTitle, context: lastCtx, markdown: lastBody });
    }
    _helpSections = sections;
    return sections;
  }

  function _renderHelpSection(idx) {
    if (_helpRenderedCache[idx]) return _helpRenderedCache[idx];
    var sections = _parseHelpSections();
    if (!sections[idx]) return '';
    var html = '';
    try {
      html = marked.parse(sections[idx].markdown, { gfm: true });
    } catch (ex) {
      html = '<p>Error rendering help content.</p>';
    }
    _helpRenderedCache[idx] = html;
    return html;
  }

  function _detectHelpContext() {
    if (_navEditMode) return 'nav';
    var el = document.activeElement;
    if (el) {
      if (el.classList && el.classList.contains('md-editable-area')) return 'content';
      if (el.closest && el.closest('.md-editable-area')) return 'content';
      if (el.tagName === 'TEXTAREA') return 'content';
    }
    return 'all';
  }

  function _showHelp(context) {
    if (_helpModalOpen) { _dismissHelp(); return; }
    var sections = _parseHelpSections();
    if (!sections.length) return;

    context = context || _detectHelpContext();

    var visibleSections = [];
    for (var i = 0; i < sections.length; i++) {
      if (context === 'all' || sections[i].context === 'all' || sections[i].context === context) {
        visibleSections.push({ idx: i, section: sections[i] });
      }
    }
    if (!visibleSections.length) {
      for (var j = 0; j < sections.length; j++) {
        visibleSections.push({ idx: j, section: sections[j] });
      }
    }

    var initialTab = 0;
    for (var k = 0; k < visibleSections.length; k++) {
      if (visibleSections[k].section.context === context) {
        initialTab = k;
        break;
      }
    }

    var overlay = document.createElement('div');
    overlay.className = 'live-wysiwyg-help-overlay';

    var backdrop = document.createElement('div');
    backdrop.className = 'live-wysiwyg-help-backdrop';
    backdrop.addEventListener('click', function () { _dismissHelp(); });
    overlay.appendChild(backdrop);

    var modal = document.createElement('div');
    modal.className = 'live-wysiwyg-help-modal';

    var header = document.createElement('div');
    header.className = 'live-wysiwyg-help-header';
    var headerTitle = document.createElement('span');
    headerTitle.textContent = 'Help Reference';
    header.appendChild(headerTitle);
    var closeBtn = document.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'live-wysiwyg-help-close';
    closeBtn.innerHTML = '&#x2715;';
    closeBtn.addEventListener('click', function () { _dismissHelp(); });
    header.appendChild(closeBtn);
    modal.appendChild(header);

    var tabBar = document.createElement('div');
    tabBar.className = 'live-wysiwyg-help-tabs';

    var body = document.createElement('div');
    body.className = 'live-wysiwyg-help-body';

    var activeTabIdx = initialTab;

    function activateTab(tabIdx) {
      activeTabIdx = tabIdx;
      var tabs = tabBar.querySelectorAll('.live-wysiwyg-help-tab');
      for (var t = 0; t < tabs.length; t++) {
        if (t === tabIdx) tabs[t].classList.add('active');
        else tabs[t].classList.remove('active');
      }
      var vs = visibleSections[tabIdx];
      if (vs) {
        body.innerHTML = _renderHelpSection(vs.idx);
        body.scrollTop = 0;
      }
    }

    for (var vi = 0; vi < visibleSections.length; vi++) {
      var tab = document.createElement('button');
      tab.type = 'button';
      tab.className = 'live-wysiwyg-help-tab';
      tab.textContent = visibleSections[vi].section.title;
      tab.setAttribute('data-tab-idx', vi);
      tab.addEventListener('click', (function (idx) {
        return function () { activateTab(idx); };
      })(vi));
      tabBar.appendChild(tab);
    }

    modal.appendChild(tabBar);
    modal.appendChild(body);
    overlay.appendChild(modal);

    document.body.appendChild(overlay);
    _helpModalOpen = true;

    activateTab(initialTab);

    _attachDialogKeyboard(modal, {
      category: 'informational',
      onDismiss: function () { _dismissHelp(); },
      onConfirm: function () { _dismissHelp(); },
      autoFocus: closeBtn
    });

    modal.addEventListener('keydown', function (e) {
      if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
        e.preventDefault();
        var dir = e.key === 'ArrowLeft' ? -1 : 1;
        var next = activeTabIdx + dir;
        if (next >= 0 && next < visibleSections.length) {
          activateTab(next);
          var tabs = tabBar.querySelectorAll('.live-wysiwyg-help-tab');
          if (tabs[next]) tabs[next].focus();
        }
      }
    });
  }

  function _dismissHelp() {
    if (!_helpModalOpen) return;
    var overlay = document.querySelector('.live-wysiwyg-help-overlay');
    if (overlay) overlay.parentNode.removeChild(overlay);
    _helpModalOpen = false;
  }

  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;
    _focusSavedDocElOverflow = document.documentElement.style.overflow;
    document.body.style.overflow = 'hidden';
    document.documentElement.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 helpBtn = document.createElement('button');
    helpBtn.type = 'button';
    helpBtn.className = 'live-wysiwyg-focus-help-btn';
    helpBtn.title = 'Help (Ctrl+?)';
    helpBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>';
    helpBtn.addEventListener('click', function () {
      _showHelp();
    });
    header.appendChild(helpBtn);

    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 _slideToolbarWrap(wrap, show, cb) {
      if (!wrap) { if (cb) cb(); return; }
      if (wrap._slideAnim) { wrap._slideAnim.cancel(); wrap._slideAnim = null; }
      if (show) {
        wrap.classList.remove('focus-markdown-mode');
        wrap.style.display = 'flex';
        var h = wrap.scrollHeight;
        var anim = wrap.animate(
          [{ maxHeight: '0px', paddingTop: '0px', paddingBottom: '0px', opacity: 0 },
           { maxHeight: h + 'px', paddingTop: '4px', paddingBottom: '8px', opacity: 1 }],
          { duration: 150, easing: 'ease-in-out', fill: 'forwards' }
        );
        wrap._slideAnim = anim;
        anim.onfinish = function () {
          wrap._slideAnim = null;
          wrap.style.removeProperty('display');
          anim.cancel();
          if (cb) cb();
        };
      } else {
        var h = wrap.scrollHeight;
        var anim = wrap.animate(
          [{ maxHeight: h + 'px', paddingTop: '4px', paddingBottom: '8px', opacity: 1 },
           { maxHeight: '0px', paddingTop: '0px', paddingBottom: '0px', opacity: 0 }],
          { duration: 150, easing: 'ease-in-out', fill: 'forwards' }
        );
        wrap._slideAnim = anim;
        anim.onfinish = function () {
          wrap._slideAnim = null;
          wrap.classList.add('focus-markdown-mode');
          anim.cancel();
          if (cb) cb();
        };
      }
    }

    function _crossfadeContentSwitch(el, switchFn, cb) {
      if (!el) { switchFn(); if (cb) cb(); return; }
      if (el._crossfadeAnim) { el._crossfadeAnim.cancel(); el._crossfadeAnim = null; }
      var fadeOut = el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 80, easing: 'ease-in', fill: 'forwards' });
      el._crossfadeAnim = fadeOut;
      fadeOut.onfinish = function () {
        fadeOut.cancel();
        el.style.opacity = '0';
        switchFn();
        var fadeIn = el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 80, easing: 'ease-out', fill: 'forwards' });
        el._crossfadeAnim = fadeIn;
        fadeIn.onfinish = function () {
          fadeIn.cancel();
          el._crossfadeAnim = null;
          el.style.removeProperty('opacity');
          if (cb) cb();
        };
      };
    }

    function syncModeToggle(mode) {
      if (mode === 'wysiwyg') {
        wysBtn.classList.add('active');
        mdBtn.classList.remove('active');
        overlay.classList.remove('focus-mode-markdown');
      } else {
        mdBtn.classList.add('active');
        wysBtn.classList.remove('active');
        overlay.classList.add('focus-mode-markdown');
      }
      _updateToolbarHeight(overlay, drawer);
      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);
            if (wysiwygEditor && wysiwygEditor.markdownArea && wysiwygEditor.currentMode === 'markdown') {
              _updateHeadingTrackerMarkdown(wysiwygEditor.markdownArea);
            }
          };
        }
        if (!_focusMdPasteHandler) {
          _focusMdPasteHandler = function (e) {
            if (!_lastCopiedHeadingLink) return;
            var ta = wysiwygEditor && wysiwygEditor.markdownArea;
            if (!ta) return;
            var start = ta.selectionStart;
            var end = ta.selectionEnd;
            if (start === end) return;
            var pasted = (e.clipboardData || window.clipboardData || {}).getData('text');
            if (!pasted || pasted.trim() !== _lastCopiedHeadingLink.fullText) return;
            e.preventDefault();
            var selectedText = ta.value.substring(start, end);
            var curSrc = _getCurrentSrcPath();
            var link;
            if (_lastCopiedHeadingLink.srcPath === curSrc) {
              link = '#' + _lastCopiedHeadingLink.slug;
            } else {
              link = _computeRelativePath(_getDir(curSrc), _lastCopiedHeadingLink.srcPath) + '#' + _lastCopiedHeadingLink.slug;
            }
            var replacement = '[' + selectedText + '](' + link + ')';
            ta.setRangeText(replacement, start, end, 'end');
            ta.dispatchEvent(new Event('input', { bubbles: true }));
          };
        }
        ma.addEventListener('input', _focusMdInputHandler);
        ma.addEventListener('click', _focusMdCursorHandler);
        ma.addEventListener('keyup', _focusMdCursorHandler);
        ma.addEventListener('paste', _focusMdPasteHandler, true);
        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);
        }
        if (_focusMdPasteHandler) ma.removeEventListener('paste', _focusMdPasteHandler, true);
      }
    }

    wysBtn.addEventListener('click', function () {
      if (wysiwygEditor && wysiwygEditor.currentMode !== 'wysiwyg') {
        _checkHeadingMigrationBeforeNavigate();
        _slideToolbarWrap(toolbarWrap, true, function () {
          _updateToolbarHeight(overlay, drawer);
        });
        _crossfadeContentSwitch(wysiwygEditor.contentAreaContainer, function () {
          wysiwygEditor.switchToMode('wysiwyg');
          syncModeToggle('wysiwyg');
        }, function () {
          scrollToCenterCursor(wysiwygEditor.editableArea, false);
        });
      }
    });
    mdBtn.addEventListener('click', function () {
      if (wysiwygEditor && wysiwygEditor.currentMode !== 'markdown') {
        _checkHeadingMigrationBeforeNavigate();
        _slideToolbarWrap(toolbarWrap, false, function () {
          _updateToolbarHeight(overlay, drawer);
        });
        _crossfadeContentSwitch(wysiwygEditor.contentAreaContainer, function () {
          wysiwygEditor.switchToMode('markdown');
          syncModeToggle('markdown');
        }, 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);
    }

    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();
      if (_navSnapshots.length === 0 && typeof liveWysiwygNavData !== 'undefined' && liveWysiwygNavData.length) {
        var freshSnap = _takeNavSnapshot();
        var persisted = _restoreNavSnapshots();
        if (persisted) {
          var persistedDiskSnap = persisted.snapshots[persisted.diskSnapshotIndex];
          var freshDiskHash = _computeDiskStateHash(freshSnap);
          var persistedDiskHash = _computeDiskStateHash(persistedDiskSnap);
          if (freshDiskHash === persistedDiskHash) {
            var freshUidCounter = _uidCounter;
            _navSnapshots = persisted.snapshots;
            _navSnapshotIndex = persisted.snapshotIndex;
            _navDiskSnapshotIndex = persisted.diskSnapshotIndex;
            _uidCounter = Math.max(persisted.uidCounter || 0, freshUidCounter);
            _applySnapshotToGlobals(_navSnapshots[_navSnapshotIndex]);
          } else {
            _navSnapshots = persisted.snapshots;
            _navSnapshots.push(freshSnap);
            var newIdx = _navSnapshots.length - 1;
            _navSnapshotIndex = newIdx;
            _navDiskSnapshotIndex = newIdx;
            _uidCounter = Math.max(persisted.uidCounter || 0, _uidCounter);
            _applySnapshotToGlobals(freshSnap);
            _persistNavSnapshots();
          }
        } else {
          _navSnapshots = [freshSnap];
          _navSnapshotIndex = 0;
          _navDiskSnapshotIndex = 0;
          _persistNavSnapshots();
        }
      }
      _buildNavMenu(sidebarLeft);
      if (_navSnapshotIndex >= 0 && _navDiskSnapshotIndex >= 0 && _navSnapshotIndex !== _navDiskSnapshotIndex) {
        if (!_navEditMode) {
          _navCleanSnapshot = _navSnapshots[_navDiskSnapshotIndex];
          _navEditMode = true;
          if (_navSidebarEl) _navSidebarEl.classList.add('live-wysiwyg-nav-edit-mode');
        }
        _renderNavFromSnapshot();
      } else if (_navSnapshots.length >= 2 && _navSidebarEl) {
        _addNavEditActions(_navSidebarEl);
        _updateUndoRedoBtns();
      }
      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 copy heading link ---
    tocList.addEventListener('click', function (e) {
      var btn = e.target.closest('.live-wysiwyg-toc-copy-btn');
      if (!btn) return;
      e.preventDefault();
      e.stopPropagation();
      var slug = btn.getAttribute('data-toc-slug');
      if (!slug) return;
      var srcPath = _getCurrentSrcPath();
      var fullText = srcPath + '#' + slug;
      _lastCopiedHeadingLink = { srcPath: srcPath, slug: slug, fullText: fullText };
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(fullText).then(function () {
          _showToast('Copied heading link', 2000);
        }).catch(function () {
          _showToast('Copied heading link', 2000);
        });
      }
    });

    // --- 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();

    try {
      var backupRaw = sessionStorage.getItem('live_wysiwyg_content_backup');
      if (backupRaw) {
        sessionStorage.removeItem('live_wysiwyg_content_backup');
        var backup = JSON.parse(backupRaw);
        if (backup && backup.srcPath === _getCurrentSrcPath() && backup.content) {
          var ta = document.querySelector('.live-edit-source');
          var serverContent = ta ? ta.value : '';
          if (backup.content !== serverContent) {
            if (wysiwygEditor._loadContent) {
              wysiwygEditor._loadContent(backup.content);
            }
            if (wysiwygEditor._resetPristineContent) {
              wysiwygEditor._resetPristineContent(serverContent);
            }
          }
        }
      }
    } catch (e) { /* parse / storage error */ }

    _restoreContentHistory();

    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;
    _applyYmlTransform(function (y) { return _replaceDefaultPageWeight(y, 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;
    if (_historyModeActive) _exitHistoryMode();
    if (_mermaidModeActive) exitMermaidMode();

    _flushHistoryCapture();
    _deleteSetting('live_wysiwyg_focus_nav');

    _removeFocusModeGuard();

    _persistNavSnapshots();
    if (_navEditMode) _exitNavEditModeDestructive(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 (_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;
    document.documentElement.style.overflow = _focusSavedDocElOverflow;
    _focusSavedBodyOverflow = '';
    _focusSavedDocElOverflow = '';

    var styleEl = document.getElementById(FOCUS_MODE_STYLE_ID);
    if (styleEl && styleEl.parentNode) styleEl.parentNode.removeChild(styleEl);

    _restoreEditorSelection(savedSelection, null);
  }

  // --- Mermaid Mode (Layer 3) ---

  function _getMermaidModeCSS() {
    return '.live-wysiwyg-mermaid-overlay{' +
      'position:fixed;inset:0;z-index:99995;' +
      'display:flex;flex-direction:column;' +
      'background:var(--md-default-bg-color,#fff);' +
      'color:var(--md-default-fg-color,#212121);' +
      'font-family:var(--md-text-font-family,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,sans-serif);' +
    '}' +
    '.live-wysiwyg-mermaid-header{' +
      'display:flex;align-items:center;justify-content:space-between;' +
      'padding:8px 16px;' +
      'background:var(--md-primary-fg-color,#4051b5);' +
      'color:var(--md-primary-bg-color,#fff);' +
      'font-size:.85rem;flex-shrink:0;' +
    '}' +
    '.live-wysiwyg-mermaid-header-title{' +
      'font-weight:600;' +
    '}' +
    '.live-wysiwyg-mermaid-close-btn{' +
      'background:none;border:none;color:inherit;cursor:pointer;' +
      'font-size:1.2rem;padding:4px 8px;border-radius:4px;line-height:1;' +
    '}' +
    '.live-wysiwyg-mermaid-close-btn:hover{' +
      'background:rgba(255,255,255,0.15);' +
    '}' +
    '.live-wysiwyg-mermaid-body{' +
      'flex:1 1 0;min-height:0;overflow:hidden;' +
    '}' +
    '.live-wysiwyg-mermaid-body iframe{' +
      'width:100%;height:100%;border:none;' +
    '}';
  }

  function _encodeMermaidState(code) {
    var state = JSON.stringify({
      code: code,
      mermaid: '{\n  "theme": "default"\n}',
      autoSync: true,
      updateDiagram: true
    });
    var bytes = new TextEncoder().encode(state);
    var binary = '';
    for (var i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
    return 'base64:' + btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  }

  function enterMermaidMode(mermaidBlock) {
    if (_mermaidModeActive) return;
    if (_historyModeActive) return;
    if (!isFocusModeActive || !wysiwygEditor) return;

    var pre = mermaidBlock.querySelector('pre[data-lang="mermaid"]') || mermaidBlock.querySelector('pre');
    if (!pre) return;
    var codeEl = pre.querySelector('code') || pre;
    var mermaidCode = codeEl.textContent || '';

    _mermaidModeActive = true;
    _mermaidSourceBlock = mermaidBlock;
    _mermaidOriginalCode = mermaidCode;

    var apiBase = 'http://' + location.hostname + ':' + liveWysiwygLinkCheckPort;

    var styleEl = document.getElementById(MERMAID_MODE_STYLE_ID);
    if (!styleEl) {
      styleEl = document.createElement('style');
      styleEl.id = MERMAID_MODE_STYLE_ID;
      styleEl.textContent = _getMermaidModeCSS();
      document.head.appendChild(styleEl);
    }

    _mermaidSavedBodyOverflow = document.body.style.overflow;
    _mermaidSavedDocElOverflow = document.documentElement.style.overflow;
    document.body.style.overflow = 'hidden';
    document.documentElement.style.overflow = 'hidden';

    var overlay = document.createElement('div');
    overlay.className = 'live-wysiwyg-mermaid-overlay';
    _mermaidOverlay = overlay;

    var themeColors = _detectThemeColors();
    for (var varName in themeColors) {
      if (themeColors.hasOwnProperty(varName)) {
        overlay.style.setProperty(varName, themeColors[varName]);
      }
    }

    var header = document.createElement('div');
    header.className = 'live-wysiwyg-mermaid-header';

    var titleSpan = document.createElement('span');
    titleSpan.className = 'live-wysiwyg-mermaid-header-title';
    titleSpan.textContent = 'Mermaid Diagram Editor';
    header.appendChild(titleSpan);

    var closeBtn = document.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'live-wysiwyg-mermaid-close-btn';
    closeBtn.title = 'Close Mermaid Editor (Esc)';
    closeBtn.innerHTML = '&#x2715;';
    closeBtn.addEventListener('click', function () {
      console.log('[MERMAID-PARENT] X button clicked');
      _requestMermaidClose();
    });
    header.appendChild(closeBtn);

    var body = document.createElement('div');
    body.className = 'live-wysiwyg-mermaid-body';

    var iframe = document.createElement('iframe');
    iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
    _mermaidIframe = iframe;

    body.appendChild(iframe);
    overlay.appendChild(header);
    overlay.appendChild(body);
    document.body.appendChild(overlay);

    function onMermaidMessage(evt) {
      if (!_mermaidModeActive) return;
      var data = evt.data;
      if (!data || typeof data !== 'object') return;

      if (data.type === 'live-wysiwyg-mermaid-close') {
        console.log('[MERMAID-PARENT] close signal received, save=' + !!data.save);
        var doSave = !!data.save;
        _exitMermaidModeAsync(function () {
          if (doSave) {
            if (isFocusModeActive) {
              _flushHistoryCapture();
              _doFocusSaveBackground();
            } else {
              var _saveBtn = document.querySelector('.live-edit-save-button');
              if (_saveBtn && !_saveBtn.classList.contains('live-edit-hidden')) {
                _saveBtn.click();
              }
            }
          }
        });
      }

      if (data.type === 'live-wysiwyg-open-url' && typeof data.url === 'string') {
        var _allowedDomains = [
          'discord.com',
          'discord.gg',
          'github.com',
          'mermaid.js.org'
        ];
        try {
          var _u = new URL(data.url);
          if (_u.protocol === 'https:' || _u.protocol === 'http:') {
            var _allowed = false;
            for (var _di = 0; _di < _allowedDomains.length; _di++) {
              if (_u.hostname === _allowedDomains[_di] ||
                  _u.hostname.endsWith('.' + _allowedDomains[_di])) {
                _allowed = true;
                break;
              }
            }
            if (_allowed) {
              window.open(data.url, '_blank');
            }
          }
        } catch (_urlErr) {}
      }
    }
    overlay._mermaidMessageHandler = onMermaidMessage;
    window.addEventListener('message', onMermaidMessage);

    fetch(apiBase + '/mermaid-session', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code: mermaidCode })
    }).then(function (resp) { return resp.json(); })
      .then(function (result) {
        _mermaidSessionId = result.sessionId;
        iframe.src = apiBase + '/mermaid-editor/edit?session=' +
          _mermaidSessionId + '#' + _encodeMermaidState(mermaidCode);
        console.log('[MERMAID-PARENT] session created: ' + _mermaidSessionId);
      })
      .catch(function (err) {
        console.log('[MERMAID-PARENT] session create failed:', err);
        iframe.src = apiBase + '/mermaid-editor/edit#' + _encodeMermaidState(mermaidCode);
      });
  }


  function _requestMermaidClose(save) {
    console.log('[MERMAID-PARENT] _requestMermaidClose called, save=' + !!save);
    if (!_mermaidModeActive) return;
    if (_mermaidIframe && _mermaidIframe.contentWindow) {
      try {
        var msg = { type: 'live-wysiwyg-mermaid-request-close' };
        if (save) msg.save = true;
        _mermaidIframe.contentWindow.postMessage(msg, '*');
      } catch (ex) {
        _exitMermaidModeAsync();
        return;
      }
      setTimeout(function () {
        if (_mermaidModeActive) _exitMermaidModeAsync();
      }, 500);
    } else {
      _exitMermaidModeAsync();
    }
  }

  function _exitMermaidModeAsync(callback) {
    if (!_mermaidModeActive) return;
    _mermaidModeActive = false;

    var apiBase = 'http://' + location.hostname + ':' + liveWysiwygLinkCheckPort;
    var sessionId = _mermaidSessionId;

    function _applyCodeAndTeardown(finalCode) {
      var savedOriginalCode = _mermaidOriginalCode;

      if (finalCode && savedOriginalCode && finalCode !== savedOriginalCode &&
          _historyLastMd !== null && _historyCurrentId !== null && wysiwygEditor) {
        _flushHistoryCapture();

        var newMd = _replaceMermaidCodeBlock(_historyLastMd, savedOriginalCode, finalCode);
        if (newMd !== _historyLastMd) {
          var oldLines = _historyLastMd.split('\n');
          var newLines = newMd.split('\n');
          var diff = _computeLineDiff(oldLines, newLines);
          if (diff) {
            diff = _groupMarkdownConstructs(diff, newLines);
            var summary = _generateSummary(diff);
            var nodeId = _historyNextId++;
            var node = {
              id: nodeId,
              parentId: _historyCurrentId,
              children: [],
              activeChildId: null,
              diff: diff,
              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 = newMd;
          }
          _historySetContent(newMd);
        }
      }

      if (_mermaidOverlay) {
        if (_mermaidOverlay._mermaidMessageHandler) {
          window.removeEventListener('message', _mermaidOverlay._mermaidMessageHandler);
        }
        if (_mermaidOverlay.parentNode) {
          _mermaidOverlay.parentNode.removeChild(_mermaidOverlay);
        }
      }
      _mermaidOverlay = null;
      _mermaidIframe = null;
      _mermaidSourceBlock = null;
      _mermaidSessionId = '';
      _mermaidOriginalCode = '';

      document.body.style.overflow = _mermaidSavedBodyOverflow;
      document.documentElement.style.overflow = _mermaidSavedDocElOverflow;
      _mermaidSavedBodyOverflow = '';
      _mermaidSavedDocElOverflow = '';

      var styleEl = document.getElementById(MERMAID_MODE_STYLE_ID);
      if (styleEl && styleEl.parentNode) styleEl.parentNode.removeChild(styleEl);

      if (!_isMermaidConfiguredInYml(_virtualMkdocsYml)) {
        var pagePath = _getCurrentSrcPath();
        if (pagePath) _addCautionPage(pagePath, MERMAID_CONFIG_REASON);
        if (!_hasNavTopWarning('mermaid-config-missing')) {
          _navTopWarnings.push({
            id: 'mermaid-config-missing',
            text: 'Mermaid diagrams require pymdownx.superfences configuration in mkdocs.yml. Apply the fix to enable mermaid rendering.',
            icon: 'caution',
            title: 'Mermaid not configured',
            actionId: 'apply-mermaid-config',
            actionText: 'Apply to mkdocs.yml'
          });
          _ensureNavUncollapsed();
        }
      }

      if (callback) callback();
    }

    if (sessionId) {
      fetch(apiBase + '/mermaid-session/' + sessionId)
        .then(function (resp) {
          if (!resp.ok) throw new Error('GET session ' + resp.status);
          return resp.json();
        })
        .then(function (result) {
          var code = (typeof result.code === 'string') ? result.code : '';
          console.log('[MERMAID-EXIT] GET session code length=' + code.length);
          _applyCodeAndTeardown(code);
          fetch(apiBase + '/mermaid-session/' + sessionId, { method: 'DELETE' }).catch(function () {});
        })
        .catch(function (err) {
          console.log('[MERMAID-EXIT] GET session failed:', err);
          _applyCodeAndTeardown('');
        });
    } else {
      _applyCodeAndTeardown('');
    }
  }

  function exitMermaidMode() {
    _exitMermaidModeAsync();
  }

  var _PYTHON_NAME_TAG = '!!python/name:';

  function _preProcessYaml(yml) {
    return yml.replace(/!!python\/name:(\S+)/g, "'" + _PYTHON_NAME_TAG + "$1'");
  }

  function _postProcessYaml(yml) {
    return yml.replace(new RegExp("'" + _PYTHON_NAME_TAG.replace(/[/.]/g, '\\$&') + "(\\S+?)'", 'g'),
      _PYTHON_NAME_TAG + '$1');
  }

  function _yamlListItemKey(item) {
    if (typeof item === 'string') return item;
    if (item && typeof item === 'object') {
      var keys = Object.keys(item);
      if (keys.length > 0) return keys[0];
    }
    return JSON.stringify(item);
  }

  function _yamlDeepMerge(base, source, target) {
    var baseParsed, sourceParsed, targetParsed;
    try {
      baseParsed = jsyaml.load(_preProcessYaml(base || '')) || {};
      sourceParsed = jsyaml.load(_preProcessYaml(source || '')) || {};
      targetParsed = jsyaml.load(_preProcessYaml(target || '')) || {};
    } catch (e) {
      console.warn('[nav] _yamlDeepMerge: YAML parse error, falling back to source:', e);
      return source;
    }

    var LIST_KEYS = { plugins: true, markdown_extensions: true };

    function mergeValue(baseVal, sourceVal, targetVal, key) {
      if (JSON.stringify(baseVal) === JSON.stringify(sourceVal)) return targetVal;
      if (key && LIST_KEYS[key] && Array.isArray(baseVal) && Array.isArray(sourceVal) && Array.isArray(targetVal)) {
        return mergeList(baseVal, sourceVal, targetVal);
      }
      if (baseVal && sourceVal && typeof baseVal === 'object' && typeof sourceVal === 'object' &&
          !Array.isArray(baseVal) && !Array.isArray(sourceVal) &&
          targetVal && typeof targetVal === 'object' && !Array.isArray(targetVal)) {
        return mergeMap(baseVal, sourceVal, targetVal);
      }
      return sourceVal;
    }

    function mergeMap(baseMap, sourceMap, targetMap) {
      var result = {};
      var k;
      for (k in targetMap) {
        if (targetMap.hasOwnProperty(k)) result[k] = targetMap[k];
      }
      for (k in sourceMap) {
        if (!sourceMap.hasOwnProperty(k)) continue;
        if (baseMap.hasOwnProperty(k)) {
          result[k] = mergeValue(baseMap[k], sourceMap[k], result.hasOwnProperty(k) ? result[k] : sourceMap[k], k);
        } else {
          result[k] = sourceMap[k];
        }
      }
      for (k in baseMap) {
        if (baseMap.hasOwnProperty(k) && !sourceMap.hasOwnProperty(k)) {
          delete result[k];
        }
      }
      return result;
    }

    function mergeList(baseList, sourceList, targetList) {
      var baseKeys = {};
      for (var bi = 0; bi < baseList.length; bi++) {
        baseKeys[_yamlListItemKey(baseList[bi])] = baseList[bi];
      }
      var sourceKeys = {};
      for (var si = 0; si < sourceList.length; si++) {
        sourceKeys[_yamlListItemKey(sourceList[si])] = sourceList[si];
      }
      var result = [];
      for (var ti = 0; ti < targetList.length; ti++) {
        var tKey = _yamlListItemKey(targetList[ti]);
        if (baseKeys.hasOwnProperty(tKey) && !sourceKeys.hasOwnProperty(tKey)) {
          continue;
        }
        if (sourceKeys.hasOwnProperty(tKey)) {
          result.push(sourceKeys[tKey]);
        } else {
          result.push(targetList[ti]);
        }
      }
      for (var ai = 0; ai < sourceList.length; ai++) {
        var aKey = _yamlListItemKey(sourceList[ai]);
        if (!baseKeys.hasOwnProperty(aKey)) {
          var alreadyInResult = false;
          for (var ri = 0; ri < result.length; ri++) {
            if (_yamlListItemKey(result[ri]) === aKey) { alreadyInResult = true; break; }
          }
          if (!alreadyInResult) result.push(sourceList[ai]);
        }
      }
      return result;
    }

    var merged = mergeMap(baseParsed, sourceParsed, targetParsed);
    var dumped = jsyaml.dump(merged, { indent: 2, lineWidth: -1, noRefs: true });
    return _postProcessYaml(dumped);
  }

  function _isMermaidConfiguredInYml(yml) {
    if (!yml) return false;
    try {
      var parsed = jsyaml.load(_preProcessYaml(yml));
      if (!parsed || !Array.isArray(parsed.markdown_extensions)) return false;
      for (var i = 0; i < parsed.markdown_extensions.length; i++) {
        var ext = parsed.markdown_extensions[i];
        var sfConfig = null;
        if (typeof ext === 'object' && ext !== null && ext['pymdownx.superfences']) {
          sfConfig = ext['pymdownx.superfences'];
        }
        if (!sfConfig || !Array.isArray(sfConfig.custom_fences)) continue;
        for (var j = 0; j < sfConfig.custom_fences.length; j++) {
          var f = sfConfig.custom_fences[j];
          if (f.name === 'mermaid' &&
              f['class'] === 'mermaid' &&
              f.format === _PYTHON_NAME_TAG + 'pymdownx.superfences.fence_code_format') {
            return true;
          }
        }
      }
    } catch (e) {
      console.warn('[mermaid] Failed to parse mkdocs.yml for mermaid config check:', e);
    }
    return false;
  }

  function _addMermaidSuperfencesConfig(yml) {
    if (!yml) yml = '';
    var preProcessed = _preProcessYaml(yml);
    var parsed;
    try {
      parsed = jsyaml.load(preProcessed);
    } catch (e) {
      console.warn('[mermaid] Failed to parse mkdocs.yml for auto-fix:', e);
      return yml;
    }
    if (!parsed || typeof parsed !== 'object') parsed = {};

    if (!Array.isArray(parsed.markdown_extensions)) {
      parsed.markdown_extensions = [];
    }
    var mdExt = parsed.markdown_extensions;

    var sfConfig = null;
    for (var i = 0; i < mdExt.length; i++) {
      if (typeof mdExt[i] === 'string' && mdExt[i] === 'pymdownx.superfences') {
        mdExt[i] = { 'pymdownx.superfences': { custom_fences: [] } };
        sfConfig = mdExt[i]['pymdownx.superfences'];
        break;
      }
      if (typeof mdExt[i] === 'object' && mdExt[i] !== null &&
          mdExt[i]['pymdownx.superfences'] !== undefined) {
        sfConfig = mdExt[i]['pymdownx.superfences'];
        if (!sfConfig || typeof sfConfig !== 'object') {
          mdExt[i]['pymdownx.superfences'] = { custom_fences: [] };
          sfConfig = mdExt[i]['pymdownx.superfences'];
        }
        break;
      }
    }
    if (!sfConfig) {
      var entry = { 'pymdownx.superfences': { custom_fences: [] } };
      mdExt.push(entry);
      sfConfig = entry['pymdownx.superfences'];
    }
    if (!Array.isArray(sfConfig.custom_fences)) sfConfig.custom_fences = [];

    for (var j = 0; j < sfConfig.custom_fences.length; j++) {
      var f = sfConfig.custom_fences[j];
      if (f.name === 'mermaid' && f['class'] === 'mermaid') return yml;
    }

    sfConfig.custom_fences.push({
      name: 'mermaid',
      'class': 'mermaid',
      format: _PYTHON_NAME_TAG + 'pymdownx.superfences.fence_code_format'
    });

    var dumped = jsyaml.dump(parsed, { indent: 2, lineWidth: -1, noRefs: true });
    return _postProcessYaml(dumped);
  }

  var MERMAID_CONFIG_REASON = 'Mermaid diagrams require pymdownx.superfences configuration';

  _navCautionActions[MERMAID_CONFIG_REASON] = {
    text: 'Apply to mkdocs.yml',
    primary: true,
    handler: function (navItem) {
      if (!_navEditMode) _enterNavEditMode();
      _applyMermaidConfigFix();
      _removeNavTopWarning('mermaid-config-missing');
      _removeNavWarningReasonFromAll(null, MERMAID_CONFIG_REASON);
      _commitNavSnapshot();
    }
  };

  function _applyMermaidConfigFix() {
    if (_virtualMkdocsYml != null) {
      _applyYmlTransform(_addMermaidSuperfencesConfig);
      if (!_navBadges.some(function (b) { return b.text === 'Add mermaid to mkdocs.yml'; })) {
        _addNavBadge({
          className: 'live-wysiwyg-nav-normalize-badge',
          text: 'Add mermaid to mkdocs.yml'
        });
      }
    }
  }

  (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 () {
      if (isFocusModeActive) return;
      storeSelectionIfReadMode(window.getSelection());
      updateSelectionEditPopup();
    });
    document.addEventListener('mousedown', function (e) {
      if (isFocusModeActive) return;
      storeSelectionIfReadMode(window.getSelection());
      if (selectionEditPopup && selectionEditPopup.contains(e.target)) return;
      hideSelectionEditPopup();
    }, true);
    document.addEventListener('scroll', function () {
      if (isFocusModeActive) return;
      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) {
        if (_navEditMode && _isNavSaveable()) {
          _confirmNavSave();
        } else {
          _flushHistoryCapture();
          _doFocusSaveBackground();
        }
        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) {
      if (_compat.isComposing(e)) return;

      var dialogOpen = !!document.querySelector('.live-wysiwyg-nav-dialog') ||
                       !!document.querySelector('.live-wysiwyg-nav-settings-dropdown');

      if (e.key === 'Escape') {
        if (_mermaidModeActive) {
          console.log('[MERMAID-PARENT] Tier2 ESC intercepted, calling _requestMermaidClose');
          e.preventDefault(); e.stopImmediatePropagation();
          _requestMermaidClose();
          return;
        }
        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 (_mermaidModeActive) {
          console.log('[MERMAID-PARENT] Tier2 Ctrl+S intercepted, calling _requestMermaidClose(save=true)');
          e.preventDefault(); e.stopImmediatePropagation();
          _requestMermaidClose(true);
          return;
        }
        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 === '.') {
        if (_mermaidModeActive) return;
        _handleToggleMode(e);
        return;
      }

      if ((e.metaKey || e.ctrlKey) && e.shiftKey && (e.key === 'F' || e.key === 'f')) {
        if (isFocusModeActive && _focusOverlay) {
          e.preventDefault(); e.stopImmediatePropagation();
          var navCollapsed = _focusOverlay.classList.contains('live-wysiwyg-focus-nav-collapsed');
          var toolbarClosed = !_focusOverlay.classList.contains('live-wysiwyg-focus-toolbar-open');
          var tocCollapsed = _focusOverlay.classList.contains('live-wysiwyg-focus-toc-collapsed');
          var allCollapsed = navCollapsed && toolbarClosed && tocCollapsed;
          if (allCollapsed) {
            _focusOverlay.classList.remove('live-wysiwyg-focus-nav-collapsed');
            _focusOverlay.classList.add('live-wysiwyg-focus-toolbar-open');
            _focusOverlay.classList.remove('live-wysiwyg-focus-toc-collapsed');
            _setSetting('live_wysiwyg_focus_nav', '1');
            _setSetting('live_wysiwyg_focus_toolbar', '1');
            _setSetting('live_wysiwyg_focus_toc', '1');
          } else {
            _focusOverlay.classList.add('live-wysiwyg-focus-nav-collapsed');
            _focusOverlay.classList.remove('live-wysiwyg-focus-toolbar-open');
            _focusOverlay.classList.add('live-wysiwyg-focus-toc-collapsed');
            _setSetting('live_wysiwyg_focus_nav', '0');
            _setSetting('live_wysiwyg_focus_toolbar', '0');
            _setSetting('live_wysiwyg_focus_toc', '0');
          }
          var drawerEl = _focusOverlay.querySelector('.live-wysiwyg-focus-toolbar-drawer');
          if (drawerEl) _updateToolbarHeight(_focusOverlay, drawerEl);
          return;
        }
      }

      if ((e.metaKey || e.ctrlKey) && e.shiftKey && (e.key === '?' || e.code === 'Slash')) {
        e.preventDefault(); e.stopImmediatePropagation();
        _showHelp();
        return;
      }

      if (_helpModalOpen) 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')) {
        if (_mermaidModeActive) return;
        if (_undoViaBeforeinput) {
          _undoViaBeforeinput = false;
          e.preventDefault(); e.stopImmediatePropagation(); return;
        }
        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);
      }

      if (e.key === 'Meta' || e.key === 'Control') {
        _ctrlHeld = true;
        var _ea = wysiwygEditor && wysiwygEditor.editableArea;
        if (_ea) {
          var anchors = _ea.querySelectorAll('a[href]');
          for (var ai = 0; ai < anchors.length; ai++) {
            if (anchors[ai].matches(':hover')) { _showCtrlLinkOverlay(anchors[ai]); break; }
          }
        }
      }
    }, true);

    document.addEventListener('keyup', function (e) {
      if (e.key === 'Meta' || e.key === 'Control') {
        _ctrlHeld = false;
        _hideCtrlLinkOverlay();
      }
    }, true);

    window.addEventListener('blur', function () {
      _ctrlHeld = false;
      _hideCtrlLinkOverlay();
    });
  })();

  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._liveWysiwygTableData) {
            var twOnUpdate = _collectTableWidthsFromDOM(wysiwygEditor.editableArea);
            markdownContent = postprocessTables(markdownContent, wysiwygEditor._liveWysiwygTableData, twOnUpdate);
          }
          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;
            var wasSaveHidden = _upstreamSaveBtn && _upstreamSaveBtn.classList.contains('live-edit-hidden');
            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 (changed && wasSaveHidden && _upstreamSaveBtn) {
              _upstreamSaveBtn.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
          }
        },
      });
    } 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, htmlSnapshot) {
      textarea.value = markdown;
      var parsed = parseFrontmatter(markdown);
      wysiwygEditor._liveWysiwygFrontmatter = parsed.frontmatter;
      var bodyForPreprocess = extractRefDefsFromCommentBlocks(parsed.body);
      wysiwygEditor._liveWysiwygLinkData = preprocessMarkdownLinks(bodyForPreprocess);
      wysiwygEditor._liveWysiwygListMarkerData = preprocessListMarkers(bodyForPreprocess);
      wysiwygEditor._liveWysiwygTableData = preprocessTables(bodyForPreprocess);
      wysiwygEditor._liveWysiwygCodeBlockData = preprocessCodeBlocks(bodyForPreprocess);
      wysiwygEditor._liveWysiwygHrData = preprocessHorizontalRules(bodyForPreprocess);
      wysiwygEditor._liveWysiwygInlineCodeData = preprocessInlineCode(bodyForPreprocess);
      if (wysiwygEditor.currentMode === 'wysiwyg' && wysiwygEditor.editableArea) {
        if (htmlSnapshot) {
          wysiwygEditor.editableArea.innerHTML = htmlSnapshot;
          stripEnhancementArtifacts(wysiwygEditor.editableArea);
        } else {
          var html = wysiwygEditor._markdownToHtml(parsed.body);
          wysiwygEditor.editableArea.innerHTML = html;
        }
        if (window._normalizeTableAlignAttrs) window._normalizeTableAlignAttrs(wysiwygEditor.editableArea);
        populateRawHtmlBlocks(wysiwygEditor.editableArea);
        enhanceCodeBlocks(wysiwygEditor.editableArea);
        enhanceMermaidBlocks(wysiwygEditor.editableArea);
        enhanceBasicPreBlocks(wysiwygEditor.editableArea);
        enhanceChecklists(wysiwygEditor.editableArea);
        enhanceAdmonitions(wysiwygEditor.editableArea);
        enhanceImages(wysiwygEditor.editableArea);
      } 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');
        }
      }
    };

    _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 (_compat.isComposing(e)) 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.liveWysiwygHeadingPasteAttached) {
        ea.dataset.liveWysiwygHeadingPasteAttached = '1';
        ea.addEventListener('paste', function (e) {
          if (!_lastCopiedHeadingLink) return;
          var sel = window.getSelection();
          if (!sel || sel.isCollapsed || !sel.rangeCount) return;
          var pasted = _compat.getClipboardData(e, 'text');
          if (!pasted || pasted.trim() !== _lastCopiedHeadingLink.fullText) return;
          _flushHistoryCapture();
          e.preventDefault();
          var curSrc = _getCurrentSrcPath();
          var link;
          if (_lastCopiedHeadingLink.srcPath === curSrc) {
            link = '#' + _lastCopiedHeadingLink.slug;
          } else {
            link = _computeRelativePath(_getDir(curSrc), _lastCopiedHeadingLink.srcPath) + '#' + _lastCopiedHeadingLink.slug;
          }
          _compat.exec('createLink', false, link);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
        }, true);
      }
    })();

    (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 = _compat.getClipboardData(e, 'text');
          if (!pasted || !urlRe.test(pasted.trim())) return;
          _flushHistoryCapture();
          e.preventDefault();
          var url = pasted.trim();
          _compat.exec('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 = _compat.getClipboardData(e, '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);
      }
    })();

    var _pendingMultiBacktick = null;

    function _doInlineCodeConvert(anchorNode, openingIdx, closingIdx, sel, backtickCount) {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return false;
      var text = anchorNode.textContent;
      var inner, literal;
      if (backtickCount >= 2) {
        var ticks = '';
        for (var t = 0; t < backtickCount; t++) ticks += '`';
        inner = text.substring(openingIdx + backtickCount + 1, closingIdx - backtickCount);
        literal = ticks + ' ' + inner + ' ' + ticks;
      } 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);
      }
      _scheduleHistoryCapture(true);
      return 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();
          }
        };

        ea.addEventListener('input', function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          if (e.inputType !== 'insertText' || e.data !== '`') return;
          if (_pendingMultiBacktick) 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) === '`') {
            clearPending();
            return;
          }

          if (pendingBacktick && pendingBacktick.node === anchorNode) {
            var pIdx = pendingBacktick.offset;
            if (pIdx >= 0 && pIdx < closingIdx && text.charAt(pIdx) === '`') {
              clearPending();
              if (_doInlineCodeConvert(anchorNode, pIdx, closingIdx, sel, 1)) return;
              return;
            }
          }

          pendingBacktick = { node: anchorNode, offset: closingIdx };
        });
      }
    })();

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (ea && !ea.dataset.liveWysiwygTripleBacktickAttached) {
        ea.dataset.liveWysiwygTripleBacktickAttached = '1';

        function clearMultiPending() { _pendingMultiBacktick = null; }

        ea.addEventListener('blur', clearMultiPending);
        _ekh.multiCodeClear = 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') {
            clearMultiPending();
          }
        };

        function isInsidePreOrCodeCapture(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;
        }

        ea.addEventListener('input', function (e) {
          if (wysiwygEditor.currentMode !== 'wysiwyg') return;
          if (e.inputType !== 'insertText') return;
          var ch = e.data;
          if (ch !== '`' && ch !== ' ') 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 (isInsidePreOrCodeCapture(anchorNode)) return;
          var text = anchorNode.textContent;

          if (ch === ' ') {
            if (_pendingMultiBacktick && _pendingMultiBacktick.node === anchorNode) {
              var expectedCount = _pendingMultiBacktick.count;
              var closeRun = 0;
              var cp = anchorOffset - 2;
              while (cp >= 0 && text.charAt(cp) === '`') { closeRun++; cp--; }
              if (closeRun === expectedCount && cp >= 0 && text.charAt(cp) === ' ') {
                var openIdx = _pendingMultiBacktick.offset;
                clearMultiPending();
                anchorNode.textContent = text.substring(0, anchorOffset - 1) + text.substring(anchorOffset);
                if (_doInlineCodeConvert(anchorNode, openIdx, anchorOffset - 2, sel, expectedCount)) {
                  e.stopImmediatePropagation();
                  return;
                }
                anchorNode.textContent = text;
                var rr = document.createRange();
                rr.setStart(anchorNode, anchorOffset);
                rr.collapse(true);
                sel.removeAllRanges();
                sel.addRange(rr);
              }
            }
            if (!_pendingMultiBacktick) {
              var runLen = 0;
              var pos = anchorOffset - 2;
              while (pos >= 0 && text.charAt(pos) === '`') { runLen++; pos--; }
              if (runLen >= 2) {
                _pendingMultiBacktick = { node: anchorNode, offset: pos + 1, count: runLen };
                return;
              }
            }
            return;
          }

          // Existing block code creation: ``` at line-start
          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;
          }
          _flushHistoryCapture();
          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);
          enhanceMermaidBlocks(ea);
          enhanceBasicPreBlocks(ea);
          populateRawHtmlBlocks(ea);
          enhanceAdmonitions(ea);
          enhanceImages(ea);
          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);
          if (wysiwygEditor._finalizeUpdate) {
            wysiwygEditor._finalizeUpdate(ea.innerHTML);
          }
          _scheduleHistoryCapture(true);
        }, true);
      }

    // ── Inline element arrow-key escape and Enter splitting ──
    (function inlineElementEscapeSetup() {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;

      var INLINE_ESCAPE_TAGS = { CODE: 1, STRONG: 1, EM: 1, DEL: 1, A: 1, B: 1 };

      function findInlineAncestor(node) {
        var n = node;
        var anc = n.nodeType === 3 ? n.parentNode : n;
        while (anc && anc !== ea) {
          if (INLINE_ESCAPE_TAGS[anc.nodeName]) {
            if (anc.nodeName === 'CODE' && anc.parentNode && anc.parentNode.nodeName === 'PRE') return null;
            return anc;
          }
          if (anc.nodeName === 'PRE') return null;
          anc = anc.parentNode;
        }
        return null;
      }

      function isAtEnd(inlineEl, anchorNode, anchorOffset) {
        if (anchorNode === inlineEl) return anchorOffset >= inlineEl.childNodes.length;
        if (anchorNode.nodeType === 3 && anchorNode.parentNode === inlineEl) {
          if (anchorOffset < anchorNode.textContent.length) return false;
          var sib = anchorNode.nextSibling;
          while (sib) {
            if (sib.nodeType === 3 && sib.textContent.replace(/[\u200B\u200C\u200D\uFEFF]/g, '').length > 0) return false;
            if (sib.nodeType === 1) return false;
            sib = sib.nextSibling;
          }
          return true;
        }
        return false;
      }

      function isAtStart(inlineEl, anchorNode, anchorOffset) {
        if (anchorNode === inlineEl) return anchorOffset === 0;
        if (anchorNode.nodeType === 3 && anchorNode.parentNode === inlineEl) {
          var effectiveOffset = anchorOffset;
          var txt = anchorNode.textContent || '';
          while (effectiveOffset > 0 && /[\u200B\u200C\u200D\uFEFF]/.test(txt.charAt(effectiveOffset - 1))) effectiveOffset--;
          if (effectiveOffset > 0) return false;
          var sib = anchorNode.previousSibling;
          while (sib) {
            if (sib.nodeType === 3 && sib.textContent.replace(/[\u200B\u200C\u200D\uFEFF]/g, '').length > 0) return false;
            if (sib.nodeType === 1) return false;
            sib = sib.previousSibling;
          }
          return true;
        }
        return false;
      }

      function ensureTextNodeAfter(inlineEl) {
        var next = inlineEl.nextSibling;
        if (next && next.nodeType === 3) return next;
        var tn = document.createTextNode('\u200B');
        if (inlineEl.nextSibling) {
          inlineEl.parentNode.insertBefore(tn, inlineEl.nextSibling);
        } else {
          inlineEl.parentNode.appendChild(tn);
        }
        return tn;
      }

      function ensureTextNodeBefore(inlineEl) {
        var prev = inlineEl.previousSibling;
        if (prev && prev.nodeType === 3) return prev;
        var tn = document.createTextNode('\u200B');
        inlineEl.parentNode.insertBefore(tn, inlineEl);
        return tn;
      }

      _ekh.inlineArrowEscape = function (e) {
        if (e.shiftKey) return;
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        var sel = window.getSelection();
        if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
        var anchorNode = sel.anchorNode;
        var anchorOffset = sel.anchorOffset;
        if (!anchorNode) return;
        var inlineEl = findInlineAncestor(anchorNode);
        if (!inlineEl) return;

        var isRight = e.key === 'ArrowRight';
        if (isRight && isAtEnd(inlineEl, anchorNode, anchorOffset)) {
          e.preventDefault();
          var afterNode = ensureTextNodeAfter(inlineEl);
          var startOff = (afterNode.textContent.length > 0 && /[\u200B\u200C\u200D\uFEFF]/.test(afterNode.textContent.charAt(0))) ? 1 : 0;
          var range = document.createRange();
          range.setStart(afterNode, startOff);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
        } else if (!isRight && isAtStart(inlineEl, anchorNode, anchorOffset)) {
          e.preventDefault();
          var beforeNode = ensureTextNodeBefore(inlineEl);
          var endOff = beforeNode.textContent.length;
          if (endOff > 0 && /[\u200B\u200C\u200D\uFEFF]/.test(beforeNode.textContent.charAt(endOff - 1))) endOff--;
          var range = document.createRange();
          range.setStart(beforeNode, endOff);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
        }
      };

      function findContainingBlock(node) {
        var anc = node;
        while (anc && anc !== ea) {
          if (anc.nodeName === 'P' || anc.nodeName === 'LI' || anc.nodeName === 'DIV' ||
              (anc.nodeName.match && anc.nodeName.match(/^H[1-6]$/))) {
            if (anc.nodeName === 'DIV' && anc === ea) break;
            return anc;
          }
          anc = anc.parentNode;
        }
        return null;
      }

      function collectNodesAfter(refNode, container) {
        var nodes = [];
        var sib = refNode.nextSibling;
        while (sib) {
          nodes.push(sib);
          sib = sib.nextSibling;
        }
        if (refNode.parentNode !== container) {
          var parent = refNode.parentNode;
          sib = parent.nextSibling;
          while (sib) {
            nodes.push(sib);
            sib = sib.nextSibling;
          }
        }
        return nodes;
      }

      _ekh.inlineEnterEscape = function (e) {
        if (e.shiftKey) return;
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        var sel = window.getSelection();
        if (!sel || !sel.isCollapsed || !sel.rangeCount) return;
        var anchorNode = sel.anchorNode;
        var anchorOffset = sel.anchorOffset;
        if (!anchorNode) return;
        var inlineEl = findInlineAncestor(anchorNode);
        if (!inlineEl) return;

        var block = findContainingBlock(inlineEl);
        if (!block) return;

        e.preventDefault();
        _flushHistoryCapture();

        var atEnd = isAtEnd(inlineEl, anchorNode, anchorOffset);
        var atStart = isAtStart(inlineEl, anchorNode, anchorOffset);

        var newBlock;
        if (block.nodeName === 'LI') {
          newBlock = document.createElement('li');
        } else {
          newBlock = document.createElement('p');
        }

        if (atStart) {
          var nodesFromInline = [];
          var sib = inlineEl;
          while (sib) {
            nodesFromInline.push(sib);
            sib = sib.nextSibling;
          }
          for (var i = 0; i < nodesFromInline.length; i++) {
            newBlock.appendChild(nodesFromInline[i]);
          }
          if (!block.hasChildNodes() || (block.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '').length === 0) {
            block.innerHTML = '<br>';
          }
          if (block.nodeName === 'LI' && block.parentNode) {
            block.parentNode.insertBefore(newBlock, block.nextSibling);
          } else {
            block.parentNode.insertBefore(newBlock, block.nextSibling);
          }
          var cursorTarget = newBlock.firstChild;
          if (!cursorTarget) { cursorTarget = document.createTextNode('\u200B'); newBlock.appendChild(cursorTarget); }
          var range = document.createRange();
          if (cursorTarget.nodeType === 3) {
            range.setStart(cursorTarget, 0);
          } else {
            range.setStart(newBlock, 0);
          }
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
        } else if (atEnd) {
          var nodesAfter = collectNodesAfter(inlineEl, block);
          var hasContentAfter = false;
          for (var i = 0; i < nodesAfter.length; i++) {
            var nodeText = (nodesAfter[i].textContent || '').replace(/[\u200B\u200C\u200D\uFEFF]/g, '').trim();
            if (nodeText.length > 0 || (nodesAfter[i].nodeType === 1 && nodesAfter[i].nodeName !== 'BR')) {
              hasContentAfter = true;
              break;
            }
          }
          if (hasContentAfter) {
            for (var i = 0; i < nodesAfter.length; i++) {
              newBlock.appendChild(nodesAfter[i]);
            }
          } else {
            for (var i = 0; i < nodesAfter.length; i++) {
              if (nodesAfter[i].parentNode) nodesAfter[i].parentNode.removeChild(nodesAfter[i]);
            }
            newBlock.innerHTML = '<br>';
          }
          block.parentNode.insertBefore(newBlock, block.nextSibling);
          var cursorTarget = newBlock.firstChild;
          if (!cursorTarget) { cursorTarget = document.createTextNode('\u200B'); newBlock.appendChild(cursorTarget); }
          var range = document.createRange();
          if (cursorTarget.nodeType === 3) {
            range.setStart(cursorTarget, 0);
          } else {
            range.setStart(newBlock, 0);
          }
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
        } else {
          var text = anchorNode.textContent || '';
          var leftText = text.substring(0, anchorOffset);
          var rightText = text.substring(anchorOffset);

          anchorNode.textContent = leftText;

          var cloned = document.createElement(inlineEl.nodeName);
          for (var ai = 0; ai < inlineEl.attributes.length; ai++) {
            var attr = inlineEl.attributes[ai];
            if (attr.name === 'data-md-literal') continue;
            cloned.setAttribute(attr.name, attr.value);
          }
          cloned.textContent = rightText;

          var nodesAfterInline = collectNodesAfter(inlineEl, block);
          if (rightText.replace(/[\u200B\u200C\u200D\uFEFF]/g, '').length > 0) {
            newBlock.appendChild(cloned);
          } else {
            if (rightText) {
              newBlock.appendChild(document.createTextNode(rightText));
            }
          }
          for (var i = 0; i < nodesAfterInline.length; i++) {
            newBlock.appendChild(nodesAfterInline[i]);
          }
          if (!newBlock.hasChildNodes()) newBlock.innerHTML = '<br>';

          var trailingInOriginal = inlineEl.nextSibling;
          while (trailingInOriginal) {
            var next = trailingInOriginal.nextSibling;
            if (trailingInOriginal.nodeType === 3) {
              var trimmed = trailingInOriginal.textContent.replace(/[\u200B\u200C\u200D\uFEFF]/g, '');
              if (trimmed.length === 0) { trailingInOriginal.parentNode.removeChild(trailingInOriginal); }
            }
            trailingInOriginal = next;
          }

          if (leftText.replace(/[\u200B\u200C\u200D\uFEFF]/g, '').length === 0) {
            if (inlineEl.parentNode) inlineEl.parentNode.removeChild(inlineEl);
            if (!block.hasChildNodes() || (block.textContent || '').replace(/[\u200B\u200C\u200D\uFEFF\s]/g, '').length === 0) {
              block.innerHTML = '<br>';
            }
          }

          block.parentNode.insertBefore(newBlock, block.nextSibling);
          var cursorTarget = newBlock.firstChild;
          if (!cursorTarget) { cursorTarget = document.createTextNode('\u200B'); newBlock.appendChild(cursorTarget); }
          var range = document.createRange();
          if (cursorTarget.nodeType === 3) {
            range.setStart(cursorTarget, 0);
          } else {
            range.setStart(newBlock, 0);
          }
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
        }

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

    (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 || _getSetting('live_wysiwyg_unicode_emoji') === '1') {
          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 sorted = 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);
        });
        var limit;
        if (prefix.length === 0) {
          limit = sorted.length;
        } else {
          var exactCount = 0;
          for (var ec = 0; ec < sorted.length; ec++) {
            if (sorted[ec].indexOf(prefix) >= 0) exactCount++;
            else break;
          }
          limit = exactCount + MAX_SUGGESTIONS;
        }
        var matches = sorted.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);
        });
        pop.style.visibility = 'hidden';
        document.body.appendChild(pop);
        var rect = anchorRect || { left: 0, top: 0, bottom: 20 };
        var popH = pop.offsetHeight;
        var popW = pop.offsetWidth;
        var top = rect.bottom + 4;
        if (top + popH > window.innerHeight - 8 && rect.top > popH + 8) {
          top = rect.top - popH - 4;
        }
        var left = rect.left;
        if (left + popW > window.innerWidth - 8) {
          left = Math.max(4, window.innerWidth - popW - 8);
        }
        if (left < 4) left = 4;
        pop.style.left = left + 'px';
        pop.style.top = top + 'px';
        pop.style.visibility = '';
        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 range = sel.getRangeAt(0);
              var r = _compat.getRangeRect(range);
              if (!r || (r.width === 0 && r.height === 0)) {
                r = node.getBoundingClientRect ? node.getBoundingClientRect() : ea.getBoundingClientRect();
              }
              var anchorRect = { left: r.left, top: r.top, 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 = _compat.getRangeRect(sel.getRangeAt(0));
            if (!r || (r.width === 0 && r.height === 0)) {
              r = ea.getBoundingClientRect();
            }
            var anchorRect = { left: r.left, top: r.top, 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 if (_getSetting('live_wysiwyg_unicode_emoji') === '1') {
                  sel.removeAllRanges();
                  sel.addRange(savedRange);
                  savedRange.deleteContents();
                  var uniNode = document.createTextNode(emoji);
                  savedRange.insertNode(uniNode);
                  node = uniNode;
                  insertEnd = 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 && (_compat.isPrintableKey(e) || 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'];
        var cbm;
        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]);
          cbm = beforeCursor.match(/^```(\w+) $/);
          if (cbm) return doCodeBlock(anchorNode, block, countPrefixLen(raw, cbm[0].length), sel, cbm[1], '```' + cbm[1]);
        } 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] + ' ');
          cbm = beforeCursor.match(/^```(\w+)$/);
          if (cbm) return doCodeBlock(anchorNode, block, countPrefixLen(raw, cbm[0].length), sel, cbm[1], '```' + cbm[1]);
        }
        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);
        _compat.exec(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;
      }

      function doCodeBlock(textNode, block, prefixLen, sel, lang, literal) {
        var MERMAID_DEFAULT = 'stateDiagram-v2\n    [*] --> Still\n    Still --> [*]\n    Still --> Moving\n    Moving --> Still\n    Moving --> Crash\n    Crash --> [*]\n';
        stripPrefix(textNode, prefixLen);
        var pre = document.createElement('pre');
        pre.setAttribute('data-lang', lang);
        pre.setAttribute('data-md-literal', literal);
        var code = document.createElement('code');
        code.textContent = (lang === 'mermaid') ? MERMAID_DEFAULT : '\n';
        pre.appendChild(code);
        if (block === ea) {
          ea.replaceChild(pre, textNode.parentNode === ea ? textNode : block);
        } else {
          block.parentNode.replaceChild(pre, block);
        }
        enhanceCodeBlocks(ea);
        enhanceMermaidBlocks(ea);
        enhanceBasicPreBlocks(ea);
        populateRawHtmlBlocks(ea);
        enhanceAdmonitions(ea);
        enhanceImages(ea);
        if (lang === 'mermaid') {
          var wrapper = pre.parentNode;
          if (wrapper && wrapper.classList && wrapper.classList.contains('md-mermaid-block')) {
            var pAfter = document.createElement('p');
            pAfter.innerHTML = '<br>';
            if (wrapper.nextSibling) {
              wrapper.parentNode.insertBefore(pAfter, wrapper.nextSibling);
            } else {
              wrapper.parentNode.appendChild(pAfter);
            }
            var range = document.createRange();
            range.setStart(pAfter, 0);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            ea.focus();
          }
        } else {
          var codeEl = pre.querySelector('code') || pre;
          var tn = codeEl.firstChild;
          if (!tn || tn.nodeType !== 3) {
            tn = document.createTextNode('\n');
            codeEl.appendChild(tn);
          }
          var range = document.createRange();
          range.setStart(tn, 0);
          range.collapse(true);
          sel.removeAllRanges();
          sel.addRange(range);
        }
        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/end (non-CODE) or immediately after (all inline elements)
        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;
            if (anc.nodeName !== 'CODE') {
              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) {
          _flushHistoryCapture();
          if (handleRevertOnBackspace(sel)) {
            e.preventDefault();
            e.stopImmediatePropagation();
            if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
            _scheduleHistoryCapture(true);
            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;
        _flushHistoryCapture();
        var converted = handleBlockConversions(anchorNode, anchorOffset, sel, false);
        if (converted) {
          e.preventDefault();
          if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
          _scheduleHistoryCapture(true);
        }
      };

      // ── 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) {
            _flushHistoryCapture();
            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) {
          if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
          _scheduleHistoryCapture(true);
        }
      });
    })();

    (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);
        var useUnicode = _getSetting('live_wysiwyg_unicode_emoji') === '1';
        protected_ = protected_.replace(shortcodeRe, function (m, key) {
          var em = EMOJI_MAP[key];
          if (!em) return m;
          return useUnicode ? em : emojiToImgHtml(":" + key + ":", em);
        });
        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;
      proto._markdownToHtml = function (markdown) {
        var md = markdown || "";
        var html = origMarkdownToHtml.call(this, md);
        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 rawText = node.textContent || '';
          var CM_PH = '\uFFFF__CM__\uFFFF';
          var CME_PH = '\uFFFF__CME__\uFFFF';
          var withPH = rawText.replace(CURSOR_MARKER_RE, CM_PH).replace(CURSOR_MARKER_END_RE, CME_PH);
          var cleanContent = withPH.replace(/[\u200B\u200C\u200D\uFEFF]/g, '').trim();
          var codeContent = cleanContent.replace(/\uFFFF__CM__\uFFFF/g, CURSOR_MARKER).replace(/\uFFFF__CME__\uFFFF/g, CURSOR_MARKER_END);
          if (options && options.inTableCell) codeContent = codeContent.replace(/\|/g, '\\|');
          var fenceContent = cleanContent.replace(/\uFFFF__CM__\uFFFF/g, '').replace(/\uFFFF__CME__\uFFFF/g, '');
          if (fenceContent.indexOf('`') >= 0) {
            var needed = 1, brun = 0;
            for (var ci = 0; ci < fenceContent.length; ci++) {
              if (fenceContent.charAt(ci) === '`') { brun++; if (brun >= needed) needed = brun + 1; }
              else { brun = 0; }
            }
            var ticks = '';
            for (var ti = 0; ti < needed; ti++) ticks += '`';
            return ticks + ' ' + codeContent + ' ' + ticks;
          }
          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);
        if (window._normalizeTableAlignAttrs) window._normalizeTableAlignAttrs(wysiwygEditor.editableArea);
        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, .md-mermaid-block');
            for (var ci = 0; ci < allCodeBlocks.length; ci++) {
              var cb = allCodeBlocks[ci];
              if (!r.intersectsNode(cb)) continue;
              if (cb.classList.contains('md-mermaid-block')) {
                toRemove.push(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();
            _flushHistoryCapture();
            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, .md-mermaid-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);
            }
            _scheduleHistoryCapture(true);
            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');
            _flushHistoryCapture();
            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);
            }
            _scheduleHistoryCapture(true);
            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, .md-mermaid-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, .md-mermaid-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') || cn.classList.contains('md-code-copy-btn'))) 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') || en.classList.contains('md-code-copy-btn'))) 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') || cn.classList.contains('md-code-copy-btn'))) 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') ||
             n.classList.contains('md-code-copy-btn');
    }

    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 _isSelectableTarget(node, ea) {
      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('md-mermaid-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;
    }

    function _selectionCrossesTitleBoundary(sel) {
      if (!sel || !sel.rangeCount) return false;
      var range = sel.getRangeAt(0);
      var startNode = range.startContainer;
      var endNode = range.endContainer;
      if (startNode.nodeType === 3) startNode = startNode.parentNode;
      if (endNode.nodeType === 3) endNode = endNode.parentNode;

      var titleSelectors = ['.admonition-title', '.md-code-title'];
      for (var ti = 0; ti < titleSelectors.length; ti++) {
        var startTitle = startNode.closest ? startNode.closest(titleSelectors[ti]) : null;
        var endTitle = endNode.closest ? endNode.closest(titleSelectors[ti]) : null;
        if (startTitle !== endTitle) return true;
      }
      return false;
    }

    function _buildProgressiveRanges(sel, ea) {
      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, ea)) {
          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));
      return targetRanges;
    }

    (function () {
      var ea = wysiwygEditor.editableArea;
      if (!ea) return;

        _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 = _buildProgressiveRanges(sel, 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('beforeinput', function (e) {
        if (e.inputType === 'historyUndo') {
          e.preventDefault();
          _undoViaBeforeinput = true;
          _contentUndo();
        } else if (e.inputType === 'historyRedo') {
          e.preventDefault();
          _undoViaBeforeinput = true;
          _contentRedo();
        } else if (_historyBranchPopup) {
          _dismissHistoryBranchPopup();
        }
      });

      ea.addEventListener('keydown', function _editorKeydownRouter(e) {
        if (_navEditMode) return;
        if (_mermaidModeActive) return;
        if (_compat.isComposing(e)) return;
        if (_ekh.inlineCodeClear) _ekh.inlineCodeClear(e);
        if (_ekh.multiCodeClear) _ekh.multiCodeClear(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.inlineEnterEscape) { _ekh.inlineEnterEscape(e); if (e.defaultPrevented) return; }
          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.inlineArrowEscape) { _ekh.inlineArrowEscape(e); if (e.defaultPrevented) return; }
          if (_ekh.checklistArrow) _ekh.checklistArrow(e);
        } else if (key === 'a' && (e.metaKey || e.ctrlKey)) {
          if (_ekh.progressiveSelectAll) _ekh.progressiveSelectAll(e);
        } else if (key === 'b' && (e.metaKey || e.ctrlKey)) {
          e.preventDefault();
          _flushHistoryCapture();
          _compat.exec('bold');
          wysiwygEditor._finalizeUpdate(ea.innerHTML);
        } else if (key === 'i' && (e.metaKey || e.ctrlKey)) {
          e.preventDefault();
          _flushHistoryCapture();
          _compat.exec('italic');
          wysiwygEditor._finalizeUpdate(ea.innerHTML);
        } else if (key === 'Tab') {
          e.preventDefault();
          _flushHistoryCapture();
          var sel = window.getSelection();
          if (sel && sel.rangeCount > 0) {
            var range = sel.getRangeAt(0);
            var ancestor = range.commonAncestorContainer;
            if (ancestor.nodeType === 3) ancestor = ancestor.parentNode;
            var listItem = wysiwygEditor._findParentElement(ancestor, 'LI');
            var list = wysiwygEditor._findParentElement(ancestor, ['UL', 'OL']);
            var inList = !!(listItem || (list && (list.nodeName === 'UL' || list.nodeName === 'OL')));
            var tableCell = wysiwygEditor._findParentElement(ancestor, ['TD', 'TH']);
            if (inList) {
              if (wysiwygEditor._listIndentOutdentByDOM(e.shiftKey)) {
                wysiwygEditor._finalizeUpdate(ea.innerHTML);
              } else {
                _compat.exec(e.shiftKey ? 'outdent' : 'indent');
              }
            } else if (tableCell) {
              var table = wysiwygEditor._findParentElement(tableCell, 'TABLE');
              if (table) {
                var cells = [];
                var allCells = table.querySelectorAll('th, td');
                for (var ci = 0; ci < allCells.length; ci++) cells.push(allCells[ci]);
                var currentIndex = cells.indexOf(tableCell);
                var nextIndex = currentIndex + (e.shiftKey ? -1 : 1);
                if (nextIndex >= 0 && nextIndex < cells.length) {
                  var nextCell = cells[nextIndex];
                  wysiwygEditor._focusCell(nextCell);
                  var row = wysiwygEditor._findParentElement(nextCell, 'TR');
                  wysiwygEditor.currentTableSelectionInfo = { cell: nextCell, row: row, table: table, cellIndex: nextCell.cellIndex, rowIndex: row.rowIndex };
                  wysiwygEditor._showContextualTableToolbar(nextCell);
                } else if (!e.shiftKey && nextIndex >= cells.length) {
                  var nextFocusable = table.nextElementSibling;
                  while (nextFocusable && (nextFocusable.nodeName === '#text' || (!nextFocusable.hasAttribute('tabindex') && nextFocusable.nodeName !== 'P'))) {
                    nextFocusable = nextFocusable.nextElementSibling;
                  }
                  if (nextFocusable && nextFocusable.nodeName === 'P' && nextFocusable.firstChild) {
                    var tabRange = document.createRange();
                    tabRange.setStart(nextFocusable.firstChild, 0);
                    tabRange.collapse(true);
                    sel.removeAllRanges();
                    sel.addRange(tabRange);
                  } else if (nextFocusable) {
                    nextFocusable.focus();
                  }
                  wysiwygEditor._hideContextualTableToolbar();
                }
              }
            } else {
              _compat.exec('insertText', false, '    ');
            }
          } else {
            _compat.exec('insertText', false, '    ');
          }
        }
      }, true);

      var ma = wysiwygEditor.markdownArea;
      if (ma) {
        ma.addEventListener('keydown', function _markdownKeydownRouter(e) {
          if (_navEditMode) return;
          if (_mermaidModeActive) return;
          if (_compat.isComposing(e)) return;
          var key = e.key;
          if (key === 'Tab') {
            e.preventDefault();
            _flushHistoryCapture();
            var start = ma.selectionStart;
            var text = ma.value;
            var firstLineStart = text.lastIndexOf('\n', start - 1) + 1;
            var firstLineEnd = text.indexOf('\n', firstLineStart);
            var firstLine = text.substring(firstLineStart, firstLineEnd === -1 ? text.length : firstLineEnd);
            var handledByListLogic = false;
            if (/^(\*|-|\+|\d+\.)\s+/.test(firstLine.trim())) {
              if (e.shiftKey) {
                wysiwygEditor._applyMarkdownListOutdentInternal();
                handledByListLogic = true;
              } else {
                wysiwygEditor._applyMarkdownListIndentInternal();
                handledByListLogic = true;
              }
            }
            if (!handledByListLogic) {
              _compat.exec('insertText', false, '    ');
            }
            wysiwygEditor._finalizeUpdate(ma.value);
          } else if (key === 'b' && (e.metaKey || e.ctrlKey)) {
            e.preventDefault();
            _flushHistoryCapture();
            var boldCfg = null;
            for (var bi = 0; bi < wysiwygEditor.options.buttons.length; bi++) {
              if (wysiwygEditor.options.buttons[bi].id === 'bold') { boldCfg = wysiwygEditor.options.buttons[bi]; break; }
            }
            if (boldCfg) wysiwygEditor._applyMarkdownFormatting(boldCfg);
          } else if (key === 'i' && (e.metaKey || e.ctrlKey)) {
            e.preventDefault();
            _flushHistoryCapture();
            var italicCfg = null;
            for (var ii = 0; ii < wysiwygEditor.options.buttons.length; ii++) {
              if (wysiwygEditor.options.buttons[ii].id === 'italic') { italicCfg = wysiwygEditor.options.buttons[ii]; break; }
            }
            if (italicCfg) wysiwygEditor._applyMarkdownFormatting(italicCfg);
          }
        }, 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 (cl && cl.contains('md-mermaid-block')) return 'mermaidblock';
        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' };
            }
            if (c.node.nodeName === 'PRE' && c.node.parentNode &&
                c.node.parentNode.classList && c.node.parentNode.classList.contains('md-mermaid-block')) {
              return { node: c.node.parentNode, type: 'mermaidblock' };
            }
            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, .md-mermaid-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-code-copy-btn, .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);
        _compat.setClipboardData(e, '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 + ')';
        }
        _compat.setClipboardData(e, '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 && sel && !sel.isCollapsed && _selectionCrossesTitleBoundary(sel)) {
          var ranges = _buildProgressiveRanges(sel, ea);
          var cur = sel.rangeCount ? sel.getRangeAt(0) : null;
          if (cur) {
            for (var pi = 0; pi < ranges.length; pi++) {
              try {
                if (ranges[pi].compareBoundaryPoints(Range.START_TO_START, cur) <= 0 &&
                    ranges[pi].compareBoundaryPoints(Range.END_TO_END, cur) >= 0) {
                  sel.removeAllRanges();
                  sel.addRange(ranges[pi]);
                  block = findSelectedBlock(sel);
                  if (block) break;
                }
              } catch (ex) { /* different document roots */ }
            }
          }
        }
        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>';
          _compat.setClipboardData(e, '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 || ''; }
          _compat.setClipboardData(e, '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>';
        _compat.setClipboardData(e, '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 || '';
        }
        _compat.setClipboardData(e, '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 && sel && !sel.isCollapsed && _selectionCrossesTitleBoundary(sel)) {
          var ranges = _buildProgressiveRanges(sel, ea);
          var cur = sel.rangeCount ? sel.getRangeAt(0) : null;
          if (cur) {
            for (var pi = 0; pi < ranges.length; pi++) {
              try {
                if (ranges[pi].compareBoundaryPoints(Range.START_TO_START, cur) <= 0 &&
                    ranges[pi].compareBoundaryPoints(Range.END_TO_END, cur) >= 0) {
                  sel.removeAllRanges();
                  sel.addRange(ranges[pi]);
                  block = findSelectedBlock(sel);
                  if (block) break;
                }
              } catch (ex) { /* different document roots */ }
            }
          }
        }
        if (!block) return;

        e.preventDefault();

        if (block.type === 'list-item') {
          var wrapList = _wrapLiInList(block.node);
          var wrapperHtml = '<div ' + BLOCK_ATTR + '="list">' + wrapList.outerHTML + '</div>';
          _compat.setClipboardData(e, '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 || ''; }
          _compat.setClipboardData(e, 'text/plain', plainText);
          return;
        }

        var clone = block.node.cloneNode(true);
        stripCodeUIFromClone(clone);

        var wrapperHtml = '<div ' + BLOCK_ATTR + '="' + block.type + '">' + clone.outerHTML + '</div>';
        _compat.setClipboardData(e, '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 || '';
        }
        _compat.setClipboardData(e, '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, .md-mermaid-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, .md-mermaid-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 = _compat.getClipboardData(e, '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 'mermaidblock':
            var mermaidPre = blockContent.querySelector('pre[data-lang="mermaid"]') || blockContent.querySelector('pre');
            if (mermaidPre) blockContent = mermaidPre;
            pasteCodeblock(blockContent, ctx);
            enhanceBasicPreBlocks(ea);
            enhanceCodeBlocks(ea);
            enhanceMermaidBlocks(ea);
            enhanceAdmonitions(ea);
            enhanceImages(ea);
            focusInsidePastedBlock('codeblock', blockContent);
            break;
          case 'codeblock':
            pasteCodeblock(blockContent, ctx);
            enhanceBasicPreBlocks(ea);
            enhanceCodeBlocks(ea);
            enhanceMermaidBlocks(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);

      // --- Drag-and-drop: image assets from nav menu ---

      var _WYSIWYG_ASSET_MIME = 'application/x-live-wysiwyg-asset';

      ea.addEventListener('dragover', function (e) {
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        if (!e.dataTransfer || !e.dataTransfer.types) return;
        var hasAsset = false;
        for (var i = 0; i < e.dataTransfer.types.length; i++) {
          if (e.dataTransfer.types[i] === _WYSIWYG_ASSET_MIME) { hasAsset = true; break; }
        }
        if (!hasAsset) return;
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
        if (!ea.classList.contains('live-wysiwyg-drop-target')) {
          ea.classList.add('live-wysiwyg-drop-target');
        }
      });

      ea.addEventListener('dragenter', function (e) {
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        if (!e.dataTransfer || !e.dataTransfer.types) return;
        var hasAsset = false;
        for (var i = 0; i < e.dataTransfer.types.length; i++) {
          if (e.dataTransfer.types[i] === _WYSIWYG_ASSET_MIME) { hasAsset = true; break; }
        }
        if (hasAsset) ea.classList.add('live-wysiwyg-drop-target');
      });

      ea.addEventListener('dragleave', function (e) {
        if (e.target === ea || !ea.contains(e.relatedTarget)) {
          ea.classList.remove('live-wysiwyg-drop-target');
        }
      });

      ea.addEventListener('drop', function (e) {
        ea.classList.remove('live-wysiwyg-drop-target');
        if (wysiwygEditor.currentMode !== 'wysiwyg') return;
        if (!e.dataTransfer) return;
        var raw;
        try { raw = e.dataTransfer.getData(_WYSIWYG_ASSET_MIME); } catch (_) { return; }
        if (!raw) return;
        var assetData;
        try { assetData = JSON.parse(raw); } catch (_) { return; }
        if (!assetData || !assetData._uid) return;
        e.preventDefault();
        e.stopPropagation();

        var diskSrcPath = assetData.src_path;
        var _diskIdx = _navDiskSnapshotIndex >= 0 ? _navDiskSnapshotIndex : 0;
        if (_navSnapshots && _navSnapshots.length > 0 && _navSnapshots[_diskIdx] && _navSnapshots[_diskIdx].navData) {
          var snap0Data = _navSnapshots[_diskIdx].navData;
          var found = null;
          (function findInSnap(items) {
            for (var i = 0; i < items.length; i++) {
              if (items[i]._uid === assetData._uid) { found = items[i]; return; }
              if (items[i].children) findInSnap(items[i].children);
              if (found) return;
            }
          })(snap0Data);
          if (found && found.src_path) diskSrcPath = found.src_path;
        }

        var relativePath = computeRelativeImagePath(_getCurrentSrcPath(), diskSrcPath);
        var resolvedUrl = resolveImageSrc(relativePath);

        var range = _compat.caretRangeFromPoint(e.clientX, e.clientY);
        if (!range || !ea.contains(range.startContainer)) {
          range = document.createRange();
          range.selectNodeContents(ea);
          range.collapse(false);
        }

        _flushHistoryCapture();

        var img = document.createElement('img');
        img.src = resolvedUrl;
        var filename = (assetData.title || diskSrcPath.split('/').pop() || '').replace(/\.[^.]+$/, '');
        img.alt = filename.replace(/[-_]/g, ' ');
        img.setAttribute('data-orig-src', relativePath);
        img.setAttribute('data-size-syntax', _getSetting('live_wysiwyg_image_attr_syntax') === '0' ? 'html' : 'attr');

        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);
        }

        var sel = window.getSelection();
        if (sel) {
          var r = document.createRange();
          r.setStart(pAfter, pAfter.childNodes.length > 0 ? 1 : 0);
          r.collapse(true);
          sel.removeAllRanges();
          sel.addRange(r);
        }

        enhanceImages(ea);
        if (wysiwygEditor._finalizeUpdate) wysiwygEditor._finalizeUpdate(ea.innerHTML);
      });

    })();

        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) {
        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();
  }
})();
