import { isSpace as h, normalizeReference as b } from "../common/utils.js";
function C(r, m) {
  let o, p, l, s, f = "", d = "", c = r.pos, k = !0;
  if (r.src.charCodeAt(r.pos) !== 91)
    return !1;
  const A = r.pos, i = r.posMax, u = r.pos + 1, n = r.md.helpers.parseLinkLabel(r, r.pos, !0);
  if (n < 0)
    return !1;
  let e = n + 1;
  if (e < i && r.src.charCodeAt(e) === 40) {
    for (k = !1, e++; e < i && (o = r.src.charCodeAt(e), !(!h(o) && o !== 10)); e++)
      ;
    if (e >= i)
      return !1;
    if (c = e, l = r.md.helpers.parseLinkDestination(r.src, e, r.posMax), l.ok) {
      for (f = r.md.normalizeLink(l.str), r.md.validateLink(f) ? e = l.pos : f = "", c = e; e < i && (o = r.src.charCodeAt(e), !(!h(o) && o !== 10)); e++)
        ;
      if (l = r.md.helpers.parseLinkTitle(r.src, e, r.posMax), e < i && c !== e && l.ok)
        for (d = l.str, e = l.pos; e < i && (o = r.src.charCodeAt(e), !(!h(o) && o !== 10)); e++)
          ;
    }
    (e >= i || r.src.charCodeAt(e) !== 41) && (k = !0), e++;
  }
  if (k) {
    if (typeof r.env.references > "u")
      return !1;
    if (e < i && r.src.charCodeAt(e) === 91 ? (c = e + 1, e = r.md.helpers.parseLinkLabel(r, e), e >= 0 ? p = r.src.slice(c, e++) : e = n + 1) : e = n + 1, p || (p = r.src.slice(u, n)), s = r.env.references[b(p)], !s)
      return r.pos = A, !1;
    f = s.href, d = s.title;
  }
  if (!m) {
    r.pos = u, r.posMax = n;
    const L = r.push("link_open", "a", 1), x = [["href", f]];
    L.attrs = x, d && x.push(["title", d]), r.linkLevel++, r.md.inline.tokenize(r), r.linkLevel--, r.push("link_close", "a", -1);
  }
  return r.pos = e, r.posMax = i, !0;
}
export {
  C as default
};
