import parse, {
  domToReact,
  Element,
  type DOMNode,
  type HTMLReactParserOptions,
} from "html-react-parser";
import Link from "next/link";
import { ButtonLink } from "@/components/general/ButtonLink";
import { internalHref } from "@/lib/links";

/**
 * Renders CMS rich text (HTML) as React. Everything renders as plain HTML,
 * except:
 *
 * - inline button markers (`<a class="button">` from the button-link Draftail
 *   feature) become the ButtonLink component
 * - links pointing at this site become next/link
 */
const options: HTMLReactParserOptions = {
  replace: (node) => {
    if (!(node instanceof Element) || node.name !== "a") {
      return;
    }
    const href = node.attribs.href ?? "#";
    const internal = internalHref(href);
    if (node.attribs.class?.split(/\s+/).includes("button")) {
      return (
        <ButtonLink href={internal ?? href}>
          {domToReact(node.children as DOMNode[], options)}
        </ButtonLink>
      );
    }
    if (internal) {
      return (
        <Link href={internal}>
          {domToReact(node.children as DOMNode[], options)}
        </Link>
      );
    }
  },
};

export const RichText = ({ content }: { content: string }) => {
  return <>{parse(content, options)}</>;
};
