/**
 * Render markdown and sanitize the resulting HTML before DOM insertion.
 * This protects the web UI from untrusted model/tool output.
 */
export function renderSafeMarkdown(text) {
  const raw = String(text ?? '');
  let html = '';
  const md = globalThis.marked;

  try {
    if (md) {
      html = md.parse(raw);
    }
  } catch {
    // Fall through to plain-text fallback
  }

  if (!html) {
    html = `<p>${escapeHtml(raw)}</p>`;
  }

  return sanitizeHtml(html);
}

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

function sanitizeHtml(html) {
  const root = document.createElement('div');
  root.innerHTML = html;

  // Drop elements that can execute script or embed active content.
  const blockedTags = new Set([
    'script',
    'style',
    'iframe',
    'object',
    'embed',
    'link',
    'meta',
    'base',
    'form',
    'input',
    'button',
    'textarea',
    'select',
  ]);

  const nodes = root.querySelectorAll('*');
  for (const el of nodes) {
    const tag = el.tagName.toLowerCase();
    if (blockedTags.has(tag)) {
      el.remove();
      continue;
    }

    for (const attr of Array.from(el.attributes)) {
      const name = attr.name.toLowerCase();
      const value = attr.value.trim();

      // Remove event handlers and inline styles.
      if (name.startsWith('on') || name === 'style') {
        el.removeAttribute(attr.name);
        continue;
      }

      // Strip scriptable URL schemes.
      if (name === 'href' || name === 'src' || name === 'xlink:href') {
        if (isUnsafeUrl(value)) {
          el.removeAttribute(attr.name);
        }
      }
    }

    if (tag === 'a' && el.getAttribute('target') === '_blank') {
      const rel = (el.getAttribute('rel') ?? '').toLowerCase();
      if (!rel.includes('noopener') || !rel.includes('noreferrer')) {
        el.setAttribute('rel', 'noopener noreferrer');
      }
    }
  }

  return root.innerHTML;
}

function isUnsafeUrl(value) {
  const normalized = value.replace(/[\u0000-\u001F\u007F\s]+/g, '').toLowerCase();
  return normalized.startsWith('javascript:') || normalized.startsWith('vbscript:') || normalized.startsWith('data:text/html');
}
