(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__correlation');
    var strings = config.strings || {};
    var loaded = false;
    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 render(result) {
        var cards = Object.keys(result.metrics || {}).map(function (key) {
            var metric = result.metrics[key] || {};
            var current = metric.current || null;
            var value = current ? String(current.value) + (metric.unit === 'percent' ? '%' : '') : (strings.insufficientData || 'Insufficient data');
            return '<article><h3>' +
                escapeHtml(label('correlationMetricLabels', key, strings.recordedMetric || 'Recorded metric')) +
                '</h3><strong>' + escapeHtml(value) + '</strong><p>' +
                escapeHtml(label('correlationDirectionLabels', metric.direction || 'unknown')) + '</p><small>' +
                escapeHtml(label('correlationSourceLabels', key, strings.recordedSource || 'Recorded source')) + ' · ' +
                escapeHtml(label('correlationStatusLabels', metric.data_status || 'not_available')) + ' · ' +
                escapeHtml(label('correlationScopeLabels', metric.attribution_scope || 'source_metric_only')) +
                '</small><details><summary>' + escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
                escapeHtml([key, metric.source, metric.direction, metric.data_status, metric.attribution_scope].filter(Boolean).join(' · ')) +
                '</code></details></article>';
        }).join('');
        target.innerHTML = '<section class="aysa-ai-visibility__correlation-shell"><h2>' +
            escapeHtml(strings.correlationTitle || 'Source correlation') + '</h2><p>' +
            escapeHtml(strings.correlationHint || 'Compare saved observations without blending sources.') +
            '</p><div class="aysa-ai-visibility__correlation-grid">' + cards + '</div><p class="aysa-ai-visibility__correlation-caveat"><strong>' +
            escapeHtml(strings.correlationCaveat || 'Co-movement is not causal attribution.') + '</strong></p></section>';
    }
    function load() {
        if (loaded) { return; }
        loaded = true;
        var finishLoading = viewState ? viewState.begin(target, 'correlation') : function () {};
        request('setup_read', {include_archived: false}).then(function (setup) {
            if (!setup.profile) { throw new Error(strings.measurementNotReady || 'Setup is not ready.'); }
            return request('correlation_read', {profile_id: Number(setup.profile.id)});
        }).then(function (result) {
            finishLoading();
            render(result);
        }).catch(function (error) {
            finishLoading();
            loaded = false;
            if (viewState) { viewState.fail(target, 'correlation', error.message, load); }
            else { target.innerHTML = '<p>' + escapeHtml(error.message) + '</p>'; }
        });
    }
    Array.prototype.forEach.call(root.querySelectorAll('[data-view="correlation"]'), function (button) { button.addEventListener('click', load); });
}());
