/** Minimal markdown → HTML renderer for AI-generated text. */

function esc(s: string): string {
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function inline(s: string): string {
  return s
    .replace(/`([^`\n]+)`/g, '<code class="md-ic">$1</code>')
    .replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
    .replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
}

export function markdownToHtml(text: string): string {
  const codeBlocks: string[] = [];

  // Extract fenced code blocks first
  const withPlaceholders = text.replace(/```([^\n]*)\n?([\s\S]*?)```/g, (_m, _lang, code: string) => {
    const i = codeBlocks.length;
    codeBlocks.push(`<pre class="md-pre"><code>${esc(code.replace(/\n$/, ''))}</code></pre>`);
    return `\x00CODE${i}\x00`;
  });

  const out: string[] = [];
  const blocks = withPlaceholders.split(/\n{2,}/);

  for (const block of blocks) {
    const b = block.trim();
    if (!b) continue;

    // Code block placeholder (whole block)
    const cp = b.match(/^\x00CODE(\d+)\x00$/);
    if (cp) { out.push(codeBlocks[+cp[1]]); continue; }

    // Heading
    const h3 = b.match(/^###\s+(.+)/);
    const h2 = b.match(/^##\s+(.+)/);
    const h1 = b.match(/^#\s+(.+)/);
    if (h3) { out.push(`<h5 class="md-h">${inline(esc(h3[1]))}</h5>`); continue; }
    if (h2) { out.push(`<h4 class="md-h">${inline(esc(h2[1]))}</h4>`); continue; }
    if (h1) { out.push(`<h3 class="md-h">${inline(esc(h1[1]))}</h3>`); continue; }

    // Process line-by-line (mixed lists + prose)
    const lines = b.split('\n');
    const parts: string[] = [];
    let listType: 'ul' | 'ol' | null = null;

    const closeList = () => {
      if (listType) { parts.push(listType === 'ul' ? '</ul>' : '</ol>'); listType = null; }
    };

    for (const line of lines) {
      const t = line.trim();

      // Inline code placeholder
      const icp = t.match(/^\x00CODE(\d+)\x00$/);
      if (icp) { closeList(); parts.push(codeBlocks[+icp[1]]); continue; }

      if (/^[-*+]\s/.test(t)) {
        if (listType !== 'ul') { closeList(); parts.push('<ul class="md-ul">'); listType = 'ul'; }
        parts.push(`<li>${inline(esc(t.replace(/^[-*+]\s+/, '')))}</li>`);
      } else if (/^\d+\.\s/.test(t)) {
        if (listType !== 'ol') { closeList(); parts.push('<ol class="md-ol">'); listType = 'ol'; }
        parts.push(`<li>${inline(esc(t.replace(/^\d+\.\s+/, '')))}</li>`);
      } else {
        closeList();
        if (t) parts.push(`<p class="md-p">${inline(esc(t))}</p>`);
      }
    }
    closeList();
    out.push(parts.join(''));
  }

  return out.join('');
}
