"use client";

import DOMPurify from "dompurify";
import { useMemo } from "react";
import clsx from "clsx";

interface RichTextProps {
  content?: string | null;
  className?: string;
}

export default function RichText({ content, className }: RichTextProps) {
  const sanitizedHtml = useMemo(() => {
    if (!content) return "";

    const clean = DOMPurify.sanitize(content, {
      USE_PROFILES: { html: true },
      ADD_TAGS: ["iframe", "video", "source", "figure", "figcaption"],
      ADD_ATTR: [
        "allow",
        "allowfullscreen",
        "frameborder",
        "loading",
        "target",
        "rel",
      ],
    });

    const parser = new DOMParser();
    const doc = parser.parseFromString(clean, "text/html");

    doc.querySelectorAll("a").forEach((link) => {
      const href = link.getAttribute("href");

      if (!href) return;

      if (href.startsWith("http://") || href.startsWith("https://")) {
        link.setAttribute("target", "_blank");
        link.setAttribute("rel", "noopener noreferrer");
      }
    });

    return doc.body.innerHTML;
  }, [content]);

  return (
    <div className={clsx("rich-text", className)}      
      dangerouslySetInnerHTML={{
        __html: sanitizedHtml,
      }}
    />
  );
}
