/* global React */
/* Tiny markdown -> HTML for copilot/briefing/scenario text, plus ```chart``` extraction. */

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

// Pull ```chart {json}``` blocks out; return { text, charts:[spec,...] }
function splitCharts(raw) {
  const charts = [];
  const text = raw.replace(/```chart\s*([\s\S]*?)```/g, (_, body) => {
    try { charts.push(JSON.parse(body.trim())); } catch (e) { /* ignore bad spec */ }
    return '';
  }).replace(/```[\s\S]*?```/g, m => m); // leave other fences alone
  return { text: text.trim(), charts };
}

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

// Convert a (chart-free) markdown string to an HTML string.
function mdToHtml(md) {
  const lines = md.split('\n');
  let html = '', i = 0, inUl = false, inOl = false;
  const closeLists = () => { if (inUl) { html += '</ul>'; inUl = false; } if (inOl) { html += '</ol>'; inOl = false; } };
  while (i < lines.length) {
    let ln = lines[i];
    // table block
    if (/^\s*\|.*\|\s*$/.test(ln) && i + 1 < lines.length && /^\s*\|[\s:|-]+\|\s*$/.test(lines[i + 1])) {
      closeLists();
      const header = ln.trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim());
      i += 2;
      let rows = [];
      while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) {
        rows.push(lines[i].trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim())); i++;
      }
      html += '<table><thead><tr>' + header.map(h => `<th>${inline(escapeHtml(h))}</th>`).join('') + '</tr></thead><tbody>';
      html += rows.map(r => '<tr>' + r.map(c => `<td>${inline(escapeHtml(c))}</td>`).join('') + '</tr>').join('');
      html += '</tbody></table>';
      continue;
    }
    const esc = escapeHtml(ln);
    if (/^###\s+/.test(ln)) { closeLists(); html += `<h3>${inline(esc.replace(/^###\s+/, ''))}</h3>`; }
    else if (/^##\s+/.test(ln)) { closeLists(); html += `<h2>${inline(esc.replace(/^##\s+/, ''))}</h2>`; }
    else if (/^\s*[-*]\s+/.test(ln)) { if (!inUl) { closeLists(); html += '<ul>'; inUl = true; } html += `<li>${inline(esc.replace(/^\s*[-*]\s+/, ''))}</li>`; }
    else if (/^\s*\d+\.\s+/.test(ln)) { if (!inOl) { closeLists(); html += '<ol>'; inOl = true; } html += `<li>${inline(esc.replace(/^\s*\d+\.\s+/, ''))}</li>`; }
    else if (/^\s*---\s*$/.test(ln)) { closeLists(); html += '<hr style="border:none;border-top:1px solid var(--rule-dim);margin:8px 0">'; }
    else if (ln.trim() === '') { closeLists(); }
    else { closeLists(); html += `<div>${inline(esc)}</div>`; }
    i++;
  }
  closeLists();
  return html;
}

window.mdToHtml = mdToHtml;
window.splitCharts = splitCharts;
