/**
 * Lightweight Markdown Parser for Askany Chat
 * Supports common markdown syntax for chat messages
 */

(function(window) {
    'use strict';

    var MarkdownParser = {
        /**
         * Parse markdown text to HTML
         * @param {string} text - Markdown text
         * @return {string} HTML string
         */
        parse: function(text) {
            if (!text) return '';

            // Escape HTML first to prevent XSS
            text = this.escapeHtml(text);

            // Parse in order of precedence
            text = this.parseCodeBlocks(text);
            text = this.parseInlineCode(text);
            text = this.parseHeaders(text);
            text = this.parseBold(text);
            text = this.parseItalic(text);
            text = this.parseStrikethrough(text);
            text = this.parseLists(text);
            text = this.parseBlockquotes(text);
            text = this.parseLinks(text);
            text = this.parseLineBreaks(text);

            return text.trim();
        },

        /**
         * Escape HTML special characters
         */
        escapeHtml: function(text) {
            var map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, function(m) { return map[m]; });
        }
    };

    // Export to window
    window.AskanyMarkdown = MarkdownParser;

})(window);
