import { arrayReplaceAt as _ } from "../common/utils.js";
function w(e) {
  return /^<a[>\s]/i.test(e);
}
function g(e) {
  return /^<\/a\s*>/i.test(e);
}
function b(e) {
  const f = e.tokens;
  if (e.md.options.linkify)
    for (let k = 0, T = f.length; k < T; k++) {
      if (f[k].type !== "inline" || !e.md.linkify.pretest(f[k].content))
        continue;
      let c = f[k].children, u = 0;
      for (let l = c.length - 1; l >= 0; l--) {
        const i = c[l];
        if (i.type === "link_close") {
          for (l--; c[l].level !== i.level && c[l].type !== "link_open"; )
            l--;
          continue;
        }
        if (i.type === "html_inline" && (w(i.content) && u > 0 && u--, g(i.content) && u++), !(u > 0) && i.type === "text" && e.md.linkify.test(i.content)) {
          const h = i.content;
          let t = e.md.linkify.match(h);
          const s = [];
          let r = i.level, p = 0;
          t.length > 0 && t[0].index === 0 && l > 0 && c[l - 1].type === "text_special" && (t = t.slice(1));
          for (let n = 0; n < t.length; n++) {
            const L = t[n].url, y = e.md.normalizeLink(L);
            if (!e.md.validateLink(y))
              continue;
            let o = t[n].text;
            t[n].schema ? t[n].schema === "mailto:" && !/^mailto:/i.test(o) ? o = e.md.normalizeLinkText("mailto:" + o).replace(/^mailto:/, "") : o = e.md.normalizeLinkText(o) : o = e.md.normalizeLinkText("http://" + o).replace(/^http:\/\//, "");
            const v = t[n].index;
            if (v > p) {
              const x = new e.Token("text", "", 0);
              x.content = h.slice(p, v), x.level = r, s.push(x);
            }
            const m = new e.Token("link_open", "a", 1);
            m.attrs = [["href", y]], m.level = r++, m.markup = "linkify", m.info = "auto", s.push(m);
            const d = new e.Token("text", "", 0);
            d.content = o, d.level = r, s.push(d);
            const a = new e.Token("link_close", "a", -1);
            a.level = --r, a.markup = "linkify", a.info = "auto", s.push(a), p = t[n].lastIndex;
          }
          if (p < h.length) {
            const n = new e.Token("text", "", 0);
            n.content = h.slice(p), n.level = r, s.push(n);
          }
          f[k].children = c = _(c, l, s);
        }
      }
    }
}
export {
  b as default
};
