(function () {
    'use strict';

    var GROUPS = ['Find', 'Understand', 'Access'];
    var STATUS_LABELS = {
        pass: 'Looks good',
        warning: 'Needs attention',
        error: 'Action required'
    };

    function safeString(value) {
        return typeof value === 'string' ? value : '';
    }

    function normalizeResult(value) {
        var result = value && typeof value === 'object' ? value : {};
        var findings = Array.isArray(result.findings) ? result.findings.filter(function (finding) {
            return finding && GROUPS.indexOf(finding.category) !== -1 && Object.prototype.hasOwnProperty.call(STATUS_LABELS, finding.status);
        }) : [];
        return {
            normalized_url: safeString(result.normalized_url),
            checked_at: safeString(result.checked_at),
            cached: result.cached === true,
            counts: result.counts && typeof result.counts === 'object' ? result.counts : {},
            findings: findings,
            sampled: Array.isArray(result.sampled) ? result.sampled.map(safeString).filter(Boolean) : []
        };
    }

    function appendTextElement(parent, tag, className, value) {
        var element = document.createElement(tag);
        if (className) {
            element.className = className;
        }
        element.textContent = safeString(value);
        parent.appendChild(element);
        return element;
    }

    function renderCounts(container, counts) {
        container.replaceChildren();
        ['pass', 'warning', 'error'].forEach(function (status) {
            var count = Number(counts[status] || 0);
            var item = document.createElement('span');
            item.className = 'aysa-agentmarkup__count is-' + status;
            appendTextElement(item, 'strong', '', String(count));
            appendTextElement(item, 'span', '', STATUS_LABELS[status]);
            container.appendChild(item);
        });
    }

    function renderFinding(finding) {
        var article = document.createElement('article');
        article.className = 'aysa-agentmarkup__finding is-' + finding.status;
        var heading = document.createElement('div');
        heading.className = 'aysa-agentmarkup__finding-heading';
        appendTextElement(heading, 'span', 'aysa-agentmarkup__badge', STATUS_LABELS[finding.status]);
        appendTextElement(heading, 'h4', '', safeString(finding.title));
        article.appendChild(heading);
        appendTextElement(article, 'p', 'aysa-agentmarkup__evidence', safeString(finding.evidence));
        if (safeString(finding.action)) {
            var action = document.createElement('p');
            action.className = 'aysa-agentmarkup__action';
            appendTextElement(action, 'strong', '', 'Next action: ');
            action.appendChild(document.createTextNode(safeString(finding.action)));
            article.appendChild(action);
        }
        return article;
    }

    function renderGroups(container, findings) {
        container.replaceChildren();
        GROUPS.forEach(function (groupName) {
            var section = document.createElement('section');
            section.className = 'aysa-agentmarkup__group';
            appendTextElement(section, 'h3', '', groupName);
            var items = findings.filter(function (finding) { return finding.category === groupName; });
            items.forEach(function (finding) { section.appendChild(renderFinding(finding)); });
            container.appendChild(section);
        });
    }

    function messageFromResponse(response) {
        if (response && response.data) {
            if (typeof response.data === 'string') {
                return response.data;
            }
            if (typeof response.data.message === 'string') {
                return response.data.message;
            }
        }
        return 'The AgentMarkup check could not be completed. Please retry.';
    }

    function init() {
        var config = window.aysaAgentMarkupChecker || {};
        var form = document.getElementById('aysa-agentmarkup-form');
        if (!form) {
            return;
        }
        var input = document.getElementById('aysa-agentmarkup-url');
        var button = document.getElementById('aysa-agentmarkup-submit');
        var status = document.getElementById('aysa-agentmarkup-status');
        var results = document.getElementById('aysa-agentmarkup-results');
        var origin = document.getElementById('aysa-agentmarkup-origin');
        var counts = document.getElementById('aysa-agentmarkup-counts');
        var groups = document.getElementById('aysa-agentmarkup-groups');
        var sampledList = document.getElementById('aysa-agentmarkup-sampled-list');

        form.addEventListener('submit', function (event) {
            event.preventDefault();
            if (!input || !safeString(input.value).trim()) {
                status.className = 'aysa-agentmarkup__status is-error';
                status.textContent = 'The verified website URL is unavailable.';
                input.focus();
                return;
            }
            if (!safeString(config.ajaxUrl) || !safeString(config.nonce)) {
                status.className = 'aysa-agentmarkup__status is-error';
                status.textContent = 'AgentMarkup configuration is unavailable. Reload this page and retry.';
                return;
            }

            button.disabled = true;
            form.setAttribute('aria-busy', 'true');
            status.className = 'aysa-agentmarkup__status is-loading';
            status.textContent = 'Checking the bounded public evidence…';
            results.hidden = true;

            var body = new URLSearchParams();
            body.set('action', 'aysa_agentmarkup_check');
            body.set('nonce', config.nonce);

            window.fetch(config.ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                body: body.toString()
            }).then(function (response) {
                return response.json().then(function (json) {
                    if (!response.ok || !json || json.success !== true) {
                        throw new Error(messageFromResponse(json));
                    }
                    return normalizeResult(json.data);
                });
            }).then(function (result) {
                origin.textContent = result.normalized_url;
                renderCounts(counts, result.counts);
                renderGroups(groups, result.findings);
                sampledList.replaceChildren();
                result.sampled.forEach(function (url) {
                    appendTextElement(sampledList, 'li', '', url);
                });
                results.hidden = false;
                status.className = 'aysa-agentmarkup__status is-success';
                status.textContent = 'Check completed' + (result.cached ? ' from the bounded 15-minute cache.' : '.') + (result.checked_at ? ' Evidence time: ' + result.checked_at : '');
                results.focus({preventScroll: true});
            }).catch(function (error) {
                status.className = 'aysa-agentmarkup__status is-error';
                status.textContent = safeString(error && error.message) || 'The AgentMarkup check could not be completed. Please retry.';
            }).finally(function () {
                button.disabled = false;
                form.setAttribute('aria-busy', 'false');
            });
        });
    }

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = {normalizeResult: normalizeResult, safeString: safeString, groups: GROUPS.slice()};
    }
    if (typeof document !== 'undefined') {
        document.addEventListener('DOMContentLoaded', init);
    }
}());
