(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__commerce');
    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 metricName(key) {
        return label('commerceMetricLabels', key, strings.recordedMetric || 'Recorded metric');
    }
    function renderReport(result) {
        var metrics = result.metrics || {};
        var kpis = Object.keys(metrics).map(function (key) {
            var metric = metrics[key] || {};
            var value = metric.value_percent == null
                ? (strings.insufficientData || 'Insufficient data')
                : String(metric.value_percent) + '%';
            var explanation = '';
            if (metric.value_percent == null) {
                explanation = label('commerceInsufficientReasonLabels', metric.insufficient_reason,
                    strings.measurementNotReady || 'This metric is not ready yet.');
                if (metric.insufficient_reason === 'minimum_sample_size_not_met') {
                    explanation += ' ' + (strings.additionalConversationsShort ||
                        '{count} additional eligible conversation(s) required to reach {minimum}.')
                        .replace('{count}', String(Number(metric.additional_sample_required || 0)))
                        .replace('{minimum}', String(Number(metric.minimum_required_sample_size || 0)));
                }
            }
            return '<article><h3>' + escapeHtml(metricName(key)) + '</h3><strong>' + escapeHtml(value) +
                '</strong><small>n=' + escapeHtml(metric.sample_size || 0) + ' · ' +
                escapeHtml(metric.numerator || 0) + '/' + escapeHtml(metric.denominator || 0) +
                (metric.wilson_low_percent == null ? '' : ' · 95% CI ' + escapeHtml(metric.wilson_low_percent) +
                    '–' + escapeHtml(metric.wilson_high_percent)) + '</small>' +
                (explanation ? '<p>' + escapeHtml(explanation) + '</p>' : '') + '</article>';
        }).join('');
        var checks = (((result.readiness || {}).checks) || []).map(function (check) {
            return '<article class="is-' + escapeHtml(check.status || 'missing') + '"><h3>' +
                escapeHtml(label('commerceReadinessLabels', check.key, strings.recordedMetric || 'Recorded check')) + '</h3><strong>' +
                escapeHtml(check.coverage || 0) + '%</strong><p>' +
                escapeHtml(label('readinessStatusLabels', check.status, strings.measurementNotReady || 'Needs review')) +
                '</p><details><summary>' + escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
                escapeHtml(String(check.key || '') + ' · ' + String(check.status || '')) + '</code></details></article>';
        }).join('');
        var observations = (result.observations || []).slice(0, 50).map(function (row) {
            return '<article><h3>' + escapeHtml(row.product_external_id || '') + ' · ' +
                escapeHtml(label('commerceObservationLabels', row.recommended ? 'recommended' : 'mentioned')) + '</h3><p>' +
                escapeHtml(row.evidence_excerpt || '') + '</p>' +
                (row.confusion_detected ? '<p><strong>' + escapeHtml(strings.commerceConfusions || 'Potential confusion') +
                    '</strong></p>' : '') + '</article>';
        }).join('');
        var ucp = (result.readiness || {}).ucp || {};
        target.querySelector('.aysa-ai-visibility__commerce-report').innerHTML =
            '<div class="aysa-ai-visibility__commerce-kpis">' + kpis + '</div><h3>' +
            escapeHtml(strings.commerceReadiness || 'Commerce readiness checks') + '</h3><div class="aysa-ai-visibility__commerce-checks">' +
            checks + '</div><p><strong>UCP:</strong> ' +
            escapeHtml(label('ucpStatusLabels', ucp.status || 'not_verified', strings.measurementNotReady || 'Needs review')) +
            ' · ' + escapeHtml(strings.commerceCatalog || 'Catalog products') + ': ' + escapeHtml(result.catalog_count || 0) +
            '</p><details><summary>' + escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
            escapeHtml(ucp.status || 'not_verified') + '</code></details><h3>' +
            escapeHtml(strings.commerceObservations || 'Product observations') + '</h3><div class="aysa-ai-visibility__commerce-evidence">' +
            (observations || '<p>' + escapeHtml(strings.noEvidence || 'No evidence available.') + '</p>') + '</div>';
    }
    function shell(profile, baseline) {
        target.innerHTML = '<section class="aysa-ai-visibility__commerce-shell"><h2>' +
            escapeHtml(strings.commerceTitle || 'Product Visibility & Commerce Readiness') + '</h2><p>' +
            escapeHtml(strings.commerceHint || 'Analyze WooCommerce against existing evidence without side effects.') +
            '</p><div class="aysa-ai-visibility__commerce-actions"><button type="button" class="button button-primary" data-commerce-analyze ' +
            (baseline ? '' : 'disabled') + '>' + escapeHtml(strings.analyzeCommerce || 'Analyze current WooCommerce catalog') +
            '</button><span role="status">' + (baseline ? '' : escapeHtml(strings.commerceBaselineRequired || 'Complete a measurement first.')) +
            '</span></div><div class="aysa-ai-visibility__commerce-report"></div></section>';
        var button = target.querySelector('[data-commerce-analyze]');
        if (!button || !baseline) {
            return;
        }
        button.addEventListener('click', function () {
            var status = button.parentNode.querySelector('[role="status"]');
            button.disabled = true;
            status.textContent = strings.analyzingCommerce || 'Analyzing catalog…';
            request('commerce_analyze', {
                profile_id: Number(profile.id),
                baseline_run_batch_id: Number(baseline.id)
            }).then(function (result) {
                status.textContent = '';
                renderReport(result);
            }).catch(function (error) {
                status.textContent = error.message;
                button.disabled = false;
            });
        });
    }
    function load() {
        if (loaded) {
            return;
        }
        loaded = true;
        var finishLoading = viewState ? viewState.begin(target, 'commerce') : function () {};
        Promise.all([
            request('setup_read', {include_archived: false}),
            request('runs_list', {limit: 20})
        ]).then(function (results) {
            var profile = results[0].profile || null;
            var runs = results[1].runs || [];
            var baseline = runs.filter(function (run) {
                return run.status === 'aggregated' || run.status === 'completed';
            })[0] || null;
            if (!profile) {
                finishLoading();
                target.innerHTML = '<p>' + escapeHtml(strings.measurementNotReady || 'Setup is not ready.') + '</p>';
                return;
            }
            finishLoading();
            shell(profile, baseline);
        }).catch(function (error) {
            finishLoading();
            loaded = false;
            if (viewState) { viewState.fail(target, 'commerce', error.message, load); }
            else { target.innerHTML = '<p>' + escapeHtml(error.message) + '</p>'; }
        });
    }
    Array.prototype.forEach.call(root.querySelectorAll('[data-view="commerce"]'), function (button) {
        button.addEventListener('click', load);
    });
}());
