import { useState } from "react";
import type { ReactNode } from "react";
import { getFluentEmojiCDN } from "@lobehub/fluent-emoji/es/getFluentEmojiCDN";

const emojiRegex =
  /(\p{Extended_Pictographic}(?:\uFE0F|\uFE0E)?(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\uFE0E)?)*)/gu;

interface EmojiTextProps {
  text: string;
}

function FluentEmojiImage({ emoji }: { emoji: string }) {
  const [failed, setFailed] = useState(false);

  if (failed) {
    return (
      <span className="mx-0.5 inline-block translate-y-[1px] text-[0.95em] leading-none">
        {emoji}
      </span>
    );
  }

  return (
    <img
      src={getFluentEmojiCDN(emoji, { cdn: "unpkg", type: "3d" })}
      alt={emoji}
      loading="lazy"
      onError={() => setFailed(true)}
      className="mx-0.5 inline-block h-[1.45em] w-[1.45em] translate-y-[0.32em] object-contain"
      draggable={false}
    />
  );
}

export function renderEmojiText(text: string): ReactNode {
  const parts = text.split(emojiRegex);

  return parts.map((part, index) => {
    if (!part) return null;

    if (emojiRegex.test(part)) {
      emojiRegex.lastIndex = 0;

      return <FluentEmojiImage key={`${part}-${index}`} emoji={part} />;
    }

    emojiRegex.lastIndex = 0;
    return part;
  });
}

export function EmojiText({ text }: EmojiTextProps) {
  return <>{renderEmojiText(text)}</>;
}
