import { Fragment, createElement } from "react";
import type { RichNode } from "@/content/types";

export function RichText({ nodes }: { nodes: readonly RichNode[] }) {
  return (
    <>
      {nodes.map((node, i) => {
        if (node.type === "text")
          return <Fragment key={i}>{node.text}</Fragment>;
        if (node.type === "br") return <br key={i} />;
        if (node.type === "a")
          return (
            <a key={i} href={node.href}>
              <RichText nodes={node.children} />
            </a>
          );
        return createElement(
          node.type,
          { key: i },
          <RichText nodes={node.children} />,
        );
      })}
    </>
  );
}

export function plainText(nodes: readonly RichNode[]): string {
  return nodes
    .map((node) =>
      node.type === "text"
        ? node.text
        : node.type === "br"
          ? " "
          : plainText(node.children),
    )
    .join(" ")
    .replace(/\s+/g, " ")
    .trim();
}
