// Format message with markdown-like syntax
function formatMessage(text) {
    // Escape HTML first
    let formatted = text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');

    // Code blocks with language detection (```language\ncode```)
    formatted = formatted.replace(/```(\w+)?\n?([\s\S]*?)```/g, function (match, language, code) {
        const lang = language || 'code';
        const codeId = 'code-' + Math.random().toString(36).substr(2, 9);
        return `<pre><div class="code-header"><span class="code-language">${lang}</span><button class="copy-btn" onclick="copyCode('${codeId}')">Copy</button></div><code id="${codeId}">${applySyntaxHighlight(code.trim(), lang)}</code></pre>`;
    });

    // Inline code (`code`) - must come after code blocks
    formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>');

    // Headings (### Heading)
    formatted = formatted.replace(/^### (.+)$/gm, '<h3>$1</h3>');
    formatted = formatted.replace(/^## (.+)$/gm, '<h2>$1</h2>');
    formatted = formatted.replace(/^# (.+)$/gm, '<h1>$1</h1>');

    // Blockquotes (> text)
    formatted = formatted.replace(/^&gt; (.+)$/gm, '<blockquote>$1</blockquote>');

    // Unordered lists (- item or * item)
    formatted = formatted.replace(/^[-*] (.+)$/gm, '<li>$1</li>');
    // Wrap consecutive <li> in <ul>
    formatted = formatted.replace(/(<li>.*?<\/li>\n?)+/gs, function (match) {
        return '<ul>' + match + '</ul>';
    });

    // Numbered lists (1. item)
    formatted = formatted.replace(/^\d+\. (.+)$/gm, '<li class="numbered">$1</li>');
    // Wrap numbered <li> in <ol>
    formatted = formatted.replace(/(<li class="numbered">.*?<\/li>\n?)+/gs, function (match) {
        return '<ol>' + match.replace(/ class="numbered"/g, '') + '</ol>';
    });

    // Bold (**text** or __text__)
    formatted = formatted.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
    formatted = formatted.replace(/__([^_]+)__/g, '<strong>$1</strong>');

    // Italic (*text*) - simple version to avoid conflicts
    formatted = formatted.replace(/\*([^\*\n]+)\*/g, '<em>$1</em>');

    // Horizontal rule (---)
    formatted = formatted.replace(/^---$/gm, '<hr>');

    // Auto-link URLs
    formatted = formatted.replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');

    // Line breaks (convert \n to <br>, but not inside block elements)
    formatted = formatted.replace(/\n(?!<\/?(h[1-3]|li|ul|ol|blockquote|hr))/g, '<br>');

    return formatted;
}

// TEST FUNCTION - Remove after testing
console.log('Enhanced formatMessage loaded successfully');
