import type { ReactNode } from 'react';
import DOMPurify from 'dompurify';

export const parseChatMessageText = (text: string): ReactNode => {
  const urlPattern = /(https?:\/\/\S+)/g;
  const emojiPattern = /(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)/gu;

  const parts = text.split(urlPattern);

  return parts.map((p, idx) =>
    urlPattern.test(p) ? (
      <a key={idx} href={p} target="_blank" rel="noopener noreferrer">
        {p}
      </a>
    ) : (
      <span
        key={idx}
        dangerouslySetInnerHTML={{
          __html: DOMPurify.sanitize(p.replace(emojiPattern, (emoji) => `<span style="font-size: 18px; line-height: 1.5;">${emoji}</span>`))
        }}
      />
    )
  );
};
