export function textToAdoHtml(text) {
  if (!text) return '';
  const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();
  // Normalize "N. " or "N) " after semicolon
  text = text.replace(/;\s+(\d+[.)]\s)/g, '\n$1');
  // Normalize "(N) " after semicolon or colon → "N. " on new line
  text = text.replace(/[;:]\s+\((\d+)\)\s+/g, (m, n) => (m[0] === ':' ? ':\n' : '\n') + n + '. ');
  const lines = text.split('\n');
  let html = '';
  let inOl = false;
  let inUl = false;
  lines.forEach(line => {
    const t = line.trim();
    const numM = t.match(/^(\d+)[.)]\s+(.+)$/);
    const bulM = !numM && t.match(/^[-•*]\s+(.+)$/);
    if (numM) {
      if (inUl) { html += '</ul>'; inUl = false; }
      if (!inOl) { html += '<ol>'; inOl = true; }
      html += '<li>' + esc(numM[2]) + '</li>';
    } else if (bulM) {
      if (inOl) { html += '</ol>'; inOl = false; }
      if (!inUl) { html += '<ul>'; inUl = true; }
      html += '<li>' + esc(bulM[1]) + '</li>';
    } else {
      if (inOl) { html += '</ol>'; inOl = false; }
      if (inUl) { html += '</ul>'; inUl = false; }
      if (!t) return;
      // Long line with multiple "; " → split into list items
      const parts = t.split('; ');
      if (parts.length >= 3 && t.length > 100) {
        html += '<ul>' + parts.map(s => s.trim() ? '<li>' + esc(s.trim()) + '</li>' : '').join('') + '</ul>';
      } else {
        html += '<p>' + esc(t) + '</p>';
      }
    }
  });
  if (inOl) html += '</ol>';
  if (inUl) html += '</ul>';
  return html;
}
