import React from 'react';
import CodeBlock from './CodeBlock';

const formatText = (text) => {
  return text
    .replace(/\n/g, "<br>")
    .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
    .replace(/\*(.*?)\*/g, "<em>$1</em>");
};

export default function MessageBubble({ role, content, time }) {
  return (
    <div className={`message ${role}`}>
      <div className="bubble">
        <FormattedContent content={content} />
        <div className="timestamp">{time}</div>
      </div>
    </div>
  );
}

function FormattedContent({ content }) {
  const blocks = content.split('```');

  return (
    <>
      {blocks.map((block, i) =>
        i % 2 === 1 ? (
          <CodeBlock key={i} content={block} />
        ) : (
          <div
            key={i}
            className="formatted-text"
            dangerouslySetInnerHTML={{ __html: formatText(block) }}
          />
        )
      )}
    </>
  );
}
