(function () {
  'use strict';

  var CFG = (typeof window !== 'undefined' && window.misticeaseCfg) ? window.misticeaseCfg : {};
  var TARGETS = '.misticease-thumbnail, .misticease-n-link, a.misticease-img-popup';
  var SKIP_ANCESTOR = 'pre,code,script,style,textarea,kbd,samp,var';
  var IMAGE_EXT_RE = /\.(?:jpe?g|png|gif|webp|avif)(?:[?#][^\s<>"']*)?$/i;
  var WS_RE = /^[\s\u00A0\u3000]*$/;
  var IMAGES_ENABLED = !(CFG.images === false || CFG.images === 0 || CFG.images === '0' || CFG.images === '' || CFG.images === 'off' || CFG.images === null || typeof CFG.images === 'undefined');

  function trimValue(value) {
    return String(value || '').replace(/^[\s\u00A0\u3000]+|[\s\u00A0\u3000]+$/g, '');
  }

  function clampNumber(value, min, max) {
    value = parseInt(value, 10);
    if (!isFinite(value) || value < 1) return null;
    return Math.min(Math.max(value, min), max);
  }

  function isAdminContext(root) {
    var doc = (root && root.ownerDocument) || document;
    var body = doc && doc.body;
    return !!(body && body.classList && body.classList.contains('wp-admin'));
  }

  function isTargetElement(el) {
    return !!(el && el.matches && el.matches(TARGETS));
  }

  function shouldSkipTextNode(node) {
    if (!node || node.nodeType !== 3 || !node.parentElement) return true;
    return !!node.parentElement.closest(SKIP_ANCESTOR + ',a,.misticease-thumbnail,.misticease-n-link,.misticease-img-popup');
  }

  function shouldSkipElement(el) {
    if (!el || el.nodeType !== 1) return false;
    if (isTargetElement(el)) return false;
    return !!(el.matches && el.matches(SKIP_ANCESTOR + ',a'));
  }

  function isWhitespaceText(node) {
    return !!(node && node.nodeType === 3 && WS_RE.test(node.nodeValue || ''));
  }

  function nextSignificantSibling(node) {
    var cur = node ? node.nextSibling : null;
    while (cur && isWhitespaceText(cur)) {
      cur = cur.nextSibling;
    }
    return cur || null;
  }

  function elementHasOnlyWhitespaceOrTextNode(el, textNode) {
    if (!el || !textNode) return false;
    for (var cur = el.firstChild; cur; cur = cur.nextSibling) {
      if (cur === textNode || isWhitespaceText(cur)) continue;
      return false;
    }
    return true;
  }

  function isPendingAdjacentToTarget(pending, target) {
    if (!pending || !pending.node || !pending.spec || !target) return false;

    var textNode = pending.node;
    var parent = textNode.parentNode;
    if (!parent) return false;

    var targetIsGeneratedVideo = target.classList &&
      (target.classList.contains('misticease-thumbnail') || target.classList.contains('misticease-n-link'));

    if (!targetIsGeneratedVideo && !WS_RE.test(pending.spec.stripped || '')) {
      return false;
    }

    if (target.parentNode === parent && nextSignificantSibling(textNode) === target) {
      return true;
    }

    if (!WS_RE.test(pending.spec.stripped || '')) {
      return false;
    }

    if (parent.nodeType === 1 && elementHasOnlyWhitespaceOrTextNode(parent, textNode)) {
      var next = nextSignificantSibling(parent);
      if (next === target) {
        return true;
      }
    }

    return false;
  }

  function parsePrefix(text) {
    var source = String(text || '');
    var wsMatch = source.match(/[\s\u00A0\u3000]*$/);
    var trailingWs = wsMatch ? wsMatch[0] : '';
    var s = source.slice(0, source.length - trailingWs.length);

    if (!s || s.slice(-1) !== '/') return null;

    var result = {
      label: '',
      title: '',
      thumbWidth: null,
      thumbRadius: null,
      popupWidth: null,
      textLink: false,
      noPopup: false,
      consumed: false,
      stripped: source
    };
    var matched;

    while (s) {
      matched = s.match(/ttl[ \u3000]([^\/<>'"\n\r]+)\/$/i);
      if (matched) {
        result.title = trimValue(matched[1]);
        s = s.slice(0, s.length - matched[0].length);
        result.consumed = true;
        continue;
      }

      matched = s.match(/t(\d{1,4})\/$/i);
      if (matched) {
        result.thumbWidth = clampNumber(matched[1], 100, 4096);
        s = s.slice(0, s.length - matched[0].length);
        result.consumed = true;
        continue;
      }

      matched = s.match(/p(\d{1,4})\/$/i);
      if (matched) {
        result.popupWidth = clampNumber(matched[1], 200, 8192);
        s = s.slice(0, s.length - matched[0].length);
        result.consumed = true;
        continue;
      }

      matched = s.match(/r(\d{1,4})\/$/i);
      if (matched) {
        result.thumbRadius = clampNumber(matched[1], 1, 9999);
        s = s.slice(0, s.length - matched[0].length);
        result.consumed = true;
        continue;
      }

      matched = s.match(/np\/$/i);
      if (matched) {
        result.noPopup = true;
        s = s.slice(0, s.length - matched[0].length);
        result.consumed = true;
        continue;
      }

      matched = s.match(/n\/$/i);
      if (matched) {
        result.textLink = true;
        s = s.slice(0, s.length - matched[0].length);
        result.consumed = true;
        continue;
      }

      break;
    }

    matched = s.match(/\/([^\/<>'"\n\r]+)\/$/);
    if (matched) {
      result.label = trimValue(matched[1]);
      result.textLink = true;
      s = s.slice(0, s.length - matched[0].length);
      result.consumed = true;
    }

    if (!result.consumed) return null;
    result.stripped = s + trailingWs;
    return result;
  }

  function firstImage(el) {
    return (el && el.querySelector) ? el.querySelector('img') : null;
  }

  function setThumbImageSize(img, width, videoRatio) {
    if (!img || !width) return;
    var height = null;

    if (videoRatio) {
      height = Math.max(1, Math.round(width * 9 / 16));
    } else {
      var currentWidth = parseInt(img.getAttribute('width') || '', 10);
      var currentHeight = parseInt(img.getAttribute('height') || '', 10);
      if (isFinite(currentWidth) && currentWidth > 0 && isFinite(currentHeight) && currentHeight > 0) {
        height = Math.max(1, Math.round(width * currentHeight / currentWidth));
      }
    }

    try { img.setAttribute('width', String(width)); } catch (_e) {}
    if (height) {
      try { img.setAttribute('height', String(height)); } catch (_e2) {}
    }
    if (img.style) {
      img.style.width = '100%';
      img.style.maxWidth = width + 'px';
      img.style.height = 'auto';
    }
  }

  function applySizeAndTitle(el, spec) {
    if (!el || !spec) return;

    if (spec.popupWidth) {
      try { el.setAttribute('data-popup-width', String(spec.popupWidth)); } catch (_e) {}
    }

    if (spec.title) {
      try { el.setAttribute('data-misticease-title', spec.title); } catch (_e2) {}
    }

    if (spec.thumbWidth && el.classList && el.classList.contains('misticease-thumbnail')) {
      el.style.maxWidth = spec.thumbWidth + 'px';
      setThumbImageSize(firstImage(el), spec.thumbWidth, true);
    } else if (spec.thumbWidth && !(spec.label || spec.textLink)) {
      setThumbImageSize(firstImage(el), spec.thumbWidth, false);
    }

    if (spec.thumbRadius && !spec.textLink && el.classList) {
      if (el.classList.contains('misticease-thumbnail')) {
        el.style.borderRadius = spec.thumbRadius + 'px';
        var thumbImg = firstImage(el);
        if (thumbImg && thumbImg.style) thumbImg.style.borderRadius = spec.thumbRadius + 'px';
      } else if (el.classList.contains('misticease-img-popup')) {
        var img = firstImage(el);
        if (img && img.style) img.style.borderRadius = spec.thumbRadius + 'px';
      }
    }
  }

  function defaultLinkText(el) {
    if (!el) return 'Open';
    var txt = trimValue(el.textContent || '');
    if (txt) return txt;

    var img = firstImage(el);
    if (img) {
      var alt = trimValue(img.getAttribute('alt') || '');
      if (alt) return alt.replace(/\s+thumbnail$/i, '');
    }

    var href = trimValue(el.getAttribute ? (el.getAttribute('href') || '') : '');
    if (href) {
      try {
        var url = new URL(href, window.location.href);
        var path = url.pathname || '';
        var slash = path.lastIndexOf('/');
        return decodeURIComponent(slash >= 0 ? path.slice(slash + 1) : path) || 'Open';
      } catch (_e) {}
    }

    return 'Open';
  }

  function thumbnailToTextLink(el, spec) {
    if (!el || !el.parentNode) return;

    var a = document.createElement('a');
    a.href = '#';
    a.className = 'misticease-n-link';
    a.textContent = spec.label || defaultLinkText(el);

    var attrs = ['data-video-id', 'data-video-type', 'data-popup-width', 'data-misticease-title'];
    for (var i = 0; i < attrs.length; i++) {
      var v = el.getAttribute(attrs[i]);
      if (v) a.setAttribute(attrs[i], v);
    }

    if (spec.popupWidth) a.setAttribute('data-popup-width', String(spec.popupWidth));
    if (spec.title) a.setAttribute('data-misticease-title', spec.title);

    el.parentNode.replaceChild(a, el);
  }

  function imageAnchorToNonPopupImage(el) {
    if (!el || !el.parentNode || !el.classList || !el.classList.contains('misticease-img-popup')) return;

    var img = firstImage(el);
    if (!img) return;

    try { img.classList.add('misticease-np'); } catch (_e) {}
    try { img.setAttribute('data-misticease-np', '1'); } catch (_e2) {}

    if (img.style) {
      if (!img.style.maxWidth) {
        img.style.maxWidth = '100%';
      }
      img.style.height = 'auto';
    }

    el.parentNode.replaceChild(img, el);
  }

  function imageAnchorToTextLink(el, spec) {
    if (!el || !spec.label) return;
    el.textContent = spec.label;
  }

  function applySpecToTarget(el, spec, textNode) {
    if (!el || !spec || !textNode) return;

    textNode.nodeValue = spec.stripped;
    applySizeAndTitle(el, spec);

    if (spec.noPopup && el.classList && el.classList.contains('misticease-img-popup')) {
      imageAnchorToNonPopupImage(el);
      return;
    }

    if (spec.textLink) {
      if (el.classList && el.classList.contains('misticease-thumbnail')) {
        thumbnailToTextLink(el, spec);
      } else if (el.classList && el.classList.contains('misticease-img-popup')) {
        imageAnchorToTextLink(el, spec);
      } else if (el.classList && el.classList.contains('misticease-n-link') && spec.label) {
        el.textContent = spec.label;
      }
    }
  }

  function applyPrefixMarkup(root) {
    var rt = root || document.body;
    if (!rt || isAdminContext(rt)) return;

    var walker = document.createTreeWalker(rt, NodeFilter.SHOW_ALL, null, false);
    var pending = null;
    var actions = [];
    var node;

    while ((node = walker.nextNode())) {
      if (node.nodeType === 3) {
        if (shouldSkipTextNode(node)) {
          pending = null;
          continue;
        }

        if (WS_RE.test(node.nodeValue || '')) {
          continue;
        }

        var spec = parsePrefix(node.nodeValue);
        pending = spec ? { node: node, spec: spec } : null;
        continue;
      }

      if (node.nodeType !== 1) {
        continue;
      }

      if (isTargetElement(node)) {
        if (pending && isPendingAdjacentToTarget(pending, node)) {
          actions.push({ target: node, spec: pending.spec, textNode: pending.node });
        }
        pending = null;
        continue;
      }

      if (shouldSkipElement(node)) {
        pending = null;
      }
    }

    for (var i = 0; i < actions.length; i++) {
      if (!actions[i].target || !actions[i].textNode || !actions[i].textNode.parentNode) {
        continue;
      }
      applySpecToTarget(actions[i].target, actions[i].spec, actions[i].textNode);
      if (actions[i].target.parentNode) {
        try { actions[i].target.setAttribute('data-misticease-sml-done', '1'); } catch (_e) {}
      }
    }
  }

  function normalizeHost(value) {
    return String(value || '').trim().toLowerCase().replace(/:\d+$/, '');
  }

  function normalizeHostList(list, fallback) {
    var source = list && list.length ? list : (fallback || []);
    var out = [];

    for (var i = 0; i < source.length; i++) {
      var host = normalizeHost(source[i]);
      if (host && out.indexOf(host) === -1) out.push(host);
    }

    return out;
  }

  var ALLOWED_CDN_HOSTS = normalizeHostList(CFG.cdnHosts || []);
  var ALLOWED_IMAGE_HOSTS = normalizeHostList(CFG.imageHosts || [], [window.location.hostname]);

  function hostInList(host, list) {
    host = normalizeHost(host);
    return !!(host && list && list.indexOf(host) !== -1);
  }

  function imageUrlAllowed(url) {
    if (!url || !IMAGE_EXT_RE.test(url)) return false;

    try {
      var parsed = new URL(url, window.location.href);
      var host = normalizeHost(parsed.hostname || '');
      var path = String(parsed.pathname || '');

      if (hostInList(host, ALLOWED_CDN_HOSTS)) return true;
      if (!/(?:^|\/)wp-content\//i.test(path)) return false;

      return hostInList(host, ALLOWED_IMAGE_HOSTS);
    } catch (_e) {
      return false;
    }
  }

  function rewriteDirectImageNode(node) {
    if (!node || shouldSkipTextNode(node)) return;

    var text = node.nodeValue || '';
    if (text.indexOf('http') === -1 || text.indexOf('/') === -1) return;

    var re = /((?:\/[^\/<>'"\n\r]+\/)?(?:(?:ttl[ \u3000][^\/<>'"\n\r]+|t\d{1,4}|p\d{1,4}|r\d{1,4}|np|n)\/)*)?(https?:\/\/[^\s\u3000<>"']+?\.(?:jpe?g|png|gif|webp|avif)(?:[?#][^\s\u3000<>"']*)?)(?:\/{3}|(?=[\s\u00A0\u3000<]|$))/ig;
    var frag = null;
    var last = 0;
    var match;

    while ((match = re.exec(text))) {
      var prefix = match[1] || '';
      var url = match[2] || '';
      var spec = parsePrefix(prefix);

      if (!spec || !spec.label || !imageUrlAllowed(url)) {
        continue;
      }

      if (!frag) frag = document.createDocumentFragment();
      if (match.index > last) frag.appendChild(document.createTextNode(text.slice(last, match.index)));

      var a = document.createElement('a');
      a.href = url;
      a.className = 'misticease-img-popup';
      a.textContent = spec.label;
      if (spec.popupWidth) a.setAttribute('data-popup-width', String(spec.popupWidth));
      if (spec.title) a.setAttribute('data-misticease-title', spec.title);
      frag.appendChild(a);

      last = match.index + match[0].length;
    }

    if (!frag) return;
    if (last < text.length) frag.appendChild(document.createTextNode(text.slice(last)));
    node.parentNode.replaceChild(frag, node);
  }

  function rewriteDirectImageLinks(root) {
    if (!IMAGES_ENABLED) return;

    var rt = root || document.body;
    if (!rt || isAdminContext(rt)) return;

    var walker = document.createTreeWalker(rt, NodeFilter.SHOW_TEXT, {
      acceptNode: function (node) {
        if (shouldSkipTextNode(node)) return NodeFilter.FILTER_REJECT;
        var s = node.nodeValue || '';
        if (s.indexOf('http') === -1 || s.indexOf('/') === -1) return NodeFilter.FILTER_REJECT;
        return NodeFilter.FILTER_ACCEPT;
      }
    });

    var nodes = [];
    var n;
    while ((n = walker.nextNode())) nodes.push(n);

    for (var i = 0; i < nodes.length; i++) {
      rewriteDirectImageNode(nodes[i]);
    }
  }

  function run() {
    rewriteDirectImageLinks(document.body);
    applyPrefixMarkup(document.body);
  }

  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    setTimeout(run, 0);
  } else {
    document.addEventListener('DOMContentLoaded', run, false);
  }
})();