import React, { useMemo } from 'react';
import { splitChatTextLines } from './chatDataUtils';
import styles from './ChatAssistant.module.css';

interface ChatMessageTextProps {
  text: string;
}

const INLINE_MARKDOWN_PATTERN = /\*\*(.+?)\*\*/g;

function renderInlineMarkdown(line: string): React.ReactNode {
  if (!line.includes('**')) {
    return line;
  }

  const parts: React.ReactNode[] = [];
  let lastIndex = 0;
  let match: RegExpExecArray | null;
  let key = 0;

  INLINE_MARKDOWN_PATTERN.lastIndex = 0;

  while ((match = INLINE_MARKDOWN_PATTERN.exec(line)) !== null) {
    if (match.index > lastIndex) {
      parts.push(line.slice(lastIndex, match.index));
    }

    parts.push(<strong key={key++}>{match[1]}</strong>);
    lastIndex = INLINE_MARKDOWN_PATTERN.lastIndex;
  }

  if (lastIndex < line.length) {
    parts.push(line.slice(lastIndex));
  }

  return parts.length > 0 ? parts : line;
}

const ChatMessageText: React.FC<ChatMessageTextProps> = ({ text }) => {
  const lines = useMemo(() => splitChatTextLines(text), [text]);

  return (
    <div className={styles.chatBubbleText}>
      {lines.map((line, index) =>
        line === '' ? (
          <div key={index} className={styles.chatBubbleTextSpacer} aria-hidden="true" />
        ) : (
          <div key={index} className={styles.chatBubbleTextLine}>
            {renderInlineMarkdown(line)}
          </div>
        ),
      )}
    </div>
  );
};

export default ChatMessageText;
