import { isMdAsciiPunct as v, isPunctChar as E, isWhiteSpace as P } from "../common/utils.js";
const T = /['"]/, q = /['"]/g, O = "’";
function b(t, n, e) {
  return t.slice(0, n) + e + t.slice(n + 1);
}
function Q(t, n) {
  let e;
  const i = [];
  for (let c = 0; c < t.length; c++) {
    const l = t[c], x = t[c].level;
    for (e = i.length - 1; e >= 0 && !(i[e].level <= x); e--)
      ;
    if (i.length = e + 1, l.type !== "text")
      continue;
    let h = l.content, r = 0, m = h.length;
    e:
      for (; r < m; ) {
        q.lastIndex = r;
        const o = q.exec(h);
        if (!o)
          break;
        let s = !0, f = !0;
        r = o.index + 1;
        const d = o[0] === "'";
        let a = 32;
        if (o.index - 1 >= 0)
          a = h.charCodeAt(o.index - 1);
        else
          for (e = c - 1; e >= 0 && !(t[e].type === "softbreak" || t[e].type === "hardbreak"); e--)
            if (t[e].content) {
              a = t[e].content.charCodeAt(t[e].content.length - 1);
              break;
            }
        let u = 32;
        if (r < m)
          u = h.charCodeAt(r);
        else
          for (e = c + 1; e < t.length && !(t[e].type === "softbreak" || t[e].type === "hardbreak"); e++)
            if (t[e].content) {
              u = t[e].content.charCodeAt(0);
              break;
            }
        const k = v(a) || E(String.fromCharCode(a)), S = v(u) || E(String.fromCharCode(u)), y = P(a), A = P(u);
        if (A ? s = !1 : S && (y || k || (s = !1)), y ? f = !1 : k && (A || S || (f = !1)), u === 34 && o[0] === '"' && a >= 48 && a <= 57 && (f = s = !1), s && f && (s = k, f = S), !s && !f) {
          d && (l.content = b(l.content, o.index, O));
          continue;
        }
        if (f)
          for (e = i.length - 1; e >= 0; e--) {
            let p = i[e];
            if (i[e].level < x)
              break;
            if (p.single === d && i[e].level === x) {
              p = i[e];
              let g, C;
              d ? (g = n.md.options.quotes[2], C = n.md.options.quotes[3]) : (g = n.md.options.quotes[0], C = n.md.options.quotes[1]), l.content = b(l.content, o.index, C), t[p.token].content = b(
                t[p.token].content,
                p.pos,
                g
              ), r += C.length - 1, p.token === c && (r += g.length - 1), h = l.content, m = h.length, i.length = e;
              continue e;
            }
          }
        s ? i.push({
          token: c,
          pos: o.index,
          single: d,
          level: x
        }) : f && d && (l.content = b(l.content, o.index, O));
      }
  }
}
function L(t) {
  if (t.md.options.typographer)
    for (let n = t.tokens.length - 1; n >= 0; n--)
      t.tokens[n].type !== "inline" || !T.test(t.tokens[n].content) || Q(t.tokens[n].children, t);
}
export {
  L as default
};
