'use client';

import React from 'react';

interface TextElement {
  type: string;
  text: string;
}

export default function TextRenderer({ text }: { text: TextElement | string }) {
  const content = typeof text === 'string' ? text : text.text;
  const isMarkdown = typeof text === 'object' ? text.type === 'mrkdwn' : false;

  if (!isMarkdown) {
    return <span className="text-sm text-gray-200">{content}</span>;
  }

  const html = formatMarkdown(content);
  return (
    <div
      className="text-sm leading-relaxed text-gray-200"
      dangerouslySetInnerHTML={{ __html: html }}
    />
  );
}

function formatMarkdown(text: string): string {
  let html = text;

  // Bold: *text*
  html = html.replace(/\*(.+?)\*/g, '<strong>$1</strong>');
  // Italic: _text_
  html = html.replace(/_(.+?)_/g, '<em>$1</em>');
  // Strike: ~text~
  html = html.replace(/~(.+?)~/g, '<del>$1</del>');
  // Inline code: `text`
  html = html.replace(/`(.+?)`/g, '<code class="rounded bg-gray-700 px-1 py-0.5 text-xs font-mono">$1</code>');
  // Code block: ```text```
  html = html.replace(/```([\s\S]+?)```/g, '<pre class="rounded bg-gray-800 p-2 my-1 overflow-x-auto"><code class="text-xs font-mono text-gray-300">$1</code></pre>');
  // Links: <http://...|text>
  html = html.replace(/&lt;(https?:\/\/[^|]+)\|([^&]+)&gt;/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:underline">$2</a>');
  html = html.replace(/<(https?:\/\/[^|]+)>/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:underline">$1</a>');
  // Mentions: <@U12345>
  html = html.replace(/&lt;@(\w+)&gt;/g, '<span class="text-blue-400 font-medium">@$1</span>');
  // Channel links: <#C12345|general>
  html = html.replace(/&lt;#(\w+)\|([^&]+)&gt;/g, '<span class="text-blue-400 font-medium">#$2</span>');
  // Line breaks
  html = html.replace(/\n/g, '<br/>');

  return html;
}