/**
 * Minimal, dependency-free Markdown → HTML converter used to render a custom
 * page's raw content when the user has not yet run "Beautify with AI".
 *
 * Intentionally tiny: headings, paragraphs, lists, bold/italic/code, hr, and
 * fenced code blocks. The AI-beautified output is already HTML, so this is only
 * for the live-edit preview / pre-beautify state.
 */

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

function inline(s: string): string {
  return s
    .replace(/`([^`]+)`/g, (_, c) => `<code>${escapeHtml(c)}</code>`)
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/\*([^*]+)\*/g, '<em>$1</em>');
}

export function renderMarkdown(src: string): string {
  const lines = src.replace(/\r\n/g, '\n').split('\n');
  const out: string[] = [];
  let i = 0;
  let inUl = false;
  let inOl = false;

  const closeLists = () => {
    if (inUl) { out.push('</ul>'); inUl = false; }
    if (inOl) { out.push('</ol>'); inOl = false; }
  };

  while (i < lines.length) {
    const line = lines[i];

    // Fenced code block — ```` ```mermaid ```` becomes a renderable diagram div.
    if (line.trimStart().startsWith('```')) {
      closeLists();
      const info = line.trim().slice(3);
      const lang = info.split(/\s+/)[0] ?? '';
      const buf: string[] = [];
      i++;
      while (i < lines.length && !lines[i].trimStart().startsWith('```')) {
        buf.push(lines[i]);
        i++;
      }
      i++; // skip closing fence
      if (lang === 'mermaid') {
        out.push(`<div class="mermaid">${escapeHtml(buf.join('\n'))}</div>`);
      } else {
        out.push(`<pre><code data-lang="${escapeHtml(lang)}">${escapeHtml(buf.join('\n'))}</code></pre>`);
      }
      continue;
    }

    // Horizontal rule
    if (/^\s*([-*_])\1\1[-*_\s]*$/.test(line)) {
      closeLists();
      out.push('<hr/>');
      i++;
      continue;
    }

    // Heading
    const h = /^(#{1,6})\s+(.*)$/.exec(line);
    if (h) {
      closeLists();
      const level = h[1].length;
      out.push(`<h${level}>${inline(escapeHtml(h[2]))}</h${level}>`);
      i++;
      continue;
    }

    // Ordered list item
    const ol = /^\s*\d+\.\s+(.*)$/.exec(line);
    if (ol) {
      if (!inOl) { closeLists(); out.push('<ol>'); inOl = true; }
      out.push(`<li>${inline(escapeHtml(ol[1]))}</li>`);
      i++;
      continue;
    }

    // Unordered list item
    const ul = /^\s*[-*+]\s+(.*)$/.exec(line);
    if (ul) {
      if (!inUl) { closeLists(); out.push('<ul>'); inUl = true; }
      out.push(`<li>${inline(escapeHtml(ul[1]))}</li>`);
      i++;
      continue;
    }

    // Blank line
    if (line.trim() === '') {
      closeLists();
      i++;
      continue;
    }

    // Paragraph
    closeLists();
    out.push(`<p>${inline(escapeHtml(line))}</p>`);
    i++;
  }
  closeLists();
  return out.join('\n');
}
