import type { OutputOptions } from '../../components/editor/output';
import { sanitizeCustomHtml } from '../../utils/sanitize';

export const FORUM_EDITOR_OUTPUT_OPTS: OutputOptions = {
  allowTextFormatting: true,
  allowInlineMarkdown: true,
  allowBlockMarkdown: true,
};

export function titleFromFormattedBody(html: string | undefined): string | undefined {
  if (!html) return undefined;
  const match = html.trim().match(/^<h1[^>]*>([\s\S]*?)<\/h1>/i);
  if (!match) return undefined;
  const text = match[1].replace(/<[^>]+>/g, '').trim();
  return text || undefined;
}

export function stripLeadingTitleHeading(html: string): string {
  return html.replace(/^\s*<h1[^>]*>[\s\S]*?<\/h1>\s*/i, '').trim();
}

export function bodyHtmlFromMessageContent(
  content: Record<string, unknown>,
  options: { stripTitleHeading?: boolean } = {}
): string | undefined {
  if (content.format !== 'org.matrix.custom.html') return undefined;
  const raw = content.formatted_body;
  if (typeof raw !== 'string' || !raw.trim()) return undefined;

  let html = raw.trim();
  if (options.stripTitleHeading) {
    html = stripLeadingTitleHeading(html);
  }
  const sanitized = sanitizeCustomHtml(html);
  return sanitized || undefined;
}
