import DOMPurify from "dompurify";
import { ComponentProps } from "react";

let purifier: ReturnType<typeof DOMPurify>;

if (typeof window === "undefined") {
  // Mock the window object in SSR environments
  const { JSDOM } = require("jsdom");
  const windowObj = new JSDOM("").window;
  purifier = DOMPurify(windowObj);
} else {
  // CSR: use the browser's window
  purifier = DOMPurify(window);
}

// Hook: remove Froala footer <p> with <a title="Froala Editor">
purifier.addHook("uponSanitizeElement", (node, data) => {
  if (data.tagName === "p") {
    const anchor = (node as Element).querySelector('a[title="Froala Editor"]');
    if (anchor) {
      node.parentNode?.removeChild(node);
    }
  }
});

function SanitizedHTML({
  content,
  className,
}: {
  content: string;
  className?: ComponentProps<"div">["className"];
}): React.ReactElement {
  return (
    <div
      className={className}
      dangerouslySetInnerHTML={{ __html: purifier.sanitize(content) }}
    />
  );
}

export default SanitizedHTML;
