"use client";

import DOMPurify from "dompurify";

/**
 * Render a sanitized HTML string as React children. Use this anywhere
 * `dangerouslySetInnerHTML` would otherwise be the only option (e.g.
 * email preview bodies, template bodies, etc.).
 *
 * DOMPurify is configured with a strict default profile plus a small
 * allow-list for the elements commonly used in our email templates
 * (inline styles, tables, images with http(s) sources). Custom config
 * can be passed via the second argument if needed.
 */
export function SafeHtml({
  html,
  className,
  ...rest
}: {
  html: string;
  className?: string;
} & React.HTMLAttributes<HTMLDivElement>) {
  const clean = DOMPurify.sanitize(html, {
    USE_PROFILES: { html: true },
    ALLOWED_ATTR: [
      "href", "target", "rel", "src", "alt", "title", "style", "class",
      "id", "name", "colspan", "rowspan", "width", "height", "align",
      "valign", "bgcolor", "color", "border", "cellpadding", "cellspacing",
      "role", "aria-label", "aria-hidden",
    ],
  });
  return (
    <div
      className={className}
      // The sanitizer above guarantees the result is safe to inject.
      dangerouslySetInnerHTML={{ __html: clean }}
      {...rest}
    />
  );
}
