import React from "react";

type Props = {
  markdown: string;
};

export function LegalMarkdown({ markdown }: Props) {
  const html = React.useMemo(() => {
    let safe = markdown
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');
    safe = safe.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
    safe = safe.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '<em>$1</em>');
    safe = safe.replace(/\[(.+?)\]\((https?:[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
    safe = safe
      .split(/\n{2,}/)
      .map((block) => `<p>${block.replace(/\n/g, '<br/>')}</p>`)
      .join('\n');
    return safe;
  }, [markdown]);

  return <div className="prose prose-sm dark:prose-invert" dangerouslySetInnerHTML={{ __html: html }} />;
}