import { RichText } from "@atproto/api";
import type * as feedPost from "@/lib/lexicons/app/bsky/feed/post";
import * as facet from "@/lib/lexicons/app/bsky/richtext/facet";

interface BlueskyRichTextProps {
  record: feedPost.Main;
}

export function BlueskyRichText({ record }: BlueskyRichTextProps) {
  const rt = new RichText({
    text: record.text,
    facets: record.facets,
  });

  const richText = [];
  let counter = 0;

  for (const segment of rt.segments()) {
    if (segment.link && facet.link.$validate(segment.link).success) {
      richText.push(
        <a
          key={counter}
          href={segment.link.uri}
          className="BlueskyPostEmbed-link"
          target="_blank"
          rel="noopener noreferrer"
        >
          {segment.text}
        </a>,
      );
    } else if (segment.mention && facet.mention.$validate(segment.mention).success) {
      richText.push(
        <a
          key={counter}
          href={`https://bsky.app/profile/${segment.mention.did}`}
          className="BlueskyPostEmbed-mention"
          target="_blank"
          rel="noopener noreferrer"
        >
          {segment.text}
        </a>,
      );
    } else if (segment.tag && facet.tag.$validate(segment.tag).success) {
      richText.push(
        <a
          key={counter}
          href={`https://bsky.app/hashtag/${segment.tag.tag}`}
          className="BlueskyPostEmbed-tag"
          target="_blank"
          rel="noopener noreferrer"
        >
          {segment.text}
        </a>,
      );
    } else {
      richText.push(segment.text);
    }

    counter++;
  }

  return <>{richText}</>;
}
