let mod: typeof import("katex").default | null = null

export async function renderKatex(
  source: string,
  el: HTMLElement,
  displayMode = false,
) {
  if (!mod) mod = (await import("katex")).default
  try {
    mod?.render(source, el, { throwOnError: false, displayMode })
  } catch {
    el.textContent = source
  }
}

export function renderKatexSync(
  source: string,
  el: HTMLElement,
  displayMode = false,
) {
  if (!mod) {
    renderKatex(source, el, displayMode)
    return
  }
  try {
    mod?.render(source, el, { throwOnError: false, displayMode })
  } catch {
    el.textContent = source
  }
}

/**
 * Extract math content from a math_block's raw text (which includes
 * optional $$...$$ fences). Returns the content between fences, or
 * empty string if the text doesn't represent valid fenced math.
 */
export function getMathContent(text: string): string {
  const lines = text.split("\n")
  if (
    lines.length >= 2 &&
    /^\$\$$/.test(lines[0] ?? "") &&
    /^\$\$$/.test(lines[lines.length - 1] ?? "")
  ) {
    return lines.slice(1, -1).join("\n")
  }
  return ""
}
