import { useMemo } from "react";
import RepoEmbedCard from "./repo-embed-card";
import XEmbedCard from "./x-embed-card";
import { parseRepoLinks } from "./repo-link-parser";
import { parseXLinks } from "./x-link-parser";

type Props = {
  content: string;
  contentType?: string;
};

/**
 * Renders message content, detecting same-origin repo links and
 * X/Twitter links, replacing them with embed cards.
 */
export default function MessageContent({ content, contentType }: Props) {
  const isPlainText = contentType === "text" || !contentType;

  const elements = useMemo(() => {
    const repoLinks = parseRepoLinks(content);
    const xLinks = parseXLinks(content);

    const allLinks = [
      ...repoLinks.map((l) => ({ kind: "repo" as const, url: l.url, data: l, index: content.indexOf(l.url) })),
      ...xLinks.map((l) => ({ kind: "x" as const, url: l.url, data: l, index: content.indexOf(l.url) })),
    ].sort((a, b) => a.index - b.index);

    if (allLinks.length === 0) {
      return [
        <p
          className={
            isPlainText
              ? "whitespace-pre-wrap break-words text-[13px] leading-[1.55] text-foreground/85"
              : "whitespace-pre-wrap break-words text-[13px] text-foreground/85"
          }
          key="only"
        >
          {content}
        </p>,
      ];
    }

    const result: React.ReactNode[] = [];
    let cursor = 0;

    for (const link of allLinks) {
      if (link.index > cursor) {
        const text = content.slice(cursor, link.index);
        if (text.trim()) {
          result.push(
            <p
              className={
                isPlainText
                  ? "whitespace-pre-wrap break-words text-[13px] leading-[1.55] text-foreground/85"
                  : "whitespace-pre-wrap break-words text-[13px] text-foreground/85"
              }
              key={`t-${cursor}`}
            >
              {text}
            </p>,
          );
        }
      }

      if (link.kind === "repo") {
        result.push(<RepoEmbedCard key={`repo-${link.url}`} link={link.data} />);
      } else {
        result.push(<XEmbedCard key={`x-${link.url}`} link={link.data} />);
      }

      cursor = link.index + link.url.length;
    }

    if (cursor < content.length) {
      const text = content.slice(cursor);
      if (text.trim()) {
        result.push(
          <p
            className={
              isPlainText
                ? "whitespace-pre-wrap break-words text-[13px] leading-[1.55] text-foreground/85"
                : "whitespace-pre-wrap break-words text-[13px] text-foreground/85"
            }
            key={`t-${cursor}`}
          >
            {text}
          </p>,
        );
      }
    }

    return result;
  }, [content, isPlainText]);

  return <div>{elements}</div>;
}
