// Tiny markdown renderer — headings, paragraphs, lists, blockquotes, inline emphasis/code/links.
// Good enough for the editorial content this site serves.

(function() {
  function esc(s) {
    return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  }
  function inline(s) {
    s = esc(s);
    s = s.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
    s = s.replace(/\*(.+?)\*/g, '<em>$1</em>');
    s = s.replace(/`(.+?)`/g, '<code>$1</code>');
    s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
    return s;
  }
  window.renderMD = function(md) {
    const lines = md.split('\n');
    const out = [];
    let para = [];
    let list = null;
    const flushPara = () => {
      if (para.length) { out.push('<p>' + inline(para.join(' ')) + '</p>'); para = []; }
    };
    const flushList = () => {
      if (list) { out.push('<' + list.tag + '>' + list.items.map(i => '<li>' + inline(i) + '</li>').join('') + '</' + list.tag + '>'); list = null; }
    };
    for (let raw of lines) {
      const line = raw.trimEnd();
      if (!line.trim()) { flushPara(); flushList(); continue; }
      let m;
      if ((m = line.match(/^(#{1,4})\s+(.*)$/))) {
        flushPara(); flushList();
        const level = m[1].length;
        out.push(`<h${level}>${inline(m[2])}</h${level}>`);
      } else if ((m = line.match(/^\s*[-*]\s+(.*)$/))) {
        flushPara();
        if (!list || list.tag !== 'ul') { flushList(); list = { tag: 'ul', items: [] }; }
        list.items.push(m[1]);
      } else if ((m = line.match(/^\s*\d+\.\s+(.*)$/))) {
        flushPara();
        if (!list || list.tag !== 'ol') { flushList(); list = { tag: 'ol', items: [] }; }
        list.items.push(m[1]);
      } else if ((m = line.match(/^>\s*(.*)$/))) {
        flushPara(); flushList();
        out.push('<blockquote>' + inline(m[1]) + '</blockquote>');
      } else if (line.match(/^---+$/)) {
        flushPara(); flushList();
        out.push('<hr />');
      } else {
        para.push(line);
      }
    }
    flushPara(); flushList();
    return out.join('\n');
  };
})();
