import React from 'react';

// Simple markdown-like parsing for Discord-style formatting
export function parseMarkdown(text) {
  if (!text) return null;

  const elements = [];
  let remaining = text;
  let key = 0;

  const patterns = [
    // Code blocks (```)
    { regex: /```(\w+)?\n?([\s\S]*?)```/g, render: (match, lang, code) => (
      <pre key={key++} className="code-block" data-language={lang}>
        <code>{code}</code>
      </pre>
    )},
    // Inline code (`)
    { regex: /`([^`]+)`/g, render: (match, code) => (
      <code key={key++} className="inline-code">{code}</code>
    )},
    // Spoiler (||text||)
    { regex: /\|\|([^|]+)\|\|/g, render: (match, content) => (
      <span key={key++} className="spoiler" onClick={(e) => e.target.classList.toggle('revealed')}>
        {content}
      </span>
    )},
    // Bold (**text**)
    { regex: /\*\*([^*]+)\*\*/g, render: (match, content) => (
      <strong key={key++}>{content}</strong>
    )},
    // Italic (*text* or _text_)
    { regex: /(?:\*|_)([^*_]+)(?:\*|_)/g, render: (match, content) => (
      <em key={key++}>{content}</em>
    )},
    // Strikethrough (~~text~~)
    { regex: /~~([^~]+)~~/g, render: (match, content) => (
      <del key={key++}>{content}</del>
    )},
    // Underline (__text__)
    { regex: /__([^_]+)__/g, render: (match, content) => (
      <u key={key++}>{content}</u>
    )},
    // Links [text](url)
    { regex: /\[([^\]]+)\]\(([^)]+)\)/g, render: (match, text, url) => (
      <a key={key++} href={url} target="_blank" rel="noopener noreferrer" className="message-link">
        {text}
      </a>
    )},
    // Auto-link URLs
    { regex: /(https?:\/\/[^\s<]+)/g, render: (match, url) => (
      <a key={key++} href={url} target="_blank" rel="noopener noreferrer" className="message-link">
        {url}
      </a>
    )},
    // Mentions (@user)
    { regex: /@(\w+)/g, render: (match, user) => (
      <span key={key++} className="mention">@{user}</span>
    )},
    // Channel mentions (#channel)
    { regex: /#(\w+)/g, render: (match, channel) => (
      <span key={key++} className="channel-mention">#{channel}</span>
    )},
    // Role mentions (@&role)
    { regex: /@&(\w+)/g, render: (match, role) => (
      <span key={key++} className="role-mention">@{role}</span>
    )},
    // Emoji :emoji_name:
    { regex: /:(\w+):/g, render: (match, name) => {
      const emojiMap = {
        smile: '😊', laughing: '😆', heart: '❤️', fire: '🔥', 
        rocket: '🚀', thumbsup: '👍', thumbsdown: '👎', check: '✅',
        x: '❌', star: '⭐', eyes: '👀', thinking: '🤔',
        aethex: '🔺', foundation: '🔴', corporation: '🔵', labs: '🟠',
      };
      const emoji = emojiMap[name.toLowerCase()];
      return emoji ? <span key={key++} className="emoji">{emoji}</span> : match;
    }},
    // Block quote (> text)
    { regex: /^>\s(.+)$/gm, render: (match, content) => (
      <blockquote key={key++} className="block-quote">{content}</blockquote>
    )},
  ];

  // Process special patterns
  // For simplicity, we'll do a basic render with some patterns
  const processedText = text
    .replace(/```(\w+)?\n?([\s\S]*?)```/g, '⟦CODE_BLOCK⟧$1⟦SEP⟧$2⟦END_CODE⟧')
    .replace(/`([^`]+)`/g, '⟦INLINE_CODE⟧$1⟦END_INLINE⟧')
    .replace(/\|\|([^|]+)\|\|/g, '⟦SPOILER⟧$1⟦END_SPOILER⟧')
    .replace(/\*\*([^*]+)\*\*/g, '⟦BOLD⟧$1⟦END_BOLD⟧')
    .replace(/~~([^~]+)~~/g, '⟦STRIKE⟧$1⟦END_STRIKE⟧')
    .replace(/__([^_]+)__/g, '⟦UNDERLINE⟧$1⟦END_UNDERLINE⟧')
    .replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '⟦ITALIC⟧$1⟦END_ITALIC⟧')
    .replace(/(?<!_)_([^_]+)_(?!_)/g, '⟦ITALIC⟧$1⟦END_ITALIC⟧');

  return <span dangerouslySetInnerHTML={{ __html: renderMarkdown(text) }} />;
}

function renderMarkdown(text) {
  let html = text
    // Escape HTML
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    // Code blocks
    .replace(/```(\w+)?\n?([\s\S]*?)```/g, '<pre class="code-block"><code>$2</code></pre>')
    // Inline code
    .replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
    // Spoilers
    .replace(/\|\|([^|]+)\|\|/g, '<span class="spoiler">$1</span>')
    // Bold
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    // Strikethrough
    .replace(/~~([^~]+)~~/g, '<del>$1</del>')
    // Underline
    .replace(/__([^_]+)__/g, '<u>$1</u>')
    // Italic
    .replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>')
    // Mentions
    .replace(/@(\w+)/g, '<span class="mention">@$1</span>')
    // Channel mentions
    .replace(/#(\w[-\w]*)/g, '<span class="channel-mention">#$1</span>')
    // Links
    .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="message-link" target="_blank">$1</a>')
    // Auto URLs
    .replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" class="message-link" target="_blank">$1</a>')
    // Block quotes
    .replace(/^&gt;\s(.+)$/gm, '<blockquote class="block-quote">$1</blockquote>')
    // Newlines
    .replace(/\n/g, '<br>');

  return html;
}

export default function MarkdownText({ children }) {
  if (typeof children !== 'string') return children;
  return parseMarkdown(children);
}
