'use client';

import DOMPurify from 'dompurify';
import { useEffect, useState, type ElementType, type HTMLAttributes } from 'react';

interface SafeHtmlProps extends HTMLAttributes<HTMLElement> {
  html: string;
  as?: ElementType;
}

// Client-only: dompurify needs a browser window, and the isomorphic variant pulls jsdom into SSR bundles.
export function SafeHtml({ html, as: Tag = 'div', ...props }: SafeHtmlProps) {
  const [sanitized, setSanitized] = useState('');
  useEffect(() => {
    setSanitized(DOMPurify.sanitize(html, { ALLOW_DATA_ATTR: false }));
  }, [html]);
  // eslint-disable-next-line react/no-danger
  return <Tag {...props} dangerouslySetInnerHTML={{ __html: sanitized }} />;
}
