(function () {
    'use strict';
    var root = document.getElementById('aysa-ai-visibility-app');
    if (!root || !window.aysaAiVisibility) {
        return;
    }
    var state = root.querySelector('.aysa-ai-visibility__state');
    var strings = aysaAiVisibility.strings || {};
    var latestRunId = 0;
    var availableRuns = [];
    var evidencePage = 1;
    var setupData = null;
    var setupSaveTimer = 0;
    var setupIncludeArchived = false;
    var actionPlanBundle = null;
    var actionPlanApproval = null;
    var engineState = {};
    var measurementRunReference = '';
    var measurementCancelReference = '';
    var measurementCancelRunId = 0;
    var measurementRetryReference = '';
    var measurementRetryRunId = 0;
    var measurementReprocessReference = '';
    var measurementReprocessRunId = 0;
    var schedulingEnabled = false;
    var reprocessExtractionEnabled = false;

    function languageBase(language) {
        return String(language || 'ro').trim().toLowerCase().replace(/_/g, '-').split('-')[0] || 'ro';
    }
    function languagePack(packs, language) {
        packs = packs && typeof packs === 'object' ? packs : {};
        var normalized = String(language || 'ro').trim().replace(/_/g, '-');
        return packs[normalized] || packs[languageBase(normalized)] || packs.en || {};
    }
    function applyInterfaceLanguage(language) {
        var normalized = String(language || 'ro').trim().replace(/_/g, '-') || 'ro';
        var nextStrings = languagePack(aysaAiVisibility.stringsByLanguage, normalized);
        var shell = languagePack(aysaAiVisibility.shellByLanguage, normalized);
        if (nextStrings && Object.keys(nextStrings).length) {
            var selectedStrings = Object.assign({}, nextStrings);
            Object.keys(strings).forEach(function (key) { delete strings[key]; });
            Object.keys(selectedStrings).forEach(function (key) { strings[key] = selectedStrings[key]; });
            aysaAiVisibility.strings = strings;
        }
        root.setAttribute('lang', normalized);
        root.setAttribute('dir', ['ar', 'he', 'yi'].indexOf(languageBase(normalized)) !== -1 ? 'rtl' : 'ltr');
        Array.prototype.forEach.call(root.querySelectorAll('[data-aiv-i18n]'), function (node) {
            var key = node.getAttribute('data-aiv-i18n');
            if (shell[key]) {
                node.textContent = shell[key];
            }
        });
        Array.prototype.forEach.call(root.querySelectorAll('[data-aiv-i18n-aria]'), function (node) {
            var key = node.getAttribute('data-aiv-i18n-aria');
            if (shell[key]) {
                node.setAttribute('aria-label', shell[key]);
            }
        });
        root.dispatchEvent(new CustomEvent('aysa:aiv:language-changed', {
            detail: {language: normalized}
        }));
    }

    function announceProductState(name, detail) {
        root.dispatchEvent(new CustomEvent(name, {detail: detail || {}}));
    }

    function escapeHtml(value) {
        var node = document.createElement('span');
        node.textContent = String(value == null ? '' : value);
        return node.innerHTML;
    }
    function formatInterfaceDate(value) {
        if (!value) { return strings.notRecorded || 'Not recorded'; }
        var normalized = String(value).trim().replace(' ', 'T');
        if (!/(?:Z|[+-]\d{2}:\d{2})$/i.test(normalized)) { normalized += 'Z'; }
        var parsed = new Date(normalized);
        if (isNaN(parsed.getTime())) { return String(value); }
        return new Intl.DateTimeFormat(languageBase(root.getAttribute('lang')) === 'ro' ? 'ro-RO' : 'en-GB', {
            dateStyle: 'medium', timeStyle: 'short'
        }).format(parsed);
    }
    function safeUrl(value) {
        try {
            var parsed = new URL(String(value || ''));
            return (parsed.protocol === 'https:' || parsed.protocol === 'http:')
                ? parsed.href.replace(/"/g, '&quot;').replace(/'/g, '&#039;')
                : '#';
        } catch (error) {
            return '#';
        }
    }
    function escapeAttr(value) {
        return escapeHtml(value).replace(/"/g, '&quot;').replace(/'/g, '&#039;');
    }
    function mappedLabel(group, key, fallback) {
        var map = strings[group] && typeof strings[group] === 'object' ? strings[group] : {};
        return map[key] || fallback || key;
    }
    function engineLabel(key, fallback) {
        var labels = strings.engineLabels && typeof strings.engineLabels === 'object' ? strings.engineLabels : {};
        var normalizedKey = String(key || '').replace(/^dataforseo_/, '');
        return labels[key] || labels[normalizedKey] || labels[fallback] || strings.recordedEngine || 'Recorded answer engine';
    }
    function countedLabel(count, singular, plural) {
        return Number(count) === 1 ? singular : plural;
    }
    function humanError(error) {
        var message = String(error && error.message ? error.message : error || '');
        var labels = strings.errorLabels && typeof strings.errorLabels === 'object' ? strings.errorLabels : {};
        if (labels[message]) {
            return labels[message];
        }
        return /^ai_visibility_[a-z0-9_]+$/i.test(message)
            ? (strings.failed || 'The request could not be completed.')
            : message;
    }
    function normalizeEngines(value) {
        var source = value && typeof value === 'object' ? value : {};
        return Object.keys(source).reduce(function (normalized, sourceKey) {
            var engine = source[sourceKey] && typeof source[sourceKey] === 'object' ? source[sourceKey] : {};
            var engineKey = String(engine.key || sourceKey);
            normalized[engineKey] = engine;
            return normalized;
        }, {});
    }
    function request(operation, payload) {
        var controller = new AbortController();
        var timeout = window.setTimeout(function () { controller.abort(); }, Number(aysaAiVisibility.requestTimeoutMs || 15000));
        var body = new URLSearchParams({
            action: operation === 'status' ? 'aysa_ai_visibility_status' : 'aysa_ai_visibility_request',
            nonce: aysaAiVisibility.nonce
        });
        if (operation !== 'status') {
            body.set('operation', operation);
            body.set('payload', JSON.stringify(payload || {}));
        }
        return fetch(aysaAiVisibility.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 renderError(message, retry) {
        state.hidden = false;
        state.setAttribute('aria-busy', 'false');
        state.innerHTML = '<h2>' + escapeHtml(strings.unavailableTitle || 'AI Visibility unavailable') + '</h2><p>' +
            escapeHtml(message) + '</p><button type="button" class="button aysa-ai-visibility__retry">' +
            escapeHtml(strings.retry || 'Retry') + '</button>';
        state.querySelector('.aysa-ai-visibility__retry').addEventListener('click', retry || load);
    }
    function beginViewState(target, moduleKey) {
        var moduleLabel = mappedLabel('moduleLabels', moduleKey, moduleKey);
        var token = String(Date.now()) + ':' + String(Math.random());
        target.setAttribute('data-aiv-load-token', token);
        target.setAttribute('aria-busy', 'true');
        target.innerHTML = '<section class="aysa-ai-visibility__view-state" role="status"><h2>' +
            escapeHtml((strings.viewLoading || 'Loading {module}…').replace('{module}', moduleLabel)) +
            '</h2><p>' + escapeHtml(strings.checkingCopy || 'No providers are run and no credits are used.') + '</p></section>';
        var slowTimer = window.setTimeout(function () {
            if (target.getAttribute('data-aiv-load-token') !== token) { return; }
            var message = target.querySelector('.aysa-ai-visibility__view-state p');
            if (message) {
                message.textContent = (strings.viewSlow || '{module} is taking longer than expected.')
                    .replace('{module}', moduleLabel);
            }
        }, 4500);
        return function () {
            window.clearTimeout(slowTimer);
            if (target.getAttribute('data-aiv-load-token') === token) {
                target.removeAttribute('data-aiv-load-token');
                target.setAttribute('aria-busy', 'false');
            }
        };
    }
    function renderViewFailure(target, moduleKey, error, retry) {
        var moduleLabel = mappedLabel('moduleLabels', moduleKey, moduleKey);
        target.setAttribute('aria-busy', 'false');
        target.innerHTML = '<section class="aysa-ai-visibility__view-state is-error" role="alert"><h2>' +
            escapeHtml((strings.viewFailed || '{module} could not be loaded.').replace('{module}', moduleLabel)) +
            '</h2><p>' + escapeHtml(error || strings.failed || 'Request failed.') + '</p><button type="button" class="button">' +
            escapeHtml(strings.retry || 'Retry') + '</button></section>';
        target.querySelector('button').addEventListener('click', retry);
    }
    window.aysaAiVisibilityViewState = {
        begin: beginViewState,
        fail: renderViewFailure
    };
    function metricLabel(key) {
        return ({
            visibility: strings.metricVisibility,
            ai_visibility: strings.metricVisibility,
            recommendation_rate: strings.metricRecommendationRate,
            recommendation_coverage: strings.metricRecommendationCoverage,
            ai_recommendation_rate: strings.metricRecommendationRate,
            ai_recommendation_coverage: strings.metricRecommendationCoverage,
            ai_share_of_voice: strings.metricShareOfVoice,
            share_of_voice: strings.metricShareOfVoice,
            first_party_citation_rate: strings.metricCitationRate,
            fact_accuracy: strings.metricFactAccuracy
        })[key] || strings.recordedMetric || 'Recorded metric';
    }
    function entityTypeLabel(type) {
        return ({
            alias: strings.entityAliases,
            persona: strings.entityPersonas,
            topic: strings.entityTopics,
            scenario: strings.entityScenarios,
            competitor: strings.entityCompetitors,
            claim: strings.entityClaims
        })[type] || strings.recordedItem || 'Recorded item';
    }
    function insightLabel(insight) {
        return mappedLabel('insightLabels', String(insight.insight_key || ''), strings.recordedRecommendation || 'Recorded recommendation');
    }
    function insightExplanation(insight) {
        return mappedLabel('insightExplanations', String(insight.insight_key || ''), strings.recordedRecommendation || 'Recorded recommendation');
    }
    function laneLabel(lane) {
        return mappedLabel('laneLabels', String(lane || ''), strings.recordedWorkflow || 'Canonical workflow');
    }
    function priorityLabel(priority) {
        return mappedLabel('priorityLabels', String(priority || 'low'), priority || 'low');
    }
    function renderOverview(data, runs) {
        var panel = root.querySelector('[data-view-panel="overview"]');
        var run = panel.querySelector('.aysa-ai-visibility__run');
        var metrics = panel.querySelector('.aysa-ai-visibility__metrics');
        var latest = data.latest_run || null;
        latestRunId = latest ? Number(latest.id || 0) : 0;
        if (!latest) {
            run.innerHTML = '<h2>' + escapeHtml(strings.noRuns || 'No measurement yet.') + '</h2>';
            metrics.innerHTML = '';
            announceProductState('aysa:aiv:overview-rendered', {
                latest_run: null,
                product_context: data.product_context || null,
                next_actions: data.next_actions || [],
                next_actions_context: data.next_actions_context || 'unavailable',
                runs: runs || availableRuns
            });
            return;
        }
        var title = data.state === 'complete'
            ? strings.runComplete
            : (data.state === 'partial'
                ? strings.runPartial
                : (data.state === 'failed'
                    ? strings.runFailed
                    : (data.state === 'cancelled' ? strings.measurementCancelled : strings.runInProgress)));
        var cancelAction = data.state === 'running'
            ? '<button type="button" class="button" data-cancel-measurement>' +
                escapeHtml(strings.cancelMeasurement || 'Cancel measurement') + '</button>'
            : '';
        var retryAction = data.state === 'failed' || data.state === 'partial'
            ? '<button type="button" class="button" data-retry-measurement>' +
                escapeHtml(strings.reviewRetry || 'Review retryable work') + '</button>'
            : '';
        var reprocessAction = data.state === 'complete' && reprocessExtractionEnabled
            ? '<button type="button" class="button" data-reprocess-extraction>' +
                escapeHtml(strings.reviewReprocess || 'Review extraction reprocess') + '</button>'
            : '';
        run.innerHTML = '<h2>' + escapeHtml(title || data.state) + '</h2><p>' +
            escapeHtml(String(data.coverage.completed || 0) + ' / ' + String(data.coverage.planned || 0) + ' ' +
                countedLabel(data.coverage.planned, strings.conversationSingular || 'conversation', strings.conversations || 'conversations')) +
            '</p><details class="aysa-ai-visibility__evidence-technical"><summary>' +
            escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
            escapeHtml(latest.methodology_version || '') + '</code></details><div class="aysa-ai-visibility__report-actions"><button type="button" class="button" data-export-csv>' +
            escapeHtml(strings.exportCsv || 'Export CSV') + '</button><button type="button" class="button" data-print-report>' +
            escapeHtml(strings.printReport || 'Print / Save PDF') + '</button>' + cancelAction + retryAction +
            reprocessAction + '</div>';
        var renderMetric = function (metric) {
            var sufficient = metric.data_status === 'sufficient_data' && metric.value_percent !== null;
            var value = sufficient ? Number(metric.value_percent).toFixed(1) + '%' : (strings.insufficientData || 'Insufficient data');
            var interval = sufficient && metric.wilson_low_percent !== null
                ? (strings.confidenceInterval || '95% CI') + ' ' + Number(metric.wilson_low_percent).toFixed(1) + '–' +
                    Number(metric.wilson_high_percent).toFixed(1) + '%'
                : '';
            var explanation = '';
            if (!sufficient && Number(metric.additional_sample_required || 0) > 0) {
                explanation = (strings.moreEligibleNeeded || '{count} more eligible conversation(s) needed (minimum {minimum}).')
                    .replace('{count}', String(Number(metric.additional_sample_required || 0)))
                    .replace('{minimum}', String(Number(metric.minimum_sample_size || 0)));
            } else if (!sufficient) {
                explanation = strings.metricRequirementMissing || 'An additional metric requirement is not met.';
            }
            return '<article class="aysa-ai-visibility__metric"><h3>' + escapeHtml(metricLabel(metric.metric_key)) +
                '</h3><div class="aysa-ai-visibility__metric-value">' + escapeHtml(value) + '</div><small>' +
                escapeHtml('n=' + metric.sample_size + ' · ' + metric.numerator + '/' + metric.denominator) +
                '</small><small>' + escapeHtml(interval || explanation) + '</small></article>';
        };
        var allMetrics = data.metrics || [];
        var primaryKeys = ['ai_recommendation_coverage', 'ai_visibility', 'first_party_citation_rate', 'fact_accuracy'];
        var primaryMetrics = primaryKeys.map(function (key) {
            return allMetrics.filter(function (metric) { return metric.metric_key === key; })[0];
        }).filter(Boolean);
        var additionalMetrics = allMetrics.filter(function (metric) {
            return primaryKeys.indexOf(metric.metric_key) === -1;
        });
        metrics.innerHTML = '<div class="aysa-ai-visibility__primary-metrics">' + primaryMetrics.map(renderMetric).join('') + '</div>' +
            (additionalMetrics.length ? '<details class="aysa-ai-visibility__additional-metrics"><summary>' +
                escapeHtml(strings.additionalMetrics || 'Additional metrics') + '</summary><div>' +
                additionalMetrics.map(renderMetric).join('') + '</div></details>' : '');
        bindReportActions(run);
        var cancel = run.querySelector('[data-cancel-measurement]');
        if (cancel) {
            cancel.addEventListener('click', function () {
                if (!window.confirm(strings.cancelMeasurementConfirm ||
                    'Cancel this measurement? New provider work will stop. Completed work remains recorded.')) {
                    return;
                }
                if (!measurementCancelReference || measurementCancelRunId !== Number(latest.id || 0)) {
                    measurementCancelReference = 'cancel:' + String(latest.id || 0) + ':' + String(Date.now());
                    measurementCancelRunId = Number(latest.id || 0);
                }
                cancel.disabled = true;
                cancel.textContent = strings.cancellingMeasurement || 'Cancelling measurement…';
                request('run_cancel', {
                    run_batch_id: Number(latest.id || 0),
                    request_reference: measurementCancelReference,
                    confirm_cancel: true,
                    reason: 'user_requested'
                }).then(function () {
                    load();
                }).catch(function (error) {
                    cancel.disabled = false;
                    cancel.textContent = strings.cancelMeasurement || 'Cancel measurement';
                    window.alert(humanError(error));
                });
            });
        }
        var retry = run.querySelector('[data-retry-measurement]');
        if (retry) {
            retry.addEventListener('click', function () {
                retry.disabled = true;
                retry.textContent = strings.checkingRetry || 'Checking retryable work…';
                request('run_retry_prepare', {run_batch_id: Number(latest.id || 0)}).then(function (prepared) {
                    var tasks = Array.isArray(prepared.retryable_tasks) ? prepared.retryable_tasks : [];
                    if (!tasks.length) {
                        window.alert(strings.noRetryableWork || 'No safely retryable failed work is available.');
                        return null;
                    }
                    var message = (strings.retryMeasurementConfirm ||
                        'Queue one additional attempt for {count} retryable task(s)? Completed provider responses will be reused. New usage is possible only if a new provider result is produced.')
                        .replace('{count}', String(tasks.length));
                    if (!window.confirm(message)) {
                        return null;
                    }
                    if (!measurementRetryReference || measurementRetryRunId !== Number(latest.id || 0)) {
                        measurementRetryReference = 'retry:' + String(latest.id || 0) + ':' + String(Date.now());
                        measurementRetryRunId = Number(latest.id || 0);
                    }
                    return request('run_retry', {
                        run_batch_id: Number(latest.id || 0),
                        task_ids: tasks.map(function (task) { return Number(task.task_id || 0); }).filter(Boolean),
                        request_reference: measurementRetryReference,
                        confirm_retry: true
                    });
                }).then(function (result) {
                    if (result) {
                        load();
                    }
                }).catch(function (error) {
                    window.alert(humanError(error));
                }).finally(function () {
                    retry.disabled = false;
                    retry.textContent = strings.reviewRetry || 'Review retryable work';
                });
            });
        }
        var reprocess = run.querySelector('[data-reprocess-extraction]');
        if (reprocess) {
            reprocess.addEventListener('click', function () {
                reprocess.disabled = true;
                reprocess.textContent = strings.checkingReprocess || 'Checking source evidence…';
                request('run_reprocess_prepare', {run_batch_id: Number(latest.id || 0)}).then(function (prepared) {
                    var message = (strings.reprocessConfirm ||
                        'Create {count} review-only extraction candidate(s), from {source} to {target}? The answer provider and wallet will not be called, and current metrics will not change.')
                        .replace('{count}', String(prepared.candidate_count || 0))
                        .replace('{source}', String(prepared.source_extraction_version || ''))
                        .replace('{target}', String(prepared.target_extraction_version || ''));
                    if (!window.confirm(message)) {
                        return null;
                    }
                    if (!measurementReprocessReference || measurementReprocessRunId !== Number(latest.id || 0)) {
                        measurementReprocessReference = 'reprocess:' + String(latest.id || 0) + ':' + String(Date.now());
                        measurementReprocessRunId = Number(latest.id || 0);
                    }
                    return request('run_reprocess_start', {
                        run_batch_id: Number(latest.id || 0),
                        request_reference: measurementReprocessReference,
                        confirm_reprocess: true
                    });
                }).then(function (result) {
                    if (result) {
                        window.alert(strings.reprocessQueued ||
                            'Versioned extraction candidates were queued for review. Current metrics remain unchanged.');
                    }
                }).catch(function (error) {
                    window.alert(humanError(error));
                }).finally(function () {
                    reprocess.disabled = false;
                    reprocess.textContent = strings.reviewReprocess || 'Review extraction reprocess';
                });
            });
        }
        announceProductState('aysa:aiv:overview-rendered', {
            latest_run: latest,
            coverage: data.coverage || {},
            product_context: data.product_context || null,
            next_actions: data.next_actions || [],
            next_actions_context: data.next_actions_context || 'unavailable',
            runs: runs || availableRuns
        });
    }
    function csvCell(value) {
        var text = typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value == null ? '' : value);
        return '"' + text.replace(/"/g, '""') + '"';
    }
    function downloadExportCsv() {
        if (!latestRunId) {
            return;
        }
        request('export_read', {run_batch_id: latestRunId, format: 'csv'}).then(function (data) {
            var rows = [['section', 'type', 'label', 'value', 'numerator', 'denominator', 'sample_size', 'evidence', 'url']];
            (data.metrics || []).forEach(function (metric) {
                rows.push([
                    'metrics', metric.metric_key, metricLabel(metric.metric_key), metric.value_percent,
                    metric.numerator, metric.denominator, metric.sample_size, '', ''
                ]);
            });
            (data.conversations || []).forEach(function (conversation) {
                rows.push([
                    'conversations', conversation.test_type, conversation.engine, '', '', '', '',
                    conversation.response_text || '', ''
                ]);
            });
            var signals = data.signals || {};
            Object.keys(signals).forEach(function (type) {
                (signals[type] || []).forEach(function (signal) {
                    rows.push([
                        'signals', type,
                        signal.claim_text || signal.matched_text || signal.query_text || signal.title || signal.domain || '',
                        signal.classification || signal.sentiment || signal.grounding_status || '',
                        '', '', '', signal.evidence_excerpt || '', signal.canonical_url || ''
                    ]);
                });
            });
            rows.push(['methodology', '', '', '', '', '', '', data.methodology_note || '', '']);
            var csv = '\ufeff' + rows.map(function (row) { return row.map(csvCell).join(','); }).join('\r\n');
            var blob = new Blob([csv], {type: 'text/csv;charset=utf-8'});
            var url = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = url;
            link.download = 'aysa-ai-visibility-run-' + String(latestRunId) + '.csv';
            document.body.appendChild(link);
            link.click();
            link.remove();
            URL.revokeObjectURL(url);
        }).catch(function (error) {
            renderError(humanError(error), downloadExportCsv);
        });
    }
    function bindReportActions(container) {
        var csv = container.querySelector('[data-export-csv]');
        var print = container.querySelector('[data-print-report]');
        if (csv) {
            csv.addEventListener('click', downloadExportCsv);
        }
        if (print) {
            print.addEventListener('click', function () { window.print(); });
        }
    }
    function renderEngines(data) {
        var section = root.querySelector('.aysa-ai-visibility__engines');
        var grid = section.querySelector('.aysa-ai-visibility__grid');
        var engines = normalizeEngines(data.engines);
        engineState = engines;
        grid.innerHTML = Object.keys(engines).map(function (key) {
            var engine = engines[key] || {};
            return '<article><h3>' + escapeHtml(engineLabel(key, engine.engine)) + '</h3><p><strong>' +
                escapeHtml(mappedLabel('availabilityLabels', engine.availability || 'not_configured', engine.availability || 'not_configured')) + '</strong></p><p>' +
                escapeHtml(mappedLabel('channelLabels', engine.channel || '', engine.channel || '')) + '</p><details><summary>' +
                escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
                escapeHtml(key) + '</code></details></article>';
        }).join('');
        section.hidden = Object.keys(engines).length === 0;
    }
    function renderMeasurement(setup, capability) {
        var target = root.querySelector('.aysa-ai-visibility__measurement');
        schedulingEnabled = Boolean(capability && capability.flags && capability.flags.scheduling_enabled);
        var profile = setup.profile || {};
        var scenarios = (setup.entities && setup.entities.scenario ? setup.entities.scenario : []).filter(function (row) {
            return !row.archived && row.status === 'confirmed' && row.active !== false;
        });
        var engines = Object.keys(engineState).filter(function (key) {
            return engineState[key] && engineState[key].availability === 'ready';
        });
        if (!profile.id || !scenarios.length || !engines.length) {
            target.innerHTML = '<h2>' + escapeHtml(strings.measurementNotReady || 'Measurement setup is not ready.') +
                '</h2><p>' + escapeHtml(strings.measurementNotReadyHint ||
                    'Confirm at least one scenario and configure an answer engine first.') + '</p>';
            return;
        }
        target.innerHTML = '<form class="aysa-ai-visibility__measurement-form"><header><div><h2>' +
            escapeHtml(strings.measurementTitle || 'Prepare an exact measurement quote') + '</h2><p>' +
            escapeHtml(strings.measurementHint ||
                'Review the exact cohort, prompts and maximum cost before starting a paid run.') +
            '</p></div></header><fieldset><legend>' + escapeHtml(strings.scenarios || 'Scenarios') + '</legend>' +
            scenarios.map(function (row) {
                return '<label><input type="checkbox" name="scenario_ids" value="' + Number(row.id) +
                    '" data-requires-multi-turn="' + (row.conversation_mode === 'multi_turn' || row.test_type === 'recommendation_journey' ? '1' : '0') +
                    '" checked> <span><strong>' + escapeHtml(row.name || ('#' + row.id)) +
                    '</strong><small>' + escapeHtml(row.test_type || '') + '</small></span></label>';
            }).join('') + '</fieldset><fieldset><legend>' + escapeHtml(strings.answerEngines || 'Answer engines') +
            '</legend>' + engines.map(function (key) {
                var engine = engineState[key] || {};
                return '<label><input type="checkbox" name="engine_keys" value="' + escapeAttr(key) +
                    '" data-supports-multi-turn="' + (engine.supports_multi_turn ? '1' : '0') +
                    '" checked> <span><strong>' + escapeHtml(engineLabel(key, engine.engine)) +
                    '</strong><small>' + escapeHtml(mappedLabel('channelLabels', engine.channel || '', engine.channel || '')) + '</small></span></label>';
            }).join('') + '</fieldset><div class="aysa-ai-visibility__measurement-options"><label><span>' +
            escapeHtml(strings.replicates || 'Replicates') + '</span><input name="replicates" type="number" min="1" max="20" value="1"></label>' +
            '<label><span>' + escapeHtml(strings.fieldPrimaryLanguage || 'Language') +
            '</span><input name="locale" type="text" value="' + escapeAttr(profile.primary_language || '') + '"></label>' +
            '<label><span>' + escapeHtml(strings.location || 'Location') +
            '</span><input name="location" type="text" value="' +
            escapeAttr((profile.locations || [])[0] || '') + '"></label></div><button type="submit" class="button button-primary">' +
            escapeHtml(strings.calculateExactQuote || 'Calculate exact quote') +
            '</button><div class="aysa-ai-visibility__measurement-status" role="status"></div></form>' +
            '<div class="aysa-ai-visibility__quote"></div><div class="aysa-ai-visibility__schedule-status" aria-live="polite"></div>';
        var measurementForm = target.querySelector('form');
        function syncMeasurementCompatibility() {
            var requiresMultiTurn = Boolean(measurementForm.querySelector(
                'input[name="scenario_ids"][data-requires-multi-turn="1"]:checked'
            ));
            var disabledCount = 0;
            Array.prototype.forEach.call(measurementForm.querySelectorAll('input[name="engine_keys"]'), function (input) {
                var incompatible = requiresMultiTurn && input.getAttribute('data-supports-multi-turn') !== '1';
                input.disabled = incompatible;
                if (incompatible) {
                    input.checked = false;
                    disabledCount++;
                }
                input.closest('label').classList.toggle('is-incompatible', incompatible);
            });
            measurementForm.querySelector('.aysa-ai-visibility__measurement-status').textContent = disabledCount > 0
                ? (strings.multiTurnEngineUnsupported || 'An incompatible engine was deselected.')
                : '';
        }
        Array.prototype.forEach.call(measurementForm.querySelectorAll('input[name="scenario_ids"]'), function (input) {
            input.addEventListener('change', syncMeasurementCompatibility);
        });
        syncMeasurementCompatibility();
        measurementForm.addEventListener('submit', function (event) {
            event.preventDefault();
            var form = event.currentTarget;
            var scenarioIds = Array.prototype.map.call(
                form.querySelectorAll('input[name="scenario_ids"]:checked'),
                function (input) { return Number(input.value); }
            );
            var engineKeys = Array.prototype.map.call(
                form.querySelectorAll('input[name="engine_keys"]:checked'),
                function (input) { return String(input.value); }
            );
            var status = form.querySelector('.aysa-ai-visibility__measurement-status');
            if (!scenarioIds.length || !engineKeys.length) {
                status.textContent = strings.measurementSelectionRequired || 'Choose at least one scenario and engine.';
                return;
            }
            status.textContent = strings.calculatingQuote || 'Compiling exact prompts and cost…';
            request('run_quote', {
                brand_profile_id: Number(profile.id),
                scenario_ids: scenarioIds,
                engine_keys: engineKeys,
                replicates: Number(form.elements.replicates.value || 1),
                locale: String(form.elements.locale.value || ''),
                location: String(form.elements.location.value || '')
            }).then(function (quote) {
                status.textContent = '';
                renderMeasurementQuote(quote);
            }).catch(function (error) {
                status.textContent = humanError(error);
            });
        });
    }
    function renderMeasurementQuote(quote) {
        var target = root.querySelector('.aysa-ai-visibility__quote');
        var estimate = quote.estimate || {};
        var scope = quote.monitoring_scope_context || {};
        var prompts = scope.query_pack || [];
        var preflight = quote.monitoring_preflight || {};
        var policy = quote.monitoring_policy || {};
        var selection = quote.selection || {};
        var billing = quote.billing || {};
        var maximum = Number(estimate.maximum_credits || 0);
        var available = Number(billing.available_credits_cents || 0);
        var insufficient = billing.insufficient_credits === true;
        var insufficientCopy = (strings.insufficientCreditsForRun ||
            'This measurement needs a maximum of {required} credits, but only {available} are currently available. Add credits and calculate the quote again.')
            .replace('{required}', String(maximum))
            .replace('{available}', String(available));
        var activationRequired = preflight.ok && !policy.manual_start_allowed;
        var scheduleControls = schedulingEnabled && !insufficient
            ? '<section class="aysa-ai-visibility__schedule-box"><h3>' +
                escapeHtml(strings.scheduleTitle || 'Automatic AI Visibility schedule') + '</h3><p>' +
                escapeHtml(strings.scheduleHint ||
                    'Uses the canonical Monitoring frequency, exact cohort and approved monthly budget. Existing users are never enrolled automatically.') +
                '</p><div class="aysa-ai-visibility__measurement-options"><label><span>' +
                escapeHtml(strings.monthlyBudget || 'Monthly Monitoring budget') +
                '</span><input type="number" min="' + maximum + '" value="' + Math.max(maximum * 4, maximum) +
                '" data-schedule-monthly-budget></label><label><span>' +
                escapeHtml(strings.perRunCap || 'Maximum credits for this run') +
                '</span><input type="number" min="' + maximum + '" value="' + maximum +
                '" data-schedule-per-run-cap></label></div><button type="button" class="button" data-prepare-schedule>' +
                escapeHtml(strings.reviewSchedule || 'Review automatic schedule') + '</button></section>'
            : '';
        var policyControls = insufficient
            ? '<p class="aysa-ai-visibility__notice" role="alert"><strong>' + escapeHtml(insufficientCopy) + '</strong></p>'
            : (preflight.ok && policy.manual_start_allowed
            ? '<label class="aysa-ai-visibility__run-confirm"><input type="checkbox" data-confirm-run> <span>' +
                escapeHtml(strings.confirmRunCost || 'I approve this exact cohort and maximum cost.') +
                '</span></label><button type="button" class="button button-primary" data-start-measurement disabled>' +
                escapeHtml(strings.startMeasurement || 'Start measurement') + '</button>'
            : (activationRequired
                ? '<p>' + escapeHtml(strings.monitoringActivationRequired ||
                    'The policy is approved, but Monitoring must be active in Agent8 before a manual run can start.') + '</p>'
                : '<div class="aysa-ai-visibility__measurement-options"><label><span>' +
                escapeHtml(strings.monthlyBudget || 'Monthly Monitoring budget') +
                '</span><input type="number" min="' + maximum + '" value="' + Math.max(maximum * 4, maximum) +
                '" data-monthly-budget></label><label><span>' +
                escapeHtml(strings.perRunCap || 'Maximum credits for this run') +
                '</span><input type="number" min="' + maximum + '" value="' + maximum +
                '" data-per-run-cap></label></div><p>' +
                escapeHtml(strings.policyApprovalNotice || 'This authorizes manual measurements only. It does not enable a schedule.') +
                '</p><button type="button" class="button button-primary" data-prepare-policy>' +
                escapeHtml(strings.preparePolicyApproval || 'Review Monitoring approval') + '</button>'));
        if (!insufficient && billing.wallet_snapshot_available === false) {
            policyControls = '<p class="aysa-ai-visibility__notice" role="alert"><strong>' +
                escapeHtml(humanError('ai_visibility_wallet_snapshot_unavailable')) + '</strong></p>';
            scheduleControls = '';
        }
        target.innerHTML = '<article class="aysa-ai-visibility__quote-card"><header><div><h2>' +
            escapeHtml(strings.exactQuote || 'Exact quote') + '</h2><p>' +
            escapeHtml(String(estimate.conversation_count || 0) + ' ' + countedLabel(
                estimate.conversation_count,
                strings.conversationSingular || 'conversation',
                strings.conversations || 'conversations'
            ) +
                ' · ' + String(estimate.estimated_turn_count || 0) + ' ' + (strings.turns || 'turns')) +
            '</p></div><strong>' + escapeHtml(String(estimate.minimum_credits || 0) + '–' +
                String(estimate.maximum_credits || 0) + ' ' + (strings.credits || 'credits')) +
            '</strong></header><details><summary>' + escapeHtml(strings.dataPreview || 'Exact data sent to providers') +
            '</summary><ol>' + prompts.map(function (row) {
                return '<li><span>' + escapeHtml(row.prompt || '') + '</span><small>' +
                    escapeHtml([row.goal, row.language].filter(Boolean).join(' · ')) + '</small></li>';
            }).join('') + '</ol></details><div class="aysa-ai-visibility__quote-confirm"><p><strong>' +
            escapeHtml(preflight.ok
                ? (strings.policyReady || 'The canonical Monitoring policy and exact scope are ready.')
                : (strings.policyRequired || 'Approve a manual-only Monitoring budget and this exact scope before starting.')) +
            '</strong></p><p>' + escapeHtml(strings.noChargeForQuote ||
                'This quote did not call a provider or use credits.') + '</p><p>' +
            escapeHtml((strings.availableCredits || 'Available credits') + ': ' + String(available)) +
            '</p>' + policyControls +
            '<a class="button" href="' + safeUrl(aysaAiVisibility.agent8Url || '#') + '">' +
            escapeHtml(strings.openAgent8ForApproval || 'Open Agent8 Monitoring') + '</a></div>' +
            scheduleControls + '</article>';

        var confirmRun = target.querySelector('[data-confirm-run]');
        var start = target.querySelector('[data-start-measurement]');
        if (confirmRun && start) {
            confirmRun.addEventListener('change', function () { start.disabled = !confirmRun.checked; });
            start.addEventListener('click', function () {
                start.disabled = true;
                start.textContent = strings.startingMeasurement || 'Creating the durable measurement run…';
                if (!measurementRunReference) {
                    measurementRunReference = 'manual:' + String(quote.quote_hash || '') + ':' +
                        String(Date.now()) + ':' + Math.random().toString(16).slice(2);
                }
                request('run_start', Object.assign({}, selection, {
                    quote_hash: String(quote.quote_hash || ''),
                    max_total_cost: maximum,
                    run_reference: measurementRunReference,
                    explicit_confirmation: true,
                    confirmation_kind: 'ai_visibility_manual_run_approval'
                })).then(function () {
                    target.querySelector('.aysa-ai-visibility__quote-confirm').innerHTML = '<p><strong>' +
                        escapeHtml(strings.measurementQueued || 'Measurement queued. Provider work will continue in the background.') +
                        '</strong></p>';
                }).catch(function (error) {
                    start.disabled = false;
                    start.textContent = strings.startMeasurement || 'Start measurement';
                    window.alert(humanError(error));
                });
            });
        }
        var prepare = target.querySelector('[data-prepare-policy]');
        if (prepare) {
            prepare.addEventListener('click', function () {
                var monthly = Number(target.querySelector('[data-monthly-budget]').value || 0);
                var perRun = Number(target.querySelector('[data-per-run-cap]').value || 0);
                prepare.disabled = true;
                request('run_policy_prepare', Object.assign({}, selection, {
                    monthly_budget_cents: monthly,
                    per_run_cap_cents: perRun
                })).then(function (prepared) {
                    renderMeasurementPolicyConfirmation(prepared, selection, monthly, perRun);
                }).catch(function (error) {
                    prepare.disabled = false;
                    window.alert(humanError(error));
                });
            });
        }
        var prepareSchedule = target.querySelector('[data-prepare-schedule]');
        if (prepareSchedule) {
            prepareSchedule.addEventListener('click', function () {
                var monthly = Number(target.querySelector('[data-schedule-monthly-budget]').value || 0);
                var perRun = Number(target.querySelector('[data-schedule-per-run-cap]').value || 0);
                prepareSchedule.disabled = true;
                request('schedule_prepare', Object.assign({}, selection, {
                    monthly_budget_cents: monthly,
                    per_run_cap_cents: perRun
                })).then(function (prepared) {
                    renderScheduleConfirmation(prepared, selection, monthly, perRun);
                }).catch(function (error) {
                    prepareSchedule.disabled = false;
                    window.alert(humanError(error));
                });
            });
        }
    }

    function renderScheduleConfirmation(prepared, selection, monthly, perRun) {
        var target = root.querySelector('.aysa-ai-visibility__schedule-box');
        if (!target) {
            return;
        }
        var policy = prepared.policy || {};
        target.innerHTML = '<h3>' + escapeHtml(strings.scheduleTitle || 'Automatic AI Visibility schedule') +
            '</h3><dl><div><dt>' + escapeHtml(strings.scheduleFrequency || 'Frequency') + '</dt><dd>' +
            escapeHtml(prepared.frequency || policy.frequency || '') + '</dd></div><div><dt>' +
            escapeHtml(strings.nextScheduledRun || 'Next scheduled run') + '</dt><dd>' +
            escapeHtml(prepared.next_due_at || '') + '</dd></div><div><dt>' +
            escapeHtml(strings.perRunCap || 'Maximum credits for this run') + '</dt><dd>' +
            escapeHtml(String(policy.per_run_cap_cents || perRun)) + '</dd></div><div><dt>' +
            escapeHtml(strings.monthlyBudget || 'Monthly Monitoring budget') + '</dt><dd>' +
            escapeHtml(String(policy.monthly_budget_cents || monthly)) + '</dd></div></dl><label class="aysa-ai-visibility__run-confirm">' +
            '<input type="checkbox" data-confirm-schedule-consent> <span>' +
            escapeHtml(strings.scheduleConsent ||
                'I authorize recurring paid measurements for this exact cohort, frequency and budget.') +
            '</span></label><button type="button" class="button button-primary" data-confirm-schedule disabled>' +
            escapeHtml(strings.confirmSchedule || 'Confirm automatic schedule') + '</button>';
        var consent = target.querySelector('[data-confirm-schedule-consent]');
        var confirm = target.querySelector('[data-confirm-schedule]');
        consent.addEventListener('change', function () { confirm.disabled = !consent.checked; });
        confirm.addEventListener('click', function () {
            confirm.disabled = true;
            request('schedule_confirm', Object.assign({}, selection, {
                monthly_budget_cents: monthly,
                per_run_cap_cents: perRun,
                frequency: String(prepared.frequency || ''),
                confirmation_hash: String(prepared.confirmation_hash || ''),
                explicit_confirmation: true,
                confirmation_kind: 'ai_visibility_schedule_approval'
            })).then(function (confirmed) {
                target.innerHTML = '<p><strong>' +
                    escapeHtml(strings.scheduleConfirmed || 'Automatic schedule confirmed.') + '</strong></p>';
                renderScheduleStatus({schedules: confirmed.schedule ? [confirmed.schedule] : []});
            }).catch(function (error) {
                confirm.disabled = false;
                window.alert(humanError(error));
            });
        });
    }

    function renderScheduleStatus(data) {
        var target = root.querySelector('.aysa-ai-visibility__schedule-status');
        if (!target) {
            return;
        }
        var schedules = Array.isArray(data && data.schedules) ? data.schedules : [];
        target.innerHTML = schedules.map(function (schedule) {
            var scheduleState = schedule.schedule_state || {};
            var paused = schedule.status === 'paused';
            return '<article class="aysa-ai-visibility__schedule-summary"><div><h3>' +
                escapeHtml(paused
                    ? (strings.schedulePaused || 'Schedule paused — reconfirmation required')
                    : (strings.scheduleActive || 'Schedule active')) + '</h3><p>' +
                escapeHtml((schedule.frequency || '') + ' · ' +
                    (strings.nextScheduledRun || 'Next scheduled run') + ': ' +
                    String(scheduleState.next_due_at || '')) + '</p></div><button type="button" class="button" data-disable-schedule="' +
                Number(schedule.id || 0) + '">' + escapeHtml(strings.disableSchedule || 'Disable schedule') + '</button></article>';
        }).join('');
        Array.prototype.forEach.call(target.querySelectorAll('[data-disable-schedule]'), function (button) {
            button.addEventListener('click', function () {
                if (!window.confirm(strings.disableScheduleConfirm ||
                    'Disable this AI Visibility schedule? Existing measurements and evidence will remain unchanged.')) {
                    return;
                }
                button.disabled = true;
                request('schedule_disable', {
                    schedule_id: Number(button.getAttribute('data-disable-schedule') || 0),
                    explicit_confirmation: true,
                    confirmation_kind: 'ai_visibility_schedule_disable'
                }).then(function () {
                    target.innerHTML = '<p>' +
                        escapeHtml(strings.scheduleDisabled || 'Schedule disabled. Existing results were preserved.') + '</p>';
                }).catch(function (error) {
                    button.disabled = false;
                    window.alert(humanError(error));
                });
            });
        });
    }
    function renderMeasurementPolicyConfirmation(prepared, selection, monthly, perRun) {
        var target = root.querySelector('.aysa-ai-visibility__quote');
        var policy = prepared.policy || {};
        target.innerHTML = '<article class="aysa-ai-visibility__quote-card"><h2>' +
            escapeHtml(strings.preparePolicyApproval || 'Review Monitoring approval') + '</h2><p><strong>' +
            escapeHtml(String(policy.per_run_cap_cents || perRun) + ' ' + (strings.credits || 'credits')) +
            '</strong> · ' + escapeHtml(String(policy.monthly_budget_cents || monthly) + ' / month') +
            '</p><p>' + escapeHtml(strings.policyApprovalNotice ||
                'This authorizes manual measurements only. It does not enable a schedule.') +
            '</p><button type="button" class="button button-primary" data-confirm-policy>' +
            escapeHtml(strings.confirmPolicyApproval || 'Confirm manual-only Monitoring policy') + '</button></article>';
        target.querySelector('[data-confirm-policy]').addEventListener('click', function (event) {
            var button = event.currentTarget;
            button.disabled = true;
            request('run_policy_confirm', Object.assign({}, selection, {
                monthly_budget_cents: monthly,
                per_run_cap_cents: perRun,
                confirmation_hash: String(prepared.confirmation_hash || ''),
                explicit_confirmation: true,
                confirmation_kind: 'ai_visibility_monitoring_policy_approval'
            })).then(function (confirmed) {
                renderMeasurementQuote(confirmed.quote || {});
            }).catch(function (error) {
                button.disabled = false;
                window.alert(humanError(error));
            });
        });
    }
    function loadMeasurement() {
        var target = root.querySelector('.aysa-ai-visibility__measurement');
        var finishLoading = beginViewState(target, 'measurement');
        Promise.all([
            request('setup_read', {include_archived: false}),
            request('status', {})
        ]).then(function (results) {
            finishLoading();
            engineState = normalizeEngines(results[1].engines);
            renderMeasurement(results[0], results[1]);
            if (schedulingEnabled) {
                request('schedule_status', {}).then(renderScheduleStatus).catch(function (error) {
                    var scheduleStatus = root.querySelector('.aysa-ai-visibility__schedule-status');
                    if (scheduleStatus) {
                        scheduleStatus.textContent = humanError(error);
                    }
                });
            }
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'measurement', humanError(error), loadMeasurement);
        });
    }
    function citationDisplayKey(value) {
        try {
            var parsed = new URL(String(value || ''));
            var kept = [];
            parsed.searchParams.forEach(function (item, key) {
                if (key.toLowerCase().indexOf('utm_') !== 0 && ['gclid', 'fbclid', 'msclkid'].indexOf(key.toLowerCase()) === -1) {
                    kept.push([key, item]);
                }
            });
            kept.sort(function (left, right) { return (left[0] + left[1]).localeCompare(right[0] + right[1]); });
            var query = kept.map(function (item) {
                return encodeURIComponent(item[0]) + '=' + encodeURIComponent(item[1]);
            }).join('&');
            return parsed.origin.toLowerCase() + parsed.pathname.replace(/\/$/, '') + (query ? '?' + query : '');
        } catch (error) {
            return String(value || '').trim().toLowerCase();
        }
    }
    function uniqueDisplayCitations(rows) {
        var seen = {};
        return (rows || []).filter(function (row) {
            var key = citationDisplayKey(row.canonical_url || row.original_url || '');
            if (!key || seen[key]) {
                return false;
            }
            seen[key] = true;
            return true;
        });
    }
    function conversationInterpretation(row) {
        var recommendations = (row.recommendations || []).filter(function (item) {
            return Boolean(Number(item.counts_as_recommendation || 0));
        });
        var citations = row.citations || [];
        var firstParty = citations.filter(function (item) { return item.ownership_type === 'first_party'; });
        var mentions = (row.occurrences || []).filter(function (item) { return item.entity_type === 'target_brand'; });
        if (recommendations.length) { return strings.evidenceRecommended || 'The business was explicitly recommended.'; }
        if (firstParty.length) { return strings.evidenceCited || 'The site was cited without an explicit recommendation.'; }
        if (mentions.length) { return strings.evidenceMentioned || 'The business was mentioned without a recommendation.'; }
        return strings.evidenceNoSignal || 'No eligible business signal was detected.';
    }
    function loadEvidence(page) {
        var target = root.querySelector('.aysa-ai-visibility__evidence');
        if (!latestRunId) {
            target.innerHTML = '<p>' + escapeHtml(strings.noEvidence || 'No evidence yet.') + '</p>';
            return;
        }
        var finishLoading = beginViewState(target, 'evidence');
        request('evidence_read', {run_batch_id: latestRunId, page: page, per_page: 20}).then(function (data) {
            finishLoading();
            evidencePage = Number(data.pagination.page || 1);
            var rows = data.conversations || [];
            target.innerHTML = rows.length ? rows.map(function (row) {
                var recommendations = (row.recommendations || []).map(function (item) {
                    return '<li><strong>' + escapeHtml(mappedLabel('recommendationLabels', item.classification, strings.evidenceRecommended || 'Recommendation signal')) +
                        '</strong><span>' + escapeHtml(item.evidence_excerpt || '') + '</span></li>';
                }).join('');
                var citations = uniqueDisplayCitations(row.citations || []).map(function (item) {
                    return '<li><a href="' + safeUrl(item.canonical_url || item.original_url) + '" target="_blank" rel="noopener noreferrer">' +
                        escapeHtml(item.domain || item.canonical_url) + '</a> <span class="aysa-ai-visibility__badge">' +
                        escapeHtml(mappedLabel('ownershipLabels', item.ownership_type || 'unknown',
                            mappedLabel('ownershipLabels', 'unknown', 'Unclassified source'))) + '</span></li>';
                }).join('');
                var testType = mappedLabel('testTypeLabels', row.test_type, strings.conversations || 'Conversation');
                var question = row.question_text || testType;
                var shortQuestion = question.length > 140 ? question.slice(0, 137) + '…' : question;
                return '<details class="aysa-ai-visibility__conversation"><summary><span>' +
                    escapeHtml(engineLabel(row.engine_key || row.engine, row.engine)) + ' · ' +
                    escapeHtml(testType) + '</span><strong>' +
                    escapeHtml(shortQuestion) + '</strong></summary><div class="aysa-ai-visibility__evidence-flow"><section><h3>' +
                    escapeHtml(strings.question || 'Question') + '</h3><p>' + escapeHtml(question) + '</p></section><section><h3>' +
                    escapeHtml(strings.answerExcerpt || 'Answer evidence') + '</h3><div class="aysa-ai-visibility__answer">' +
                    escapeHtml(row.response_text || '') + '</div></section><section><h3>' +
                    escapeHtml(strings.interpretation || 'What this means') + '</h3><p>' +
                    escapeHtml(conversationInterpretation(row)) + '</p></section><section><h3>' +
                    escapeHtml(strings.sources || 'Sources') + '</h3>' + (citations
                        ? '<ul class="aysa-ai-visibility__evidence-list">' + citations + '</ul>'
                        : '<p class="aysa-ai-visibility__muted">—</p>') + '</section></div>' +
                    (recommendations ? '<ul class="aysa-ai-visibility__evidence-list aysa-ai-visibility__recommendation-evidence">' + recommendations + '</ul>' : '') +
                    '<details class="aysa-ai-visibility__evidence-technical"><summary>' +
                    escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><p>' +
                    escapeHtml([row.provider, row.channel, row.model_family, row.test_type, row.eligibility_reason]
                        .concat((row.recommendations || []).map(function (item) { return item.classification; }))
                        .filter(Boolean).join(' · ')) +
                    '</p></details></details>';
            }).join('') : '<p>' + escapeHtml(strings.noEvidence || 'No evidence yet.') + '</p>';
            renderPagination(data.pagination || {});
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'evidence', error.name === 'AbortError' ? strings.timeout : humanError(error),
                function () { loadEvidence(evidencePage); });
        });
    }
    function renderPagination(pagination) {
        var target = root.querySelector('.aysa-ai-visibility__pagination');
        var page = Number(pagination.page || 1);
        var pages = Number(pagination.pages || 0);
        target.innerHTML = pages > 1
            ? '<button type="button" class="button" data-page="' + (page - 1) + '"' + (page <= 1 ? ' disabled' : '') + '>' +
                escapeHtml(strings.previous || 'Previous') + '</button><button type="button" class="button" data-page="' +
                (page + 1) + '"' + (page >= pages ? ' disabled' : '') + '>' + escapeHtml(strings.next || 'Next') + '</button>'
            : '';
        Array.prototype.forEach.call(target.querySelectorAll('[data-page]'), function (button) {
            button.addEventListener('click', function () { loadEvidence(Number(button.getAttribute('data-page'))); });
        });
    }
    function loadTrends() {
        var target = root.querySelector('.aysa-ai-visibility__trends');
        var finishLoading = beginViewState(target, 'trends');
        request('setup_read', {include_archived: false}).then(function (setup) {
            if (!setup.profile) {
                finishLoading();
                target.innerHTML = '<h2>' + escapeHtml(strings.noTrends || 'No trend data yet.') + '</h2>';
                return;
            }
            return request('trends_read', {
                profile_id: Number(setup.profile.id),
                limit: 12
            }).then(function (data) {
                finishLoading();
                var grouped = {};
                (data.series || []).forEach(function (point) {
                    var key = String(point.metric_key || 'unknown');
                    grouped[key] = grouped[key] || [];
                    grouped[key].push(point);
                });
                var keys = Object.keys(grouped);
                target.innerHTML = keys.length ? '<div class="aysa-ai-visibility__trend-grid">' + keys.map(function (key) {
                    var points = grouped[key];
                    var newest = points[0] || {};
                    var previous = points[1] || {};
                    var newestValue = newest.value_percent == null ? null : Number(newest.value_percent);
                    var previousValue = previous.value_percent == null ? null : Number(previous.value_percent);
                    var comparable = previousValue != null && newestValue != null && !newest.series_break &&
                        String(newest.cohort_hash || '') !== '' && newest.cohort_hash === previous.cohort_hash &&
                        String(newest.methodology_version || '') !== '' && newest.methodology_version === previous.methodology_version;
                    var delta = comparable ? newestValue - previousValue : null;
                    return '<article class="aysa-ai-visibility__trend"><header><div><h2>' +
                        escapeHtml(metricLabel(key)) + '</h2><p>' +
                        escapeHtml(String(points.length) + ' ' + (strings.measurements || 'measurements')) +
                        '</p></div><strong>' + escapeHtml(newestValue == null
                            ? (strings.insufficientData || 'Insufficient data')
                            : newestValue.toFixed(1) + '%') + '</strong></header><p class="aysa-ai-visibility__trend-delta">' +
                        escapeHtml(delta == null ? '' : ((delta >= 0 ? '+' : '') + delta.toFixed(1) + ' pp')) +
                        '</p>' + (!comparable && points.length > 1
                            ? '<p>' + escapeHtml(strings.trendNotComparable || 'The latest two observations are not comparable, so no delta is shown.') + '</p>'
                            : '') + '<ol>' + points.map(function (point) {
                            var value = point.value_percent == null
                                ? (strings.insufficientData || 'Insufficient data')
                                : Number(point.value_percent).toFixed(1) + '%';
                            var breakLabel = point.series_break
                                ? mappedLabel('seriesBreakLabels', point.series_break_reason,
                                    strings.trendNotComparable || 'New comparison series')
                                : '';
                            return '<li><time>' + escapeHtml(formatInterfaceDate(point.period_ended_at || '')) + '</time><strong>' +
                                escapeHtml(value) + '</strong><small>' +
                                escapeHtml('n=' + String(point.sample_size || 0)) + '</small>' +
                                (breakLabel ? '<span>' + escapeHtml(breakLabel) + '</span><details><summary>' +
                                    escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
                                    escapeHtml(point.series_break_reason || '') + '</code></details>' : '') + '</li>';
                        }).join('') + '</ol><details><summary>' +
                        escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
                        escapeHtml(key) + '</code></details></article>';
                }).join('') + '</div>' : '<h2>' +
                    escapeHtml(strings.noTrends || 'No trend data yet.') + '</h2><p>' +
                    escapeHtml(strings.runFirst || 'Complete a measurement to generate trends.') + '</p>';
            });
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'trends', humanError(error), loadTrends);
        });
    }
    function signalCard(title, rows, renderRow) {
        return '<section class="aysa-ai-visibility__signal-group"><header><h2>' +
            escapeHtml(title) + '</h2><span class="aysa-ai-visibility__badge">' +
            String(rows.length) + '</span></header>' + (rows.length
            ? '<div class="aysa-ai-visibility__signal-list">' + rows.map(renderRow).join('') + '</div>'
            : '<p class="aysa-ai-visibility__muted">' + escapeHtml(strings.noSignalsInGroup || 'No signals in this run.') + '</p>') +
            '</section>';
    }
    function signalStatusLabel(row) {
        if (row.grounding_status) {
            return mappedLabel('groundingLabels', row.grounding_status, strings.technicalDetails || 'Review technical details');
        }
        if (row.classification) {
            return mappedLabel('factClassificationLabels', row.classification, strings.technicalDetails || 'Review technical details');
        }
        if (row.sentiment) {
            return mappedLabel('sentimentLabels', row.sentiment, strings.technicalDetails || 'Review technical details');
        }
        if (row.method) {
            return mappedLabel('signalMethodLabels', row.method, strings.technicalDetails || 'Review technical details');
        }
        return '';
    }
    function loadSignals() {
        var target = root.querySelector('.aysa-ai-visibility__signals');
        if (!latestRunId) {
            target.innerHTML = '<h2>' + escapeHtml(strings.noSignals || 'No extracted signals yet.') + '</h2>';
            return;
        }
        var finishLoading = beginViewState(target, 'signals');
        request('signals_read', {run_batch_id: latestRunId}).then(function (data) {
            finishLoading();
            var textRow = function (row) {
                return '<article><strong>' +
                    escapeHtml(row.claim_text || row.matched_text || row.query_text || signalStatusLabel(row)) +
                    '</strong><p>' + escapeHtml(row.evidence_excerpt || '') + '</p><small>' +
                    escapeHtml(signalStatusLabel(row)) + '</small><details class="aysa-ai-visibility__evidence-technical"><summary>' +
                    escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><p>' +
                    escapeHtml([row.grounding_status, row.classification, row.sentiment, row.method].filter(Boolean).join(' · ')) +
                    '</p></details></article>';
            };
            var citationRow = function (row) {
                var url = safeUrl(row.canonical_url);
                return '<article><strong><a href="' + url + '" target="_blank" rel="noopener noreferrer">' +
                    escapeHtml(row.title || row.domain || row.canonical_url || '') + '</a></strong><p>' +
                    escapeHtml(row.evidence_excerpt || '') + '</p><small>' +
                    escapeHtml([
                        mappedLabel('ownershipLabels', row.ownership_type || 'unknown', mappedLabel('ownershipLabels', 'unknown', 'Source')),
                        mappedLabel('sentimentLabels', row.sentiment || 'neutral', row.sentiment || '')
                    ].filter(Boolean).join(' · ')) + '</small><details class="aysa-ai-visibility__evidence-technical"><summary>' +
                    escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><p>' +
                    escapeHtml([row.ownership_type, row.source_category, row.sentiment].filter(Boolean).join(' · ')) +
                    '</p></details></article>';
            };
            target.innerHTML =
                signalCard(strings.perceptions || 'Perceptions', data.perceptions || [], textRow) +
                signalCard(strings.facts || 'Fact checks', data.facts || [], textRow) +
                signalCard(strings.competitorMentions || 'Competitor mentions', data.competitor_mentions || [], textRow) +
                signalCard(strings.citations || 'Citations', uniqueDisplayCitations(data.citations || []), citationRow) +
                signalCard(strings.queryExpansions || 'Query expansions', data.query_expansions || [], textRow);
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'signals', humanError(error), loadSignals);
        });
    }
    function listValue(value) {
        return Array.isArray(value) ? value.join(', ') : '';
    }
    function splitList(value) {
        return String(value || '').split(/[,;\n]+/).map(function (item) {
            return item.trim();
        }).filter(Boolean);
    }
    function setupField(name, label, value, type, prefix) {
        var id = 'aysa-aiv-' + (prefix || 'profile-') + name;
        if (type === 'textarea') {
            return '<label for="' + id + '"><span>' + escapeHtml(label) + '</span><textarea id="' + id +
                '" name="' + escapeAttr(name) + '" rows="3">' + escapeHtml(value || '') + '</textarea></label>';
        }
        return '<label for="' + escapeAttr(id) + '"><span>' + escapeHtml(label) + '</span><input id="' + escapeAttr(id) + '" name="' +
            escapeAttr(name) + '" type="' + escapeAttr(type || 'text') + '" value="' + escapeAttr(value || '') + '"' +
            (name === 'canonical_domain' && prefix !== 'entity-' ? ' readonly' : '') + '></label>';
    }
    function confirmedEntityCount(entities, type) {
        return (entities[type] || []).filter(function (row) {
            return !row.archived && row.active !== false && (row.status === 'confirmed' || row.confirmed === true);
        }).length;
    }
    function setupChecklistItem(label, count, required) {
        var ready = count > 0;
        var stateLabel = ready
            ? (strings.setupReady || 'Ready')
            : (required ? (strings.setupNeedsAttention || 'Needs attention') : (strings.setupRecommended || 'Recommended'));
        return '<li class="' + (ready ? 'is-ready' : (required ? 'needs-attention' : 'is-recommended')) + '"><span>' +
            escapeHtml(label) + '</span><strong>' + escapeHtml(stateLabel + (count > 0 ? ' · ' + count : '')) + '</strong></li>';
    }
    function renderSetup() {
        var target = root.querySelector('.aysa-ai-visibility__setup');
        var profile = setupData && setupData.profile ? setupData.profile : {};
        var entities = setupData && setupData.entities ? setupData.entities : {};
        var readyEngines = Object.keys(engineState).filter(function (key) {
            return engineState[key] && engineState[key].availability === 'ready';
        }).length;
        var profileConfirmed = profile.status === 'confirmed';
        target.innerHTML = '<section class="aysa-ai-visibility__setup-checklist"><h3>' +
            escapeHtml(strings.setupChecklist || 'Setup readiness') + '</h3><ul>' +
            setupChecklistItem(strings.setupBrand || 'Brand profile', profileConfirmed ? 1 : 0, true) +
            setupChecklistItem(strings.setupTopics || 'Confirmed topics', confirmedEntityCount(entities, 'topic'), true) +
            setupChecklistItem(strings.setupScenarios || 'Confirmed scenarios', confirmedEntityCount(entities, 'scenario'), true) +
            setupChecklistItem(strings.setupCompetitors || 'Confirmed competitors', confirmedEntityCount(entities, 'competitor'), false) +
            setupChecklistItem(strings.setupClaims || 'Confirmed claims', confirmedEntityCount(entities, 'claim'), false) +
            setupChecklistItem(strings.setupEngines || 'Ready engines', readyEngines, true) +
            '</ul></section><p class="aysa-ai-visibility__profile-state ' + (profileConfirmed ? 'is-confirmed' : 'is-draft') + '">' +
            escapeHtml(profileConfirmed ? (strings.profileConfirmedState || 'Profile explicitly confirmed.') :
                (strings.profileDraft || 'Autosaved draft — explicit confirmation is still required.')) + '</p>' +
            '<div class="aysa-ai-visibility__save-status" role="status" aria-live="polite"></div>' +
            '<form class="aysa-ai-visibility__profile-form">' +
            '<div class="aysa-ai-visibility__form-grid">' +
            setupField('brand_name', strings.fieldBrand || 'Brand', profile.brand_name) +
            setupField('canonical_domain', strings.fieldDomain || 'Canonical domain', profile.canonical_domain) +
            setupField('category', strings.fieldCategory || 'Category', profile.category) +
            setupField('primary_language', strings.fieldPrimaryLanguage || 'Primary language', profile.primary_language) +
            setupField('description', strings.fieldDescription || 'Description', profile.description, 'textarea') +
            setupField('products', strings.fieldProducts || 'Products', listValue(profile.products), 'textarea') +
            setupField('services', strings.fieldServices || 'Services', listValue(profile.services), 'textarea') +
            setupField('differentiators', strings.fieldDifferentiators || 'Differentiators', listValue(profile.differentiators), 'textarea') +
            setupField('markets', strings.fieldMarkets || 'Markets', listValue(profile.markets), 'textarea') +
            setupField('locations', strings.fieldLocations || 'Locations', listValue(profile.locations), 'textarea') +
            setupField('languages', strings.fieldLanguages || 'Languages', listValue(profile.languages), 'textarea') +
            '</div><div class="aysa-ai-visibility__form-actions"><button type="button" class="button button-primary" data-confirm-profile>' +
            escapeHtml(strings.confirmProfile || 'Confirm profile') + '</button><span class="aysa-ai-visibility__muted">' +
            escapeHtml(strings.autosaveHint || 'Changes are saved automatically as a draft.') + '</span></div></form>' +
            '<section class="aysa-ai-visibility__entity-workspace"><div class="aysa-ai-visibility__entity-header"><h3>' +
            escapeHtml(strings.setupEntities || 'Personas, topics and evidence setup') + '</h3><label><input type="checkbox" data-show-archived' +
            (setupIncludeArchived ? ' checked' : '') + '> ' + escapeHtml(strings.showArchived || 'Show archived') + '</label></div>' +
            '<p class="aysa-ai-visibility__muted">' + escapeHtml(strings.entityQualityHint || '') + '</p>' +
            '<div class="aysa-ai-visibility__entity-tabs">' +
            ['alias', 'persona', 'topic', 'scenario', 'competitor', 'claim'].map(function (type, index) {
                return '<button type="button" class="button' + (index === 0 ? ' is-active' : '') +
                    '" data-entity-tab="' + type + '">' + escapeHtml(entityTypeLabel(type)) + ' (' +
                    String((entities[type] || []).length) + ')</button>';
            }).join('') + '</div><div class="aysa-ai-visibility__entity-panel"></div></section>';
        var form = target.querySelector('.aysa-ai-visibility__profile-form');
        form.addEventListener('input', function () {
            window.clearTimeout(setupSaveTimer);
            setupSaveTimer = window.setTimeout(function () { saveProfile(false); }, 800);
        });
        target.querySelector('[data-confirm-profile]').addEventListener('click', function () { saveProfile(true); });
        target.querySelector('[data-show-archived]').addEventListener('change', function (event) {
            setupIncludeArchived = Boolean(event.target.checked);
            loadSetup(true);
        });
        Array.prototype.forEach.call(target.querySelectorAll('[data-entity-tab]'), function (button) {
            button.addEventListener('click', function () {
                Array.prototype.forEach.call(target.querySelectorAll('[data-entity-tab]'), function (tab) {
                    tab.classList.toggle('is-active', tab === button);
                });
                renderEntityPanel(button.getAttribute('data-entity-tab'));
            });
        });
        renderEntityPanel('alias');
    }
    function profilePayload(confirmed) {
        var form = root.querySelector('.aysa-ai-visibility__profile-form');
        var data = new FormData(form);
        return {
            brand_name: String(data.get('brand_name') || '').trim(),
            canonical_domain: String(data.get('canonical_domain') || '').trim(),
            category: String(data.get('category') || '').trim(),
            primary_language: String(data.get('primary_language') || '').trim(),
            description: String(data.get('description') || '').trim(),
            products: splitList(data.get('products')),
            services: splitList(data.get('services')),
            differentiators: splitList(data.get('differentiators')),
            markets: splitList(data.get('markets')),
            locations: splitList(data.get('locations')),
            languages: splitList(data.get('languages')),
            status: confirmed ? 'confirmed' : 'waiting_for_confirmation'
        };
    }
    function saveProfile(confirmed) {
        var status = root.querySelector('.aysa-ai-visibility__save-status');
        var profile = profilePayload(confirmed);
        if (!profile.brand_name) {
            status.textContent = strings.brandRequired || 'Brand name is required.';
            return;
        }
        status.textContent = strings.saving || 'Saving…';
        request('profile_save', {
            profile: profile,
            expected_version: Number((setupData.profile && setupData.profile.version) || 0),
            source_snapshot: {source: 'plugin_ai_visibility_wizard', generated_data_is_proposal: true}
        }).then(function (data) {
            setupData.profile = data.profile;
            status.textContent = confirmed ? (strings.profileConfirmed || 'Profile confirmed.') : (strings.saved || 'Saved.');
            if (confirmed) {
                renderSetup();
            }
        }).catch(function (error) {
            status.textContent = humanError(error);
            if (String(error.message).indexOf('version') !== -1) {
                loadSetup(true);
            }
        });
    }
    function entityName(type, row) {
        return type === 'alias' ? row.alias : (type === 'claim' ? row.claim_text : row.name);
    }
    function entityFormHtml(type, row) {
        row = row || {};
        var nameKey = type === 'alias' ? 'alias' : (type === 'claim' ? 'claim_text' : 'name');
        var html = '<form class="aysa-ai-visibility__entity-form" data-entity-type="' + type + '">' +
            '<input type="hidden" name="id" value="' + escapeAttr(row.id || '') + '">' +
            '<input type="hidden" name="external_key" value="' + escapeAttr(row.external_key || '') + '">' +
            '<input type="hidden" name="version" value="' + escapeAttr(row.version || 0) + '">' +
            setupField('entity_name', type === 'claim' ? (strings.fieldClaim || 'Claim') : (strings.fieldName || 'Name'), row[nameKey] || '', 'text', 'entity-') +
            setupField('entity_description', strings.fieldDescription || 'Description', row.description || '', 'textarea', 'entity-');
        if (type === 'competitor') {
            html += setupField('canonical_domain', strings.fieldCompetitorDomain || 'Competitor domain', row.canonical_domain || '', 'text', 'entity-') +
                '<label><span>' + escapeHtml(strings.fieldClassification || 'Classification') + '</span><select name="classification">' +
                ['unconfirmed', 'direct', 'indirect', 'marketplace', 'publisher', 'sub_brand'].map(function (value) {
                    return '<option value="' + value + '"' + (row.classification === value ? ' selected' : '') + '>' +
                        escapeHtml(mappedLabel('competitorClassLabels', value, value)) + '</option>';
                }).join('') + '</select></label>';
        } else if (type === 'topic') {
            html += setupField('priority', strings.fieldPriority || 'Priority 0–100', row.priority == null ? 50 : row.priority, 'number', 'entity-');
        } else if (type === 'scenario') {
            var topics = (setupData.entities.topic || []).filter(function (item) { return !item.archived; });
            var personas = (setupData.entities.persona || []).filter(function (item) { return !item.archived; });
            html += '<label><span>' + escapeHtml(strings.fieldTopic || 'Topic') + '</span><select name="topic_id"><option value="">—</option>' +
                topics.map(function (item) { return '<option value="' + item.id + '"' + (Number(row.topic_id) === Number(item.id) ? ' selected' : '') + '>' + escapeHtml(item.name) + '</option>'; }).join('') +
                '</select></label><label><span>' + escapeHtml(strings.fieldPersona || 'Persona') + '</span><select name="persona_id"><option value="">—</option>' +
                personas.map(function (item) { return '<option value="' + item.id + '"' + (Number(row.persona_id) === Number(item.id) ? ' selected' : '') + '>' + escapeHtml(item.name) + '</option>'; }).join('') +
                '</select></label><label><span>' + escapeHtml(strings.fieldTestType || 'Test type') + '</span><select name="test_type">' +
                ['discovery', 'recommendation_journey', 'brand_perception', 'competitive_comparison', 'brand_fact_check'].map(function (value) {
                    return '<option value="' + value + '"' + (row.test_type === value ? ' selected' : '') + '>' +
                        escapeHtml(mappedLabel('testTypeLabels', value, value)) + '</option>';
                }).join('') + '</select></label>';
        }
        html += '<label class="aysa-ai-visibility__check"><input type="checkbox" name="confirmed"' +
            ((row.status === 'confirmed' || row.confirmed) ? ' checked' : '') + '> ' +
            escapeHtml(strings.confirmed || 'Confirmed') + '</label>' +
            '<button type="submit" class="button button-primary">' + escapeHtml(strings.saveEntity || 'Save') +
            '</button><button type="button" class="button" data-clear-entity>' + escapeHtml(strings.clear || 'Clear') +
            '</button><span class="aysa-ai-visibility__entity-status" role="status" aria-live="polite"></span></form>';
        return html;
    }
    function renderEntityPanel(type, selected) {
        var panel = root.querySelector('.aysa-ai-visibility__entity-panel');
        var rows = (setupData.entities[type] || []);
        panel.innerHTML = '<div class="aysa-ai-visibility__entity-list">' + (rows.length ? rows.map(function (row) {
            return '<article class="' + (row.archived ? 'is-archived' : '') + '"><div><strong>' +
                escapeHtml(entityName(type, row)) + '</strong><small>' + escapeHtml(mappedLabel(
                    'entityStatusLabels',
                    row.status || (row.confirmed ? 'confirmed' : 'proposed'),
                    strings.setupNeedsAttention || 'Needs attention'
                )) +
                '</small></div><div><button type="button" class="button button-small" data-edit-entity="' + row.id + '">' +
                escapeHtml(strings.edit || 'Edit') + '</button><button type="button" class="button button-small" data-toggle-entity="' +
                row.id + '" data-archived="' + (row.archived ? '1' : '0') + '">' +
                escapeHtml(row.archived ? (strings.restore || 'Restore') : (strings.archive || 'Archive')) +
                '</button></div></article>';
        }).join('') : '<p class="aysa-ai-visibility__muted">' + escapeHtml(strings.noEntities || 'No items yet.') + '</p>') +
            '</div>' + entityFormHtml(type, selected || {});
        panel.querySelector('.aysa-ai-visibility__entity-form').addEventListener('submit', function (event) {
            event.preventDefault();
            saveEntity(type, event.currentTarget);
        });
        panel.querySelector('[data-clear-entity]').addEventListener('click', function () { renderEntityPanel(type); });
        Array.prototype.forEach.call(panel.querySelectorAll('[data-edit-entity]'), function (button) {
            button.addEventListener('click', function () {
                var id = Number(button.getAttribute('data-edit-entity'));
                renderEntityPanel(type, rows.filter(function (row) { return Number(row.id) === id; })[0] || {});
            });
        });
        Array.prototype.forEach.call(panel.querySelectorAll('[data-toggle-entity]'), function (button) {
            button.addEventListener('click', function () {
                request(button.getAttribute('data-archived') === '1' ? 'entity_restore' : 'entity_archive', {
                    profile_id: setupData.profile.id,
                    entity_type: type,
                    entity_id: Number(button.getAttribute('data-toggle-entity'))
                }).then(function () { loadSetup(true, type); }).catch(function (error) {
                    panel.querySelector('.aysa-ai-visibility__entity-status').textContent = humanError(error);
                });
            });
        });
    }
    function saveEntity(type, form) {
        var data = new FormData(form);
        var row = {
            id: Number(data.get('id') || 0),
            external_key: String(data.get('external_key') || ''),
            status: data.get('confirmed') ? 'confirmed' : 'proposed'
        };
        var value = String(data.get('entity_name') || '').trim();
        if (type === 'alias') {
            row.alias = value;
            row.alias_type = 'name';
            row.confirmed = Boolean(data.get('confirmed'));
        } else if (type === 'claim') {
            row.claim_text = value;
            row.source_type = 'manual';
        } else {
            row.name = value;
            row.description = String(data.get('entity_description') || '').trim();
        }
        if (type === 'competitor') {
            row.canonical_domain = String(data.get('canonical_domain') || '').trim();
            row.classification = String(data.get('classification') || 'unconfirmed');
            row.confirmed = Boolean(data.get('confirmed'));
        } else if (type === 'topic') {
            row.priority = Number(data.get('priority') || 50);
        } else if (type === 'scenario') {
            row.topic_id = Number(data.get('topic_id') || 0);
            row.persona_id = Number(data.get('persona_id') || 0);
            row.test_type = String(data.get('test_type') || 'discovery');
        }
        var status = form.querySelector('.aysa-ai-visibility__entity-status');
        status.textContent = strings.saving || 'Saving…';
        request('entity_save', {
            profile_id: setupData.profile.id,
            entity_type: type,
            expected_version: Number(data.get('version') || 0),
            entity: row
        }).then(function () { loadSetup(true, type); }).catch(function (error) {
            status.textContent = humanError(error);
        });
    }
    function loadSetup(force, selectedType) {
        var target = root.querySelector('.aysa-ai-visibility__setup');
        if (!force && setupData) {
            return;
        }
        var finishLoading = beginViewState(target, 'setup');
        request('setup_read', {include_archived: setupIncludeArchived}).then(function (data) {
            if (data.profile) {
                finishLoading();
                setupData = data;
                renderSetup();
                if (selectedType) {
                    var tab = root.querySelector('[data-entity-tab="' + selectedType + '"]');
                    if (tab) { tab.click(); }
                }
                return;
            }
            return request('setup_preview', {existing_context: {}}).then(function (proposal) {
                finishLoading();
                setupData = {profile: proposal.profile || {}, entities: {
                    alias: [], persona: proposal.personas || [], topic: proposal.topics || [],
                    scenario: proposal.scenarios || [], competitor: proposal.competitors || [], claim: proposal.claims || []
                }};
                renderSetup();
            });
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'setup', humanError(error), function () { loadSetup(true); });
        });
    }
    function priorityExplanation(insight) {
        var why = insight.why_detected || {};
        var factors = why.priority_factors || {};
        var parts = [];
        if (why.metric_key) {
            parts.push(metricLabel(why.metric_key) + ': ' + (why.observed_percent == null
                ? (strings.notRecorded || 'Not recorded')
                : String(Number(why.observed_percent).toFixed(1)) + '%'));
        }
        if (why.target_percent != null) {
            parts.push((strings.target || 'Target') + ': ' + String(Number(why.target_percent).toFixed(1)) + '%');
        }
        return parts.join(' · ');
    }
    function baselineContextSummary(context) {
        context = context && typeof context === 'object' ? context : {};
        if (context.baseline_available === false || !context.measurement) {
            return strings.baselineContextUnavailable || 'Baseline context is no longer available for this owned measurement.';
        }
        var measurement = context.measurement || {};
        var sample = context.sample || {};
        return (strings.baselineDate || 'Date') + ': ' + formatInterfaceDate(measurement.completed_at || measurement.started_at) +
            ' · ' + (strings.baselineSample || 'Sample') + ': ' + Number(sample.completed_conversations || 0) +
            ' / ' + Number(sample.planned_conversations || 0);
    }
    function renderBundle(bundle) {
        var target = root.querySelector('.aysa-ai-visibility__action-plan');
        actionPlanBundle = bundle;
        actionPlanApproval = null;
        var items = bundle.items || [];
        var bundleStatus = String(bundle.status || 'draft');
        var controls = bundleStatus === 'draft'
            ? '<button type="button" class="button button-primary" data-prepare-bundle>' +
                escapeHtml(strings.prepareApproval || 'Prepare approval') + '</button>'
            : (bundleStatus === 'approved_for_proposal_dispatch'
                ? '<button type="button" class="button button-primary" data-dispatch-proposals>' +
                    escapeHtml(strings.createProposals || 'Create canonical proposals') + '</button>'
                : '<strong>' + escapeHtml(strings.proposalsCreated || 'Canonical proposals created for review.') + '</strong>');
        target.innerHTML = '<section class="aysa-ai-visibility__bundle"><header><div><h2>' +
            escapeHtml(strings.bundlePreview || 'Approval bundle preview') + '</h2><p>' +
            escapeHtml((strings.bundleVersion || 'Version') + ' ' + String(bundle.version || 1) + ' · ' +
                (strings.risk || 'Risk') + ': ' + mappedLabel('riskLabels', bundle.risk_summary || 'medium', strings.notRecorded || 'Not recorded')) +
            '</p></div><strong>' + escapeHtml(String(bundle.estimated_min_credits || 0) + '–' +
                String(bundle.estimated_max_credits || 0) + ' ' + (strings.credits || 'credits')) +
            '</strong></header><div class="aysa-ai-visibility__bundle-items">' + items.map(function (item) {
                var proposal = item.proposal_payload || {};
                return '<article><h3>' + escapeHtml(laneLabel(item.canonical_lane)) + '</h3><p><strong>' +
                    escapeHtml((strings.canonicalProposalFor || 'Canonical proposal for {lane}')
                        .replace('{lane}', laneLabel(item.canonical_lane))) + '</strong></p><p>' +
                    escapeHtml(proposal.target_url || (strings.targetMissing || 'Target page must be confirmed')) +
                    '</p><dl><dt>' + escapeHtml(strings.verification || 'Verification') + '</dt><dd>' +
                    escapeHtml(strings.verificationRequired || 'Verified readback is required before completion.') + '</dd><dt>' +
                    escapeHtml(strings.rollback || 'Rollback') + '</dt><dd>' +
                    escapeHtml(strings.rollbackAvailable || 'The canonical workflow retains a rollback or recovery path.') +
                    '</dd></dl><details><summary>' + escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
                    escapeHtml([item.canonical_action_key, proposal.verification_model, proposal.rollback_model].filter(Boolean).join(' · ')) +
                    '</code></details></article>';
            }).join('') + '</div><div class="aysa-ai-visibility__form-actions">' + controls +
            '<span class="aysa-ai-visibility__muted">' +
            escapeHtml(strings.proposalOnly || 'Approval creates proposals in canonical AYSA lanes; it does not apply changes.') +
            '</span></div><div class="aysa-ai-visibility__approval" role="status"></div></section>';
        var prepare = target.querySelector('[data-prepare-bundle]');
        if (prepare) {
            prepare.addEventListener('click', function () {
                var status = target.querySelector('.aysa-ai-visibility__approval');
                status.textContent = strings.preparingApproval || 'Preparing exact approval…';
                request('action_plan_approval_prepare', {bundle_id: Number(bundle.id)}).then(function (data) {
                    actionPlanApproval = data.approval_payload;
                    status.innerHTML = '<p><strong>' + escapeHtml(strings.approvalReady || 'Exact bundle is ready for approval.') +
                        '</strong></p><button type="button" class="button button-primary" data-confirm-bundle>' +
                        escapeHtml(strings.approveBundle || 'Approve proposal bundle') + '</button>';
                    status.querySelector('[data-confirm-bundle]').addEventListener('click', confirmBundle);
                }).catch(function (error) { status.textContent = humanError(error); });
            });
        }
        var dispatch = target.querySelector('[data-dispatch-proposals]');
        if (dispatch) {
            dispatch.addEventListener('click', dispatchProposals);
        }
        announceProductState('aysa:aiv:action-plan-rendered', {
            mode: 'bundle',
            baseline_run_batch_id: Number(bundle.baseline_run_batch_id || 0)
        });
    }
    function confirmBundle() {
        if (!actionPlanBundle || !actionPlanApproval) {
            return;
        }
        if (!window.confirm(strings.approvalConfirm || 'Approve this exact proposal bundle? No changes will be applied yet.')) {
            return;
        }
        var target = root.querySelector('.aysa-ai-visibility__approval');
        target.textContent = strings.saving || 'Saving…';
        request('action_plan_approval_confirm', {
            bundle_id: Number(actionPlanBundle.id),
            approval_payload: actionPlanApproval,
            actor: {type: 'wordpress_user'}
        }).then(function (data) {
            actionPlanApproval = null;
            renderBundle(data.bundle);
        }).catch(function (error) { target.textContent = humanError(error); });
    }
    function dispatchProposals() {
        if (!actionPlanBundle || String(actionPlanBundle.status) !== 'approved_for_proposal_dispatch') {
            return;
        }
        var target = root.querySelector('.aysa-ai-visibility__approval');
        target.textContent = strings.creatingProposals || 'Creating canonical review proposals…';
        request('action_plan_proposals_dispatch', {
            bundle_id: Number(actionPlanBundle.id),
            actor: {type: 'wordpress_user'}
        }).then(function (data) {
            renderBundle(data.bundle);
            var status = root.querySelector('.aysa-ai-visibility__approval');
            status.innerHTML = '<p><strong>' + escapeHtml(strings.proposalsCreated || 'Canonical proposals created for review.') +
                '</strong></p><p>' + escapeHtml(strings.noApplyPerformed || 'No provider, wallet or apply operation was performed.') + '</p>';
        }).catch(function (error) { target.textContent = humanError(error); });
    }
    function renderInsights(profile, insights, baselineContexts) {
        var target = root.querySelector('.aysa-ai-visibility__action-plan');
        baselineContexts = baselineContexts && typeof baselineContexts === 'object' ? baselineContexts : {};
        if (!insights.length) {
            target.innerHTML = '<h2>' + escapeHtml(strings.noInsights || 'No evidence-backed recommendations yet.') +
                '</h2><p>' + escapeHtml(strings.runFirst || 'Complete a measurement to generate the Action Plan.') + '</p>';
            announceProductState('aysa:aiv:action-plan-rendered', {mode: 'empty', baseline_run_batch_ids: []});
            return;
        }
        target.innerHTML = '<form class="aysa-ai-visibility__insights"><header><div><h2>' +
            escapeHtml(strings.recommendations || 'Evidence-backed recommendations') + '</h2><p>' +
            escapeHtml(strings.selectRecommendations || 'Select recommendations for one versioned approval bundle.') +
            '</p></div><button type="submit" class="button button-primary">' +
            escapeHtml(strings.buildBundle || 'Build approval bundle') + '</button></header><div class="aysa-ai-visibility__insight-list">' +
            insights.map(function (insight) {
                var refs = insight.evidence_refs || [];
                var baselineContext = baselineContexts[String(Number(insight.run_batch_id || 0))] || {};
                var baselineMeasurement = baselineContext.measurement || {};
                var baselineComparison = baselineContext.comparison || {};
                var inputId = 'aysa-aiv-insight-' + Number(insight.id);
                return '<article class="aysa-ai-visibility__insight"><label for="' + inputId + '"><input id="' + inputId +
                    '" type="checkbox" name="insight_ids" value="' + Number(insight.id) + '"><span><span class="aysa-ai-visibility__badge">' +
                    escapeHtml(priorityLabel(insight.priority_band) + ' · ' + String(Number(insight.priority_score || 0).toFixed(1))) +
                    '</span><strong>' + escapeHtml(insightLabel(insight)) + '</strong><small>' +
                    escapeHtml(priorityExplanation(insight)) + '</small><p>' + escapeHtml(insightExplanation(insight)) +
                    '</p><small>' + escapeHtml((strings.baselineLabel || 'Baseline') + ' #' + Number(insight.run_batch_id || 0) +
                        ' · ' + String(refs.length) + ' ' + (strings.evidenceRefs || 'evidence references') +
                        ' · ' + laneLabel(insight.canonical_lane || 'monitoring')) + '</small><small>' +
                    escapeHtml(baselineContextSummary(baselineContext)) + '</small><small>' +
                    escapeHtml((strings.target || 'Target') + ': ' +
                        (insight.target_url || strings.targetMissing || 'Target page must be confirmed')) + '</small><small>' +
                    escapeHtml((strings.recommendationOnlyState || 'Recommendation only — no changes have been applied.') + ' · ' +
                        (strings.costQuotedBeforeApproval || 'Any execution cost is quoted before approval.')) +
                    '</small></span></label><details class="aysa-ai-visibility__evidence-technical"><summary>' +
                    escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><span>' +
                    escapeHtml([insight.insight_key, insight.title, insight.explanation, (insight.why_detected || {}).priority_factors &&
                        (insight.why_detected || {}).priority_factors.formula_version,
                        (strings.baselineCohort || 'Cohort') + ': ' + (baselineMeasurement.cohort_hash || strings.notRecorded || 'Not recorded'),
                        (strings.baselineMethodology || 'Methodology') + ': ' + (baselineMeasurement.methodology_version || strings.notRecorded || 'Not recorded'),
                        baselineComparison.series_break_reason
                            ? (strings.technicalReason || 'Technical reason') + ': ' + baselineComparison.series_break_reason
                            : null].filter(Boolean).join(' · ')) +
                    '</span></details></article>';
            }).join('') + '</div><div class="aysa-ai-visibility__action-status" role="status" aria-live="polite"></div></form>';
        target.querySelector('form').addEventListener('submit', function (event) {
            event.preventDefault();
            var selected = Array.prototype.map.call(
                target.querySelectorAll('input[name="insight_ids"]:checked'),
                function (input) { return Number(input.value); }
            );
            var status = target.querySelector('.aysa-ai-visibility__action-status');
            if (!selected.length) {
                status.textContent = strings.selectAtLeastOne || 'Select at least one recommendation.';
                return;
            }
            var chosen = insights.filter(function (insight) { return selected.indexOf(Number(insight.id)) !== -1; });
            var batches = chosen.map(function (insight) { return Number(insight.run_batch_id); })
                .filter(function (value, index, all) { return all.indexOf(value) === index; });
            if (batches.length !== 1) {
                status.textContent = strings.singleBaseline || 'Choose recommendations from one baseline run.';
                return;
            }
            status.textContent = strings.buildingBundle || 'Building exact bundle…';
            request('action_plan_build', {
                profile_id: Number(profile.id),
                baseline_run_batch_id: batches[0],
                insight_ids: selected,
                actor: {type: 'wordpress_user'}
            }).then(function (data) { renderBundle(data.bundle); })
                .catch(function (error) { status.textContent = humanError(error); });
        });
        announceProductState('aysa:aiv:action-plan-rendered', {
            mode: 'insights',
            baseline_run_batch_ids: insights.map(function (insight) { return Number(insight.run_batch_id || 0); })
                .filter(function (value, index, all) { return value > 0 && all.indexOf(value) === index; })
        });
    }
    function loadActionPlan() {
        var target = root.querySelector('.aysa-ai-visibility__action-plan');
        var finishLoading = beginViewState(target, 'actions');
        request('setup_read', {include_archived: false}).then(function (setup) {
            if (!setup.profile) {
                finishLoading();
                renderInsights({}, [], {});
                return;
            }
            return Promise.all([
                request('insights_list', {profile_id: Number(setup.profile.id), limit: 100, offset: 0}),
                request('action_plan_read', {profile_id: Number(setup.profile.id)})
            ]).then(function (results) {
                finishLoading();
                var latest = results[1].bundle || {};
                if (latest.id && latest.status !== 'invalidated') {
                    renderBundle(latest);
                } else {
                    renderInsights(setup.profile, results[0].insights || [], results[0].baseline_contexts || {});
                }
            });
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'actions', humanError(error), loadActionPlan);
        });
    }
    function renderImpact(interventions) {
        var target = root.querySelector('.aysa-ai-visibility__impact');
        if (!interventions.length) {
            target.innerHTML = '<h2>' + escapeHtml(strings.noInterventions || 'No verified intervention yet.') +
                '</h2><p>' + escapeHtml(strings.interventionHint || 'Impact appears after canonical lane apply and readback are complete.') + '</p>';
            return;
        }
        target.innerHTML = interventions.map(function (intervention) {
            var checks = intervention.impact_checks || [];
            var check = checks.length ? checks[checks.length - 1] : {};
            var deltas = check.metric_deltas || {};
            var deltaKeys = Object.keys(deltas);
            var deltaRows = deltaKeys.map(function (key) {
                var delta = deltas[key] || {};
                return '<div><strong>' + escapeHtml(metricLabel(key)) + '</strong><span>' +
                    escapeHtml(String(Number(delta.before_percent || 0).toFixed(1)) + '% → ' +
                        String(Number(delta.after_percent || 0).toFixed(1)) + '%') +
                    '</span><small>' + escapeHtml((Number(delta.absolute_delta_points || 0) >= 0 ? '+' : '') +
                        String(Number(delta.absolute_delta_points || 0).toFixed(1)) + ' pp') + '</small></div>';
            }).join('');
            var canAssess = check && !check.completed_at && latestRunId > 0 &&
                Number(latestRunId) !== Number(intervention.baseline_run_batch_id);
            var impactKey = String(check.outcome || '');
            var statusKey = String(intervention.status || 'monitoring');
            var impactLabel = impactKey
                ? mappedLabel('impactOutcomeLabels', impactKey, strings.notRecorded || 'Not recorded')
                : mappedLabel('interventionStatusLabels', statusKey, strings.notRecorded || 'Not recorded');
            var impactStatement = impactKey
                ? mappedLabel('impactStatementLabels', impactKey, strings.waitingImpact || 'Waiting for a comparable after run.')
                : (strings.waitingImpact || 'Waiting for a comparable after run.');
            return '<article class="aysa-ai-visibility__intervention"><header><div><h2>' +
                escapeHtml((strings.intervention || 'Intervention') + ' #' + String(intervention.id)) +
                '</h2><p>' + escapeHtml(String(intervention.deployed_at || '')) + '</p></div><span class="aysa-ai-visibility__badge">' +
                escapeHtml(impactLabel) +
                '</span></header><div class="aysa-ai-visibility__impact-deltas">' + deltaRows +
                '</div><p>' + escapeHtml(impactStatement) +
                '</p><details><summary>' + escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><p>' +
                escapeHtml([statusKey, impactKey, check.association_statement].concat(deltaKeys).filter(Boolean).join(' · ')) +
                '</p></details>' + (canAssess ? '<button type="button" class="button" data-assess-impact="' +
                    Number(intervention.id) + '">' + escapeHtml(strings.assessLatest || 'Assess latest comparable run') + '</button>' : '') +
                '<div class="aysa-ai-visibility__impact-status" role="status"></div></article>';
        }).join('');
        Array.prototype.forEach.call(target.querySelectorAll('[data-assess-impact]'), function (button) {
            button.addEventListener('click', function () {
                var status = button.parentNode.querySelector('.aysa-ai-visibility__impact-status');
                status.textContent = strings.assessing || 'Assessing durable metrics…';
                request('impact_assess', {
                    intervention_id: Number(button.getAttribute('data-assess-impact')),
                    after_run_batch_id: Number(latestRunId)
                }).then(loadImpact).catch(function (error) { status.textContent = humanError(error); });
            });
        });
    }
    function loadImpact() {
        var target = root.querySelector('.aysa-ai-visibility__impact');
        var finishLoading = beginViewState(target, 'impact');
        request('setup_read', {include_archived: false}).then(function (setup) {
            if (!setup.profile) {
                finishLoading();
                renderImpact([]);
                return;
            }
            return request('interventions_read', {
                profile_id: Number(setup.profile.id),
                limit: 20
            }).then(function (data) {
                finishLoading();
                renderImpact(data.interventions || []);
            });
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'impact', humanError(error), loadImpact);
        });
    }
    function contentAnalyzerForm(profile) {
        var target = root.querySelector('.aysa-ai-visibility__content-analyzer');
        target.innerHTML = '<section class="aysa-ai-visibility__analyzer-shell"><h2>' +
            escapeHtml(strings.contentAnalyzerTitle || 'Content Analyzer AEO/GEO') + '</h2><p>' +
            escapeHtml(strings.contentAnalyzerHint || 'Analyze a controlled content snapshot without side effects.') +
            '</p><form class="aysa-ai-visibility__analyzer-form"><div class="aysa-ai-visibility__form-grid">' +
            '<label>' + escapeHtml(strings.contentUrl || 'Canonical page URL') + '<input type="url" name="target_url" placeholder="https://' +
            escapeAttr(profile.canonical_domain || '') + '/page"></label><label>' +
            escapeHtml(strings.contentTitle || 'Page title') + '<input type="text" name="title" maxlength="500"></label>' +
            '<label class="is-wide">' + escapeHtml(strings.contentMeta || 'Meta description') + '<textarea name="meta_description" rows="2"></textarea></label>' +
            '<label class="is-wide">' + escapeHtml(strings.contentBody || 'Rendered content or text snapshot') + '<textarea name="content_text" rows="12" required></textarea></label>' +
            '<label>' + escapeHtml(strings.contentQuestions || 'Questions, one per line') + '<textarea name="questions" rows="5"></textarea></label>' +
            '<label>' + escapeHtml(strings.contentAnswers || 'Direct answers, one per line') + '<textarea name="direct_answers" rows="5"></textarea></label>' +
            '<label>' + escapeHtml(strings.contentKeywords || 'Target terms, one per line') + '<textarea name="target_keywords" rows="4"></textarea></label>' +
            '</div><div class="aysa-ai-visibility__form-actions"><button type="submit" class="button button-primary">' +
            escapeHtml(strings.analyzeContent || 'Analyze content snapshot') + '</button><span class="aysa-ai-visibility__analyzer-status" role="status"></span></div></form>' +
            '<div class="aysa-ai-visibility__analyzer-report"></div></section>';
        target.querySelector('form').addEventListener('submit', function (event) {
            event.preventDefault();
            var form = event.currentTarget;
            var status = form.querySelector('.aysa-ai-visibility__analyzer-status');
            var button = form.querySelector('button[type="submit"]');
            var values = new FormData(form);
            var lines = function (name) {
                return String(values.get(name) || '').split(/\r?\n/).map(function (value) { return value.trim(); }).filter(Boolean);
            };
            var url = String(values.get('target_url') || '').trim();
            button.disabled = true;
            status.textContent = strings.analyzingContent || 'Analyzing the supplied snapshot…';
            request('content_analyze', {
                profile_id: Number(profile.id || 0),
                baseline_run_batch_id: Number(latestRunId || 0),
                snapshot: {
                    source_type: url ? 'url' : 'text',
                    target_url: url,
                    title: String(values.get('title') || ''),
                    meta_description: String(values.get('meta_description') || ''),
                    content_text: String(values.get('content_text') || ''),
                    questions: lines('questions'),
                    direct_answers: lines('direct_answers'),
                    target_keywords: lines('target_keywords')
                }
            }).then(function (result) {
                status.textContent = '';
                renderContentAnalyzerReport(result);
            }).catch(function (error) {
                status.textContent = humanError(error);
            }).finally(function () {
                button.disabled = false;
            });
        });
    }
    function renderContentAnalyzerReport(result) {
        var report = root.querySelector('.aysa-ai-visibility__analyzer-report');
        var summary = result.summary || {};
        var scores = ['brand_favorability', 'question_coverage', 'citation_standing', 'brand_fit'].map(function (key) {
            var value = summary[key];
            return '<article><h3>' + escapeHtml(mappedLabel('contentScoreLabels', key, strings.recordedMetric || 'Recorded metric')) + '</h3><strong>' +
                escapeHtml(value == null ? (strings.insufficientData || 'Insufficient data') : String(value) + '%') + '</strong></article>';
        }).join('');
        var checks = (result.checks || []).map(function (check) {
            var failed = check.status === 'needs_improvement';
            var checkLabel = mappedLabel('contentCheckLabels', check.check_key, strings.recordedMetric || 'Recorded check');
            var guidance = mappedLabel('contentCheckGuidance', check.check_key,
                strings.measurementNotReady || 'Review this recorded check.');
            var statusLabel = mappedLabel('contentCheckStatusLabels', check.status,
                failed ? (strings.needsImprovement || 'Needs improvement') : (strings.passed || 'Passed'));
            return '<article class="aysa-ai-visibility__analyzer-check ' + (failed ? 'needs-improvement' : 'is-pass') + '"><header><h3>' +
                (failed ? '<label><input type="checkbox" data-analyzer-check="' + escapeAttr(check.id || '') + '"> ' : '') +
                escapeHtml(checkLabel) + (failed ? '</label>' : '') + '</h3><span class="aysa-ai-visibility__badge">' +
                escapeHtml(statusLabel) + '</span></header><p>' + escapeHtml(guidance) + '</p><dl><dt>' +
                escapeHtml(strings.evidenceLabel || 'Evidence') + '</dt><dd>' + escapeHtml(check.evidence || '—') + '</dd><dt>' +
                escapeHtml(strings.estimatedImpact || 'Estimated impact') + '</dt><dd>' +
                escapeHtml(mappedLabel('contentImpactLabels', check.estimated_impact, strings.notRecorded || 'Not recorded')) +
                ' · ' + escapeHtml(laneLabel(check.canonical_lane || 'monitoring')) + ' · ' +
                escapeHtml(String(Math.round(Number(check.confidence || 0) * 100))) + '%</dd></dl><details><summary>' +
                escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><p>' +
                escapeHtml([check.check_key, check.status, check.finding, check.why_it_matters,
                    check.recommended_change, check.canonical_lane].filter(Boolean).join(' · ')) +
                '</p></details></article>';
        }).join('');
        var planAction = result.analysis_run_id ? '<div class="aysa-ai-visibility__form-actions"><button type="button" class="button button-primary" data-analyzer-add-plan ' +
            (result.baseline_run_batch_id ? '' : 'disabled') + '>' + escapeHtml(strings.addSelectedToPlan || 'Add selected recommendations to Action Plan') +
            '</button><span class="aysa-ai-visibility__analyzer-plan-status" role="status">' +
            (result.baseline_run_batch_id ? '' : escapeHtml(strings.baselineRequired || 'Complete a measurement first.')) + '</span></div>' : '';
        report.innerHTML = '<div class="aysa-ai-visibility__analyzer-scores">' + scores + '</div><p class="aysa-ai-visibility__muted">' +
            escapeHtml(String(summary.passed || 0) + ' ' + (strings.passedChecks || 'passed checks') + ' · ' +
                String(summary.needs_improvement || 0) + ' ' + (strings.checksNeedImprovement || 'checks need improvement')) +
            '</p><details><summary>' + escapeHtml(strings.technicalDetails || 'Technical details') + '</summary><code>' +
            escapeHtml(result.analyzer_version || '') + '</code></details><div class="aysa-ai-visibility__analyzer-checks">' +
            checks + '</div>' + planAction;
        var add = report.querySelector('[data-analyzer-add-plan]');
        if (add) {
            add.addEventListener('click', function () {
                var ids = Array.prototype.map.call(report.querySelectorAll('[data-analyzer-check]:checked'), function (input) {
                    return Number(input.getAttribute('data-analyzer-check'));
                }).filter(Boolean);
                var status = report.querySelector('.aysa-ai-visibility__analyzer-plan-status');
                if (!ids.length) {
                    status.textContent = strings.selectAtLeastOne || 'Select at least one recommendation.';
                    return;
                }
                add.disabled = true;
                status.textContent = strings.addingToPlan || 'Adding proposal-only recommendations…';
                request('content_analyzer_select', {analysis_run_id: Number(result.analysis_run_id), check_ids: ids}).then(function () {
                    status.textContent = strings.addedToPlan || 'Recommendations added to Action Plan.';
                }).catch(function (error) {
                    status.textContent = humanError(error);
                    add.disabled = false;
                });
            });
        }
    }
    function loadContentAnalyzer() {
        var target = root.querySelector('.aysa-ai-visibility__content-analyzer');
        if (target.querySelector('form')) {
            return;
        }
        var finishLoading = beginViewState(target, 'content_analyzer');
        request('setup_read', {include_archived: false}).then(function (setup) {
            if (!setup.profile) {
                finishLoading();
                target.innerHTML = '<p>' + escapeHtml(strings.measurementNotReady || 'Setup is not ready.') + '</p>';
                return;
            }
            finishLoading();
            contentAnalyzerForm(setup.profile);
        }).catch(function (error) {
            finishLoading();
            renderViewFailure(target, 'content_analyzer', humanError(error), loadContentAnalyzer);
        });
    }
    function activateView(view) {
        Array.prototype.forEach.call(root.querySelectorAll('[data-view]'), function (button) {
            var active = button.getAttribute('data-view') === view;
            button.classList.toggle('is-active', active);
            button.setAttribute('aria-selected', active ? 'true' : 'false');
            button.setAttribute('tabindex', active ? '0' : '-1');
        });
        Array.prototype.forEach.call(root.querySelectorAll('[data-view-panel]'), function (panel) {
            panel.hidden = panel.getAttribute('data-view-panel') !== view;
        });
        if (view === 'conversations') {
            loadEvidence(1);
        } else if (view === 'measurement') {
            loadMeasurement();
        } else if (view === 'trends') {
            loadTrends();
        } else if (view === 'signals') {
            loadSignals();
        } else if (view === 'content-analyzer') {
            loadContentAnalyzer();
        } else if (view === 'action-plan') {
            loadActionPlan();
        } else if (view === 'impact') {
            loadImpact();
        } else if (view === 'setup') {
            loadSetup();
        }
    }
    function load() {
        state.hidden = false;
        state.setAttribute('aria-busy', 'true');
        state.innerHTML = '<h2>' + escapeHtml(strings.checkingTitle || 'Checking configuration…') + '</h2><p>' +
            escapeHtml(strings.checkingCopy || 'No providers are run and no credits are used.') + '</p>';
        Promise.all([request('status', {}), request('overview_read', {}), request('runs_list', {limit: 20})]).then(function (results) {
            var status = results[0];
            applyInterfaceLanguage(status.interface_language || aysaAiVisibility.locale || 'ro');
            reprocessExtractionEnabled = Boolean(status && status.flags && status.flags.reprocess_extraction_enabled);
            renderEngines(status);
            availableRuns = results[2].runs || [];
            renderOverview(results[1], availableRuns);
            state.hidden = true;
            state.setAttribute('aria-busy', 'false');
            activateView('overview');
        }).catch(function (error) {
            renderError(error.name === 'AbortError' ? (strings.timeout || 'The request timed out.') : humanError(error));
        });
    }
    applyInterfaceLanguage(aysaAiVisibility.locale || 'ro');
    root.addEventListener('aysa:aiv:run-selected', function (event) {
        var runBatchId = Number((event.detail || {}).run_batch_id || 0);
        if (!runBatchId) {
            return;
        }
        var panel = root.querySelector('[data-view-panel="overview"]');
        panel.setAttribute('aria-busy', 'true');
        request('overview_read', {run_batch_id: runBatchId}).then(function (data) {
            renderOverview(data, availableRuns);
        }).catch(function (error) {
            renderError(error.name === 'AbortError' ? (strings.timeout || 'The request timed out.') : humanError(error));
        }).finally(function () {
            panel.setAttribute('aria-busy', 'false');
        });
    });
    Array.prototype.forEach.call(root.querySelectorAll('[data-view]'), function (button) {
        button.addEventListener('click', function () { activateView(button.getAttribute('data-view')); });
        button.addEventListener('keydown', function (event) {
            var keys = ['ArrowLeft', 'ArrowRight', 'Home', 'End'];
            if (keys.indexOf(event.key) === -1) {
                return;
            }
            var buttons = Array.prototype.slice.call(root.querySelectorAll('[data-view]'));
            var index = buttons.indexOf(button);
            if (index < 0) {
                return;
            }
            event.preventDefault();
            var nextIndex = event.key === 'Home'
                ? 0
                : (event.key === 'End'
                    ? buttons.length - 1
                    : (index + (event.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length);
            buttons[nextIndex].focus();
            activateView(buttons[nextIndex].getAttribute('data-view'));
        });
    });
    load();
}());
