import { useState } from "react";
import type { ReactNode } from "react";

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

interface EmojiTextProps {
  text: string;
}

function getFluentEmojiCDN(emoji: string) {
  const code = Array.from(emoji)
    .map((char) => char.codePointAt(0)?.toString(16))
    .filter(Boolean)
    .join("-");

  return `https://cdn.jsdelivr.net/gh/microsoft/fluentui-emoji/assets/${code}/3D/${code}.png`;
}

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)}
      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)}</>;
}
