/* global askagentoAgentsMcp */
(function () {
    'use strict';

    var cfg = (typeof askagentoAgentsMcp !== 'undefined') ? askagentoAgentsMcp : {};
    var mcpUrl = cfg.mcpUrl  || '';
    var siteId = cfg.siteId  || '';
    var apiKey = cfg.apiKey  || '';
    var i18n   = cfg.i18n    || {};

    // ── Auth headers ────────────────────────────────────────────────────────

    function authHeaders() {
        return {
            'Content-Type':        'application/json',
            'X-Askagento-Site-Id': siteId,
            'X-Askagento-Api-Key': apiKey,
        };
    }

    // ── Low-level MCP call ──────────────────────────────────────────────────

    function mcpCall(method, params, onOk, onErr) {
        if (!mcpUrl) {
            onErr(i18n.notConfigured || 'MCP endpoint not configured.');
            return;
        }

        fetch(mcpUrl, {
            method:  'POST',
            headers: authHeaders(),
            body: JSON.stringify({
                jsonrpc: '2.0',
                id:      Date.now(),
                method:  method,
                params:  params || {},
            }),
        })
        .then(function (res) { return res.json(); })
        .then(function (data) {
            if (data && data.error) {
                onErr(data.error.message || JSON.stringify(data.error));
            } else if (data && data.result !== undefined) {
                onOk(data.result);
            } else {
                onErr(i18n.failed || 'Unexpected response: ' + JSON.stringify(data));
            }
        })
        .catch(function (err) {
            onErr((err && err.message) || String(err));
        });
    }

    // ── UI helpers ──────────────────────────────────────────────────────────

    function escHtml(s) {
        return String(s)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function setLoading(elId, msg) {
        var el = document.getElementById(elId);
        if (el) {
            el.innerHTML = '<p style="color:#646970;">' + escHtml(msg) + '</p>';
        }
    }

    function setError(elId, msg) {
        var el = document.getElementById(elId);
        if (el) {
            el.innerHTML = '<p style="color:#d63638;"><strong>' + escHtml(msg) + '</strong></p>';
        }
    }

    function formatAdminDate(value, callback) {
        var v = String(value || '').trim();
        if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) {
            callback(v);
            return;
        }

        var url = cfg.ajaxUrl || (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
        if (!url || !cfg.nonce) {
            callback(v);
            return;
        }

        jQuery.post(url, {
            action: 'askagento_format_admin_date',
            nonce:  cfg.nonce,
            date:   v,
        }, function (resp) {
            if (resp && resp.success && resp.data && resp.data.formatted) {
                callback(resp.data.formatted);
            } else {
                callback(v);
            }
        }).fail(function () {
            callback(v);
        });
    }

    // ── Probe: initialize + tools/list ──────────────────────────────────────

    function runProbe() {
        var resultId = 'askagento-mcp-probe-result';
        setLoading(resultId, i18n.probing || 'Running MCP probe...');

        mcpCall(
            'initialize',
            {
                protocolVersion: '2024-11-05',
                capabilities:    {},
                clientInfo:      { name: 'askagento-wp-admin', version: '1.0' },
            },
            function (initResult) {
                var protoVer = initResult.protocolVersion || '?';
                var srvName  = (initResult.serverInfo && initResult.serverInfo.name) || '?';
                var srvVer   = (initResult.serverInfo && initResult.serverInfo.version) || '?';

                mcpCall(
                    'tools/list',
                    {},
                    function (listResult) {
                        var tools = (listResult && listResult.tools) || [];
                        var toolTags = tools.map(function (t) {
                            return '<span class="askagento-mcp-tool-tag">' + escHtml(t.name || '') + '</span>';
                        }).join('');

                        var el = document.getElementById(resultId);
                        if (!el) {
                            return;
                        }

                        formatAdminDate(protoVer, function (protoDisplay) {
                            el.innerHTML =
                                '<p class="askagento-mcp-success">&#10003; ' + escHtml(i18n.handshakeSuccess || 'MCP handshake successful') + '</p>' +
                                '<p><strong>' + escHtml(i18n.protocolVersion || 'Protocol version') + ':</strong> ' + escHtml(protoDisplay) + '</p>' +
                                '<p><strong>' + escHtml(i18n.server || 'Server') + ':</strong> ' + escHtml(srvName + ' v' + srvVer) + '</p>' +
                                '<p><strong>' + escHtml(i18n.tools || 'Tools') + ' (' + tools.length + '):</strong> ' + (toolTags || '(none)') + '</p>';
                        });
                    },
                    function (err) { setError(resultId, i18n.failed + ' ' + err); }
                );
            },
            function (err) { setError(resultId, i18n.failed + ' ' + err); }
        );
    }

    // ── Search test ─────────────────────────────────────────────────────────

    function runSearch() {
        var resultId = 'askagento-mcp-search-result';
        var queryEl  = document.getElementById('askagento-mcp-search-query');
        var query    = queryEl ? queryEl.value.trim() : '';

        if (!query) {
            setError(resultId, 'Enter a search query first.');
            return;
        }

        setLoading(resultId, 'Searching via MCP...');

        mcpCall(
            'tools/call',
            { name: 'search_products', arguments: { query: query, limit: 8 } },
            function (result) {
                var text = ((result.content || [])[0] || {}).text || '';
                var el = document.getElementById(resultId);
                if (el) {
                    el.innerHTML = result.isError
                        ? '<p style="color:#d63638;">' + escHtml(text) + '</p>'
                        : '<pre class="askagento-mcp-pre-result">' + escHtml(text) + '</pre>';
                }
            },
            function (err) { setError(resultId, i18n.failed + ' ' + err); }
        );
    }

    // ── Chat test ────────────────────────────────────────────────────────────

    function runChat() {
        var resultId = 'askagento-mcp-chat-result';
        var msgEl    = document.getElementById('askagento-mcp-chat-message');
        var message  = msgEl ? msgEl.value.trim() : '';

        if (!message) {
            setError(resultId, 'Enter a message first.');
            return;
        }

        setLoading(resultId, 'Sending via MCP...');

        mcpCall(
            'tools/call',
            { name: 'chat_with_shop', arguments: { message: message } },
            function (result) {
                var text = ((result.content || [])[0] || {}).text || '';
                var el = document.getElementById(resultId);
                if (el) {
                    el.innerHTML = result.isError
                        ? '<p style="color:#d63638;">' + escHtml(text) + '</p>'
                        : '<pre class="askagento-mcp-pre-result">' + escHtml(text) + '</pre>';
                }
            },
            function (err) { setError(resultId, i18n.failed + ' ' + err); }
        );
    }

    // ── Copy helpers ────────────────────────────────────────────────────────

    function copyToClipboard(text, btn) {
        var origText = btn.textContent;
        navigator.clipboard.writeText(text)
            .then(function () {
                btn.textContent = i18n.copied || 'Copied!';
                setTimeout(function () { btn.textContent = origText; }, 1800);
            })
            .catch(function () {
                // fallback
                try {
                    var ta = document.createElement('textarea');
                    ta.value = text;
                    document.body.appendChild(ta);
                    ta.select();
                    document.execCommand('copy');
                    document.body.removeChild(ta);
                    btn.textContent = i18n.copied || 'Copied!';
                    setTimeout(function () { btn.textContent = origText; }, 1800);
                } catch (e) { /* silent */ }
            });
    }

    // ── Wire up once DOM is ready ───────────────────────────────────────────

    document.addEventListener('DOMContentLoaded', function () {

        // Probe button
        var probeBtn = document.getElementById('askagento-mcp-probe-btn');
        if (probeBtn) {
            probeBtn.addEventListener('click', runProbe);
        }

        // Search button
        var searchBtn = document.getElementById('askagento-mcp-search-btn');
        if (searchBtn) {
            searchBtn.addEventListener('click', runSearch);
        }

        // Trigger search on Enter in query field
        var queryEl = document.getElementById('askagento-mcp-search-query');
        if (queryEl) {
            queryEl.addEventListener('keydown', function (e) {
                if (e.key === 'Enter') { runSearch(); }
            });
        }

        // Chat button
        var chatBtn = document.getElementById('askagento-mcp-chat-btn');
        if (chatBtn) {
            chatBtn.addEventListener('click', runChat);
        }

        // Copy buttons for input fields
        document.querySelectorAll('.askagento-mcp-copy-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var targetId = btn.getAttribute('data-target');
                var targetEl = document.getElementById(targetId);
                if (targetEl) {
                    copyToClipboard(targetEl.value, btn);
                }
            });
        });

        var showLabel = i18n.show || 'Show';
        var hideLabel = i18n.hide || 'Hide';

        // Reveal / hide API key button
        document.querySelectorAll('.askagento-mcp-reveal-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var targetId = btn.getAttribute('data-target');
                var targetEl = document.getElementById(targetId);
                if (!targetEl) { return; }
                var btnShow = btn.getAttribute('data-label-show') || showLabel;
                var btnHide = btn.getAttribute('data-label-hide') || hideLabel;
                if (targetEl.type === 'password') {
                    targetEl.type = 'text';
                    btn.textContent = btnHide;
                } else {
                    targetEl.type = 'password';
                    btn.textContent = btnShow;
                }
            });
        });

        // Reveal / hide MCP config JSON snippets
        document.querySelectorAll('.askagento-mcp-snippet-reveal-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var targetId = btn.getAttribute('data-target');
                var wrap = document.getElementById(targetId);
                if (!wrap) { return; }
                var expanded = !wrap.hidden;
                wrap.hidden = expanded;
                btn.textContent = expanded ? showLabel : hideLabel;
                btn.setAttribute('aria-expanded', expanded ? 'false' : 'true');
            });
        });

        // Copy buttons for <pre> snippets
        document.querySelectorAll('.askagento-mcp-copy-pre-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var targetId = btn.getAttribute('data-target');
                var targetEl = document.getElementById(targetId);
                if (targetEl) {
                    copyToClipboard(targetEl.textContent, btn);
                }
            });
        });
    });

}());
