import DOMPurify from "isomorphic-dompurify";
import { cn } from "@/lib/utils";

const ALLOWED_TAGS = [
  "p",
  "br",
  "strong",
  "b",
  "em",
  "i",
  "s",
  "ul",
  "ol",
  "li",
  "a",
  "img",
  "blockquote",
  "h2",
  "h3",
] as const;

const ALLOWED_ATTR = [
  "href",
  "title",
  "target",
  "rel",
  "src",
  "alt",
  "width",
  "height",
] as const;

type RichTextContentProps = {
  content?: string | null;
  className?: string;
  emptyContent?: React.ReactNode;
};

/** Renders rich-text editor HTML through one shared, XSS-safe allowlist. */
export function RichTextContent({
  content,
  className,
  emptyContent = null,
}: RichTextContentProps) {
  const value = content?.trim();

  if (!value) {
    return <>{emptyContent}</>;
  }

  const hasHtml = /<\/?[a-z][\s\S]*>/i.test(value);

  if (!hasHtml) {
    return <div className={cn("whitespace-pre-wrap", className)}>{value}</div>;
  }

  const sanitizedHtml = DOMPurify.sanitize(value, {
    ALLOWED_TAGS: [...ALLOWED_TAGS],
    ALLOWED_ATTR: [...ALLOWED_ATTR],
  });

  return (
    <div
      className={className}
      dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
    />
  );
}
