/**
 * markdown.mjs — Markdown renderer wrapping the marked library
 */

let markedLib = null;

async function ensureMarked() {
  if (markedLib) return markedLib;
  try {
    // marked is served by express.static from node_modules or lib
    const mod = await import('/lib/marked.esm.js');
    markedLib = mod.marked || mod.default;
  } catch {
    // Fallback: try the CDN-style path that server.mjs may expose
    try {
      const mod = await import('https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js');
      markedLib = mod.marked || mod.default;
    } catch {
      // Final fallback: basic passthrough
      markedLib = null;
    }
  }

  if (markedLib?.setOptions) {
    markedLib.setOptions({
      breaks: true,
      gfm: true
    });
  }

  return markedLib;
}

export async function renderMarkdown(text) {
  const marked = await ensureMarked();
  if (!marked) return escapeBasic(text);
  try {
    return sanitizeHtml(marked.parse(text));
  } catch {
    return escapeBasic(text);
  }
}

export function renderMarkdownSync(text) {
  if (!markedLib) return escapeBasic(text);
  try {
    return sanitizeHtml(markedLib.parse(text));
  } catch {
    return escapeBasic(text);
  }
}

function escapeBasic(text) {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\n/g, '<br>');
}

/**
 * Strip dangerous HTML from marked output.
 * Preserves safe markdown-generated tags (p, h1-h6, ul, ol, li, a, code, pre,
 * em, strong, blockquote, br, hr, table, img, span, div, del, etc.).
 * Removes dangerous elements (script, style, iframe, full HTML documents, etc.).
 */
function sanitizeHtml(html) {
  let clean = html;

  // Remove DOCTYPE declarations
  clean = clean.replace(/<!DOCTYPE[^>]*>/gi, '');

  // Remove dangerous tags and their content
  const stripTags = [
    'script', 'style', 'iframe', 'object', 'embed', 'form',
    'link', 'meta', 'base', 'html', 'head', 'body', 'title',
    'frame', 'frameset'
  ];
  for (const tag of stripTags) {
    clean = clean.replace(new RegExp(`<${tag}[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'), '');
    clean = clean.replace(new RegExp(`<\\/?${tag}[^>]*>`, 'gi'), '');
  }

  // Remove event handler attributes (onclick, onerror, onload, etc.)
  clean = clean.replace(/\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi, '');

  // Remove javascript: URLs in href/src attributes
  clean = clean.replace(/(href|src)\s*=\s*["']?\s*javascript:/gi, '$1="');

  return clean;
}
