const OPEN = 123;
const CLOSE = 125;
const BACKSLASH = 92;
const TRIGGER_CLASS = "decoration-dashed underline decoration-(--primary) underline-offset-4 cursor-help";
function readSegment(src, start, max) {
  if (start >= max || src.charCodeAt(start) !== OPEN) return null;
  let pos = start + 1;
  let out = "";
  while (pos < max) {
    const code = src.charCodeAt(pos);
    if (code === BACKSLASH && pos + 1 < max) {
      const next = src.charCodeAt(pos + 1);
      if (next === OPEN || next === CLOSE || next === BACKSLASH) {
        out += src[pos + 1];
        pos += 2;
        continue;
      }
      out += src[pos];
      pos += 1;
      continue;
    }
    if (code === OPEN) return null;
    if (code === CLOSE) return { end: pos + 1, value: out };
    out += src[pos];
    pos += 1;
  }
  return null;
}
function tooltipRule(state, silent) {
  const start = state.pos;
  if (state.src.charCodeAt(start) !== OPEN) return false;
  const trigger = readSegment(state.src, start, state.posMax);
  if (!trigger) return false;
  const content = readSegment(state.src, trigger.end, state.posMax);
  if (!content) return false;
  if (!silent) {
    const token = state.push("tooltip", "", 0);
    token.markup = "{}{}";
    token.meta = { trigger: trigger.value, content: content.value };
  }
  state.pos = content.end;
  return true;
}
export default function tooltipPlugin(md) {
  md.inline.ruler.before("emphasis", "tooltip", tooltipRule);
  md.renderer.rules.tooltip = (tokens, idx) => {
    const token = tokens[idx];
    const meta = token?.meta;
    if (!meta) return "";
    const trigger = md.renderInline(meta.trigger);
    const title = md.utils.escapeHtml(meta.content);
    return `<span class="${TRIGGER_CLASS}" title="${title}">${trigger}</span>`;
  };
}
export { TRIGGER_CLASS };
