/**
 * Rich HTML formatting for shop chatbot assistant replies (product cards + markdown).
 */
(function (global) {
    'use strict';

    function escapeHtml(value) {
        return String(value == null ? '' : value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function formatInlineMarkdown(text) {
        var escaped = escapeHtml(text);
        return escaped.replace(/\*\*([^*]+)\*\*/g, function (_match, inner) {
            return '<strong>' + inner + '</strong>';
        });
    }

    function catalogProductByTitle(catalog, title) {
        var needle = String(title || '').trim().toLowerCase();
        var list = Array.isArray(catalog) ? catalog : [];
        var i;

        if (!needle) {
            return null;
        }

        for (i = 0; i < list.length; i++) {
            if (
                list[i] &&
                String(list[i].title || '')
                    .trim()
                    .toLowerCase() === needle
            ) {
                return list[i];
            }
        }

        return null;
    }

    function productCardHtml(catalog, title, price, description) {
        var hit = catalogProductByTitle(catalog, title);
        var url = hit && hit.url ? String(hit.url) : '';
        var img = hit && hit.image ? String(hit.image).trim() : '';
        var thumb;
        var displayPrice = price;

        if (!displayPrice && hit && hit.price) {
            displayPrice = String(hit.price).trim();
        }

        var priceHtml = displayPrice
            ? '<span class="askagento-chatbot-product__price">' + escapeHtml(displayPrice) + '</span>'
            : '';
        var descHtml = description
            ? '<p class="askagento-chatbot-product__desc">' + formatInlineMarkdown(description) + '</p>'
            : '';
        var titleInner = url
            ? '<a href="' +
              escapeHtml(url) +
              '">' +
              escapeHtml(title) +
              '</a>'
            : escapeHtml(title);

        if (img) {
            thumb =
                '<img class="askagento-chatbot-product__img" src="' +
                escapeHtml(img) +
                '" alt="" loading="lazy" decoding="async">';
        } else {
            thumb =
                '<div class="askagento-chatbot-product__img askagento-chatbot-product__img--empty" aria-hidden="true"></div>';
        }

        // The local catalogue index only covers part of the shop, so many cards
        // have no image/link. Tag them so the frontend can fill the thumbnail
        // (and product link) from the search endpoint after render.
        var enrichAttr = img && url ? '' : ' data-enrich-title="' + escapeHtml(title) + '"';

        return (
            '<article class="askagento-chatbot-product"' + enrichAttr + '>' +
            thumb +
            '<div class="askagento-chatbot-product__body">' +
            '<h4 class="askagento-chatbot-product__title">' +
            titleInner +
            '</h4>' +
            priceHtml +
            descHtml +
            '</div></article>'
        );
    }

    function formatAssistantHtml(text, catalog) {
        var raw = String(text || '').trim();
        var lines;
        var html = '';
        var proseBuffer = [];
        var i;
        var line;
        var productMatch;
        var title;
        var tail;
        var price;
        var priceMatch;
        var descLines;
        var next;
        var joined;

        if (!raw) {
            return '<p class="askagento-chatbot-reply__prose">' + escapeHtml('') + '</p>';
        }

        function flushProse() {
            joined = proseBuffer.join('\n').trim();
            proseBuffer = [];
            if (!joined) {
                return;
            }
            html +=
                '<p class="askagento-chatbot-reply__prose">' +
                formatInlineMarkdown(joined).replace(/\n/g, '<br>') +
                '</p>';
        }

        lines = raw.split('\n');
        i = 0;

        while (i < lines.length) {
            line = lines[i];
            productMatch = line.match(/^\s*\d+\.\s+\*\*(.+?)\*\*(.*)$/);

            if (productMatch) {
                flushProse();
                title = productMatch[1].trim();
                tail = (productMatch[2] || '').trim();
                price = '';
                priceMatch =
                    tail.match(/(?:\||\u2014|\u2013|-)\s*(?:Price:\s*)?(\$[\d,.]+(?:\s*USD)?)/i) ||
                    tail.match(/(?:Price:\s*)?(\$[\d,.]+(?:\s*USD)?)/i);

                if (priceMatch) {
                    price = priceMatch[1].trim();
                }

                i += 1;
                descLines = [];

                while (i < lines.length) {
                    next = lines[i];
                    if (!next.trim()) {
                        i += 1;
                        break;
                    }
                    if (/^\s*\d+\.\s+\*\*/.test(next)) {
                        break;
                    }
                    descLines.push(next.trim());
                    i += 1;
                }

                html += productCardHtml(catalog, title, price, descLines.join(' '));
                continue;
            }

            proseBuffer.push(line);
            i += 1;
        }

        flushProse();

        if (!html) {
            return (
                '<p class="askagento-chatbot-reply__prose">' +
                formatInlineMarkdown(raw).replace(/\n/g, '<br>') +
                '</p>'
            );
        }

        return html;
    }

    global.pfChatbotReplyFormat = {
        escapeHtml: escapeHtml,
        formatAssistantHtml: formatAssistantHtml,
    };
})(typeof window !== 'undefined' ? window : this);
