/* global jQuery, askagentoAiChatbotAdmin, pfChatbotReplyFormat */
(function ($) {
    'use strict';

    function escapeHtml(value) {
        return $('<div>').text(value == null ? '' : String(value)).html();
    }

    // Fill product-card thumbnails/links the reply references but the local
    // catalog index doesn't cover. Mirrors enrichProductImages in front-chatbot.js
    // (one batched, exact-title lookup via the askagento_ai_chatbot_resolve AJAX).
    function enrichProductImages(scope) {
        var ajaxUrl = askagentoAiChatbotAdmin.ajaxUrl;
        var nonce = askagentoAiChatbotAdmin.textSearchNonce;

        if (!scope || !ajaxUrl || !nonce) {
            return;
        }

        var cards = scope.querySelectorAll('.askagento-chatbot-product[data-enrich-title]');

        if (!cards.length) {
            return;
        }

        var byTitle = {};

        Array.prototype.forEach.call(cards, function (card) {
            var t = card.getAttribute('data-enrich-title') || '';

            if (t) {
                (byTitle[t] = byTitle[t] || []).push(card);
            }
        });

        var titles = Object.keys(byTitle);

        if (!titles.length) {
            return;
        }

        var fd = new FormData();
        fd.append('action', 'askagento_ai_chatbot_resolve');
        fd.append('nonce', nonce);
        fd.append('titles', JSON.stringify(titles));

        fetch(ajaxUrl, { method: 'POST', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    return;
                }

                var rows = Array.isArray(data.data.results) ? data.data.results : [];

                rows.forEach(function (row) {
                    var matchCards = byTitle[row.title];

                    if (!matchCards) {
                        return;
                    }

                    var imgUrl = row.image_url ? String(row.image_url).trim() : '';
                    var link = row.permalink ? String(row.permalink) : '';

                    matchCards.forEach(function (card) {
                        if (imgUrl) {
                            var ph = card.querySelector('.askagento-chatbot-product__img--empty');

                            if (ph) {
                                var im = document.createElement('img');
                                im.className = 'askagento-chatbot-product__img';
                                im.src = imgUrl;
                                im.alt = '';
                                im.loading = 'lazy';
                                im.decoding = 'async';
                                ph.replaceWith(im);
                            }
                        }

                        if (link) {
                            var titleEl = card.querySelector('.askagento-chatbot-product__title');

                            if (titleEl && !titleEl.querySelector('a')) {
                                var a = document.createElement('a');
                                a.href = link;
                                a.textContent = titleEl.textContent;
                                titleEl.textContent = '';
                                titleEl.appendChild(a);
                            }
                        }

                        card.removeAttribute('data-enrich-title');
                    });
                });
            })
            .catch(function () {
                /* leave placeholder on failure */
            });
    }

    function mapQuotaMessage(msg) {
        var m = String(msg || '').trim();
        var i18n = askagentoAiChatbotAdmin.i18n || {};

        if (m === 'AI token quota exceeded') {
            return i18n.aiTokenQuotaExceeded || m;
        }

        if (m === 'AI search quota exceeded') {
            return i18n.aiSearchQuotaExceeded || m;
        }

        return m;
    }

    async function postChatbot(payload) {
        var i18n = askagentoAiChatbotAdmin.i18n || {};

        if (!askagentoAiChatbotAdmin.chatbotUrl || !askagentoAiChatbotAdmin.siteId || !askagentoAiChatbotAdmin.apiKey) {
            throw new Error(i18n.chatbotUnavailable || '');
        }

        var ctrl = new AbortController();
        var timer = window.setTimeout(function () {
            ctrl.abort();
        }, 120000);

        var res;

        try {
            res = await fetch(askagentoAiChatbotAdmin.chatbotUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Askagento-Site-Id': askagentoAiChatbotAdmin.siteId,
                    'X-Askagento-Api-Key': askagentoAiChatbotAdmin.apiKey
                },
                body: JSON.stringify(payload),
                signal: ctrl.signal
            });
        } finally {
            window.clearTimeout(timer);
        }

        var text = await res.text();
        var decoded;

        try {
            decoded = text ? JSON.parse(text) : {};
        } catch (eJson) {
            throw new Error(i18n.requestFailed || 'Bad JSON');
        }

        if (!res.ok) {
            var remoteErr =
                decoded && typeof decoded.error === 'string' && decoded.error.trim() !== ''
                    ? decoded.error.trim()
                    : res.statusText || '';

            if (!remoteErr) {
                remoteErr = 'HTTP ' + String(res.status);
            }

            throw new Error(mapQuotaMessage(remoteErr));
        }

        return decoded;
    }

    $(function () {
        var $btn = $('#askagento-ai-chatbot-check-btn');
        var $out = $('#askagento-ai-chatbot-check-result');
        var $send = $('#askagento-ai-chatbot-send-btn');
        var $msg = $('#askagento-ai-chatbot-test-message');
        var $chatOut = $('#askagento-ai-chatbot-chat-result');
        var i18n = askagentoAiChatbotAdmin.i18n || {};

        if (!$btn.length || !$out.length) {
            return;
        }

        $btn.on('click', function () {
            var $b = $(this);

            $b.prop('disabled', true);
            $out.html('<p class="description">' + escapeHtml(i18n.working || '') + '</p>');

            postChatbot({ action: 'health' })
                .then(function (data) {
                    var lines = [];
                    var latMs = data.latency_ms != null ? Number(data.latency_ms) : NaN;
                    var pingSec = Number.isFinite(latMs) ? (latMs / 1000).toFixed(1) : '—';
                    var tok = data.usage && data.usage.total_tokens != null ? String(data.usage.total_tokens) : '—';

                    lines.push(
                        '<p class="askagento-ai-chatbot-health-ping">' +
                            escapeHtml(i18n.ping || 'Ping:') +
                            ' <strong>' +
                            escapeHtml(pingSec) +
                            '</strong> ' +
                            escapeHtml(i18n.pingUnit || 's') +
                            '</p>'
                    );
                    lines.push(
                        '<p class="askagento-ai-chatbot-health-success">' +
                            '<span class="askagento-ai-chatbot-health-check" aria-hidden="true">✓</span> ' +
                            escapeHtml(i18n.healthWorks || '') +
                            '</p>'
                    );
                    lines.push('<p><strong>' + escapeHtml(i18n.labelTokens || 'Tokens (this call)') + ':</strong> ' + escapeHtml(tok) + '</p>');
                    $out.html(lines.join(''));
                })
                .catch(function (err) {
                    $out.html(
                        '<p class="notice notice-error" style="padding:8px 12px;">' +
                            escapeHtml(err && err.message ? err.message : i18n.failed || '') +
                            '</p>'
                    );
                })
                .finally(function () {
                    $b.prop('disabled', false);
                });
        });

        if ($send.length && $msg.length && $chatOut.length) {
            $send.on('click', function () {
                var text = ($msg.val() || '').trim();
                var $s = $(this);

                if (text.length < 1) {
                    $chatOut.html(
                        '<p class="notice notice-warning" style="padding:8px 12px;">' +
                            escapeHtml(i18n.enterMessage || '') +
                            '</p>'
                    );

                    return;
                }

                $s.prop('disabled', true);
                $chatOut.html('<p class="description">' + escapeHtml(i18n.workingChat || '') + '</p>');

                postChatbot({
                    action: 'chat',
                    messages: [{ role: 'user', content: text }],
                    max_completion_tokens: 2048
                })
                    .then(function (data) {
                        var reply = data.reply != null ? String(data.reply) : '';
                        var tok = data.usage && data.usage.total_tokens != null ? String(data.usage.total_tokens) : '—';

                        var catalog =
                            askagentoAiChatbotAdmin.catalog && Array.isArray(askagentoAiChatbotAdmin.catalog)
                                ? askagentoAiChatbotAdmin.catalog
                                : [];
                        var replyHtml;

                        if (
                            typeof pfChatbotReplyFormat !== 'undefined' &&
                            pfChatbotReplyFormat &&
                            typeof pfChatbotReplyFormat.formatAssistantHtml === 'function'
                        ) {
                            replyHtml = pfChatbotReplyFormat.formatAssistantHtml(reply, catalog);
                        } else {
                            replyHtml = escapeHtml(reply).replace(/\n/g, '<br>');
                        }

                        $chatOut.html(
                            '<div class="askagento-ai-chatbot-reply">' + replyHtml + '</div>' +
                                '<p class="description">' +
                                escapeHtml(i18n.labelTokens || '') +
                                ': ' +
                                escapeHtml(tok) +
                                '</p>'
                        );

                        // Fill thumbnails/links for product cards not covered by the local catalog.
                        enrichProductImages($chatOut.get(0));
                    })
                    .catch(function (err) {
                        $chatOut.html(
                            '<p class="notice notice-error" style="padding:8px 12px;">' +
                                escapeHtml(err && err.message ? err.message : i18n.failed || '') +
                                '</p>'
                        );
                    })
                    .finally(function () {
                        $s.prop('disabled', false);
                    });
            });
        }
    });
})(jQuery);
