import { Marked } from 'marked';
import DOMPurify from 'dompurify';

const marked = new Marked({ breaks: true, gfm: true });

// Rendert Markdown zu HTML und entfernt anschließend aktive Inhalte (script, on*-Attribute,
// javascript:-URLs etc.) — verhindert Stored XSS über KI-Antworten/Kommentare/Knowledge-Base.
export function renderMd(text) {
    try {
        const html = marked.parse(String(text || ''), { async: false });
        const raw = typeof html === 'string' ? html : String(html);
        return { __html: DOMPurify.sanitize(raw) };
    } catch {
        return { __html: DOMPurify.sanitize(String(text || '').replace(/\n/g, '<br>')) };
    }
}

export function sanitizeHtml(html) {
    return DOMPurify.sanitize(String(html || ''));
}
