(function () {
    'use strict';
    var root = document.getElementById('aysa-ai-visibility-app');
    var config = window.aysaAiVisibility || {};
    if (!root || !config.ajaxUrl) { return; }
    var target = root.querySelector('.aysa-ai-visibility__knowledge-base');
    var strings = config.strings || {};
    var loaded = false;
    var profileId = 0;
    var viewState = window.aysaAiVisibilityViewState;
    function escapeHtml(value) { var node = document.createElement('span'); node.textContent = String(value == null ? '' : value); return node.innerHTML; }
    function label(group, key, fallback) {
        var labels = strings[group] && typeof strings[group] === 'object' ? strings[group] : {};
        return labels[key] || fallback || strings.recordedMetric || 'Recorded value';
    }
    function request(operation, payload) {
        var controller = new AbortController();
        var timeout = window.setTimeout(function () { controller.abort(); }, Number(config.requestTimeoutMs || 15000));
        var body = new URLSearchParams({action: 'aysa_ai_visibility_request', nonce: config.nonce, operation: operation, payload: JSON.stringify(payload || {})});
        return fetch(config.ajaxUrl, {method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, body: body.toString(), signal: controller.signal})
            .then(function (response) { return response.json(); })
            .then(function (response) { if (!response.success || !response.data) { throw new Error((response.data && response.data.message) || strings.failed || 'Request failed.'); } return response.data; })
            .finally(function () { window.clearTimeout(timeout); });
    }
    function renderSources(result) {
        var sources = result.sources || [];
        var rows = sources.map(function (source) {
            return '<article><div><h3>' + escapeHtml(source.title || strings.recordedSource || 'Recorded source') + '</h3><p>' +
                escapeHtml(label('knowledgeSourceTypeLabels', source.source_type, strings.recordedMetric || 'Recorded source')) +
                ' · v' + escapeHtml(source.version || 1) + ' · ' +
                escapeHtml(label('knowledgeVerificationLabels', source.verification_status || 'proposed')) +
                '</p><small>' + escapeHtml(source.evidence_excerpt || '') +
                '</small><details><summary>' + escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
                escapeHtml([source.external_key, source.source_type, source.verification_status].filter(Boolean).join(' · ')) +
                '</code></details></div><button type="button" class="button" data-kb-archive="' + escapeHtml(source.id) + '">' +
                escapeHtml(strings.archive || 'Archive') + '</button></article>';
        }).join('');
        target.querySelector('.aysa-ai-visibility__knowledge-list').innerHTML = rows || '<p>' + escapeHtml(strings.knowledgeEmpty || 'No active sources yet.') + '</p>';
        Array.prototype.forEach.call(target.querySelectorAll('[data-kb-archive]'), function (button) {
            button.addEventListener('click', function () {
                button.disabled = true;
                request('knowledge_source_archive', {source_id: Number(button.getAttribute('data-kb-archive'))})
                    .then(loadSources).catch(function (error) { button.disabled = false; target.querySelector('[role="status"]').textContent = error.message; });
            });
        });
    }
    function loadSources() {
        return request('knowledge_sources_list', {profile_id: profileId, include_archived: false}).then(renderSources);
    }
    function shell() {
        target.innerHTML = '<section class="aysa-ai-visibility__knowledge-shell"><h2>' + escapeHtml(strings.knowledgeBaseTitle || 'Knowledge Base') +
            '</h2><p>' + escapeHtml(strings.knowledgeBaseHint || 'Versioned encrypted first-party sources.') +
            '</p><div class="aysa-ai-visibility__knowledge-actions"><button type="button" class="button button-primary" data-kb-sync>' +
            escapeHtml(strings.syncWordPressKnowledge || 'Sync published WordPress content') + '</button><span role="status"></span></div>' +
            '<div class="aysa-ai-visibility__knowledge-list"></div></section>';
        var button = target.querySelector('[data-kb-sync]');
        button.addEventListener('click', function () {
            var status = target.querySelector('[role="status"]');
            button.disabled = true;
            status.textContent = strings.syncingKnowledge || 'Creating encrypted snapshot…';
            request('knowledge_wordpress_sync', {profile_id: profileId}).then(function () {
                status.textContent = strings.knowledgeReviewRequired || 'Official source — factual review required';
                return loadSources();
            }).catch(function (error) { status.textContent = error.message; }).finally(function () { button.disabled = false; });
        });
        return loadSources();
    }
    function load() {
        if (loaded) { return; }
        loaded = true;
        var finishLoading = viewState ? viewState.begin(target, 'knowledge_base') : function () {};
        request('setup_read', {include_archived: false}).then(function (setup) {
            if (!setup.profile) { throw new Error(strings.measurementNotReady || 'Setup is not ready.'); }
            profileId = Number(setup.profile.id);
            return shell();
        }).then(function () {
            finishLoading();
        }).catch(function (error) {
            finishLoading();
            loaded = false;
            if (viewState) { viewState.fail(target, 'knowledge_base', error.message, load); }
            else { target.innerHTML = '<p>' + escapeHtml(error.message) + '</p>'; }
        });
    }
    Array.prototype.forEach.call(root.querySelectorAll('[data-view="knowledge-base"]'), function (button) { button.addEventListener('click', load); });
}());
