(function () {
    'use strict';

    var root = document.getElementById('aysa-ai-visibility-app');
    var config = window.aysaAiVisibility || {};
    var canonicalTabs = root ? root.querySelector('[data-aiv-canonical-tabs]') : null;
    if (!root || !canonicalTabs) {
        return;
    }

    var displayedRunId = 0;
    var actualLatestRunId = 0;
    var latestOverviewDetail = null;
    var latestActionDetail = null;
    var productButtons = {};

    function languageBase() {
        return String(root.getAttribute('lang') || config.locale || 'ro').toLowerCase().replace(/_/g, '-').split('-')[0];
    }

    function shell() {
        var packs = config.shellByLanguage || {};
        return packs[languageBase()] || packs.en || {};
    }

    function mainStrings() {
        var packs = config.stringsByLanguage || {};
        return packs[languageBase()] || packs.en || config.strings || {};
    }

    function element(name, className, text) {
        var node = document.createElement(name);
        if (className) {
            node.className = className;
        }
        if (text !== undefined) {
            node.textContent = String(text);
        }
        return node;
    }

    function canonicalButton(view) {
        return canonicalTabs.querySelector('[data-view="' + view + '"]');
    }

    function addNavigationButton(container, view, labelKey, className) {
        var button = element('button', className || 'aiv-product-nav__item');
        button.type = 'button';
        button.id = 'aysa-aiv-product-' + view;
        button.setAttribute('data-aiv-product-target', view);
        button.setAttribute('data-aiv-product-label', labelKey);
        button.addEventListener('click', function () {
            var target = canonicalButton(view);
            if (target) {
                target.click();
            }
        });
        container.appendChild(button);
        productButtons[view] = button;
        var panel = root.querySelector('[data-view-panel="' + view + '"]');
        if (panel) {
            button.setAttribute('aria-controls', panel.id);
            panel.setAttribute('aria-labelledby', button.id);
        }
        return button;
    }

    function buildNavigation() {
        var nav = element('div', 'aiv-product-nav');
        nav.setAttribute('role', 'navigation');
        nav.setAttribute('aria-label', shell().sections || 'AI Visibility');

        var primary = element('div', 'aiv-product-nav__primary');
        [
            ['overview', 'overview'],
            ['conversations', 'conversations'],
            ['action-plan', 'actionPlan'],
            ['setup', 'setup']
        ].forEach(function (item) {
            addNavigationButton(primary, item[0], item[1]);
        });
        nav.appendChild(primary);

        var actions = element('div', 'aiv-product-nav__actions');
        addNavigationButton(actions, 'measurement', 'measurement', 'button button-primary aiv-product-nav__measure');
        var advanced = element('details', 'aiv-product-nav__advanced');
        var summary = element('summary', 'button');
        summary.setAttribute('data-aiv-product-label', 'advanced');
        advanced.appendChild(summary);
        var menu = element('div', 'aiv-product-nav__advanced-menu');
        [
            ['trends', 'trends'],
            ['signals', 'signals'],
            ['content-analyzer', 'contentAnalyzer'],
            ['commerce', 'commerce'],
            ['correlation', 'correlation'],
            ['knowledge-base', 'knowledgeBase'],
            ['impact', 'impact']
        ].forEach(function (item) {
            var button = addNavigationButton(menu, item[0], item[1]);
            button.addEventListener('click', function () { advanced.open = false; });
        });
        advanced.appendChild(menu);
        advanced.addEventListener('keydown', function (event) {
            if (event.key !== 'Escape' || !advanced.open) { return; }
            event.preventDefault();
            advanced.open = false;
            summary.focus();
        });
        actions.appendChild(advanced);
        nav.appendChild(actions);

        canonicalTabs.parentNode.insertBefore(nav, canonicalTabs);
        canonicalTabs.hidden = true;
        root.classList.add('aiv-product-ready');
        updateLabels();
        syncNavigation();
    }

    function updateLabels() {
        var labels = shell();
        Array.prototype.forEach.call(root.querySelectorAll('[data-aiv-product-label]'), function (node) {
            var key = node.getAttribute('data-aiv-product-label');
            node.textContent = labels[key] || key;
        });
        var nav = root.querySelector('.aiv-product-nav');
        if (nav) {
            nav.setAttribute('aria-label', labels.sections || 'AI Visibility');
        }
    }

    function syncNavigation() {
        Object.keys(productButtons).forEach(function (view) {
            var canonical = canonicalButton(view);
            var active = canonical && canonical.getAttribute('aria-selected') === 'true';
            productButtons[view].classList.toggle('is-active', Boolean(active));
            if (active) {
                productButtons[view].setAttribute('aria-current', 'page');
            } else {
                productButtons[view].removeAttribute('aria-current');
            }
        });
    }

    function valueRow(label, value) {
        var wrapper = element('div', 'aiv-product-context__value');
        wrapper.appendChild(element('dt', '', label));
        wrapper.appendChild(element('dd', '', value));
        return wrapper;
    }

    function runSelector(runs, measurement, latest) {
        runs = Array.isArray(runs) ? runs : [];
        var profileId = Number((latest || {}).brand_profile_id || 0);
        runs = runs.filter(function (run) {
            return !profileId || Number(run.brand_profile_id || 0) === profileId;
        });
        if (runs.length <= 1) { return null; }
        var label = element('label', 'aiv-product-context__selector');
        label.appendChild(element('span', '', shell().chooseMeasurement || 'Choose measurement'));
        var select = element('select');
        runs.forEach(function (run) {
            var option = element('option', '', '#' + Number(run.id || 0) + ' · ' + formatDate(run.completed_at || run.started_at));
            option.value = String(Number(run.id || 0));
            option.selected = Number(run.id || 0) === displayedRunId;
            select.appendChild(option);
        });
        select.addEventListener('change', function () {
            root.dispatchEvent(new CustomEvent('aysa:aiv:run-selected', {
                detail: {run_batch_id: Number(select.value || 0)}
            }));
        });
        label.appendChild(select);
        return label;
    }

    function statusLabel(latest) {
        var strings = mainStrings();
        var state = String((latest && latest.state) || '');
        if (state === 'complete') { return strings.runComplete || 'Complete'; }
        if (state === 'partial') { return strings.runPartial || 'Partial'; }
        if (state === 'failed') { return strings.runFailed || 'Needs attention'; }
        if (state === 'cancelled') { return strings.measurementCancelled || 'Cancelled'; }
        return strings.runInProgress || 'In progress';
    }

    function engineNames(measurement) {
        var strings = mainStrings();
        var labels = strings.engineLabels || {};
        var keys = Array.isArray(measurement.engine_keys) ? measurement.engine_keys : [];
        return keys.length ? keys.map(function (key) {
            return labels[key] || labels[String(key).replace(/^dataforseo_/, '')] || strings.recordedEngine || 'Recorded answer engine';
        }).join(', ') : '—';
    }

    function verdictLabel(context) {
        var labels = shell();
        var key = String(((context || {}).verdict || {}).key || 'no_measurement');
        return ({
            no_measurement: labels.verdictNoMeasurement,
            no_metrics: labels.verdictNoMetrics,
            measurement_complete_sample_insufficient: labels.verdictExploratory,
            recommended: labels.verdictRecommended,
            cited_not_recommended: labels.verdictCitedNotRecommended,
            mentioned_not_recommended: labels.verdictMentionedNotRecommended,
            not_visible: labels.verdictNotVisible
        })[key] || labels.verdictNoMetrics || 'No result is available yet.';
    }

    function actionLabel(action) {
        var labels = mainStrings().insightLabels || {};
        return labels[action.insight_key] || action.title || action.insight_key || '—';
    }

    function actionMetricLabel(key) {
        var strings = mainStrings();
        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,
            first_party_citation_rate: strings.metricCitationRate,
            fact_accuracy: strings.metricFactAccuracy
        })[String(key || '')] || shell().notRecorded || 'Not recorded';
    }

    function percentOrUnavailable(value) {
        return value === null || value === undefined || value === ''
            ? (shell().notRecorded || 'Not recorded')
            : Number(value).toFixed(1).replace(/\.0$/, '') + '%';
    }

    function renderNextActions(panel, run, actions) {
        var previous = panel.querySelector('.aiv-product-actions');
        if (previous) { previous.remove(); }
        actions = Array.isArray(actions) ? actions : [];
        if (!actions.length) { return; }
        var labels = shell();
        var strings = mainStrings();
        var section = element('section', 'aiv-product-actions');
        var header = element('header', 'aiv-product-actions__header');
        header.appendChild(element('h2', '', labels.nextActions || 'Next actions'));
        var open = element('button', 'button', labels.openActions || 'Open Actions');
        open.type = 'button';
        open.addEventListener('click', function () {
            var target = canonicalButton('action-plan');
            if (target) { target.click(); }
        });
        header.appendChild(open);
        section.appendChild(header);
        var list = element('ol', 'aiv-product-actions__list');
        actions.forEach(function (action) {
            var item = element('li');
            item.appendChild(element('strong', '', actionLabel(action)));
            item.appendChild(element('span', '', (labels.baseline || 'Baseline') + ' #' + Number(action.baseline_run_batch_id || 0) +
                ' · ' + Number(action.evidence_count || 0) + ' ' + (labels.evidenceCount || 'evidence items')));
            item.appendChild(element('span', '', (labels.metric || 'Metric') + ': ' + actionMetricLabel(action.metric_key) +
                ' · ' + (labels.currentValue || 'Current') + ': ' + percentOrUnavailable(action.current_value_percent) +
                ' → ' + (labels.targetValue || 'Target') + ': ' + percentOrUnavailable(action.target_value_percent)));
            item.appendChild(element('span', '', (strings.laneLabels || {})[action.canonical_lane] || action.canonical_lane || '—'));
            item.appendChild(element('span', '', (labels.targetPage || 'Target page') + ': ' +
                (action.target_url || labels.targetToConfirm || 'To be confirmed in the canonical workflow')));
            item.appendChild(element('small', '', (labels.proposalOnlyState || 'Recommendation only — no changes applied') +
                ' · ' + (labels.costBeforeApproval || 'Cost is calculated before approval')));
            list.appendChild(item);
        });
        section.appendChild(list);
        var context = panel.querySelector('.aiv-product-context');
        panel.insertBefore(section, context ? context.nextSibling : panel.firstChild);
    }

    function formatDate(value) {
        if (!value) { return '—'; }
        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() === 'ro' ? 'ro-RO' : 'en-GB', {
            dateStyle: 'medium', timeStyle: 'short'
        }).format(parsed);
    }

    function renderOverviewContext(detail) {
        latestOverviewDetail = detail || {};
        var panel = root.querySelector('[data-view-panel="overview"]');
        var run = panel ? panel.querySelector('.aysa-ai-visibility__run') : null;
        if (!panel || !run) { return; }
        var previous = panel.querySelector('.aiv-product-context');
        if (previous) { previous.remove(); }

        var labels = shell();
        var latest = detail.latest_run || null;
        var context = detail.product_context || {};
        var measurement = context.measurement || {};
        var sample = context.sample || {};
        var comparison = context.comparison || {};
        var billing = context.billing || {};
        displayedRunId = Number((measurement && measurement.run_batch_id) || (latest && latest.id) || 0);
        actualLatestRunId = Number(measurement.latest_run_batch_id || displayedRunId || 0);

        var card = element('section', 'aiv-product-context');
        card.setAttribute('aria-label', labels.currentMeasurement || 'Current measurement');
        var header = element('header', 'aiv-product-context__header');
        var heading = element('div');
        var resultLabel = measurement.is_latest === false
            ? (labels.selectedResult || 'Selected result')
            : (labels.latestResult || 'Latest result');
        heading.appendChild(element('span', 'aiv-product-context__eyebrow', measurement.is_latest === false
            ? (labels.selectedMeasurement || 'Selected measurement')
            : (labels.currentMeasurement || 'Current measurement')));
        heading.appendChild(element('h2', '', displayedRunId ? resultLabel + ' #' + displayedRunId : resultLabel));
        header.appendChild(heading);
        var selector = runSelector(detail.runs || [], measurement, latest);
        if (selector) { header.appendChild(selector); }
        if (latest) { header.appendChild(element('span', 'aiv-product-context__status', statusLabel(latest))); }
        card.appendChild(header);
        card.appendChild(element('p', 'aiv-product-context__verdict', verdictLabel(context)));

        if (!latest) {
            card.appendChild(element('p', 'aiv-product-context__notice', labels.noMeasurementContext || 'No measurement context is available.'));
        } else {
            var planned = Number(sample.planned_conversations != null ? sample.planned_conversations : (detail.coverage || {}).planned || 0);
            var completed = Number(sample.completed_conversations != null ? sample.completed_conversations : (detail.coverage || {}).completed || 0);
            var values = element('dl', 'aiv-product-context__values');
            values.appendChild(valueRow(labels.engine || 'Engine', engineNames(measurement)));
            values.appendChild(valueRow(labels.sample || 'Sample', completed + ' / ' + planned + ' · ' +
                Number(measurement.scenario_count || 0) + ' ' + String(Number(measurement.scenario_count || 0) === 1
                    ? (labels.scenarioSingular || 'scenario')
                    : (labels.scenarios || 'scenarios')).toLowerCase()));
            values.appendChild(valueRow(labels.actualCost || 'Actual cost', Number(billing.actual_credits != null ? billing.actual_credits : latest.actual_credits || 0) + ' ' + (labels.credits || 'credits')));
            values.appendChild(valueRow(labels.completedAt || 'Completed', formatDate(measurement.completed_at || latest.completed_at)));
            card.appendChild(values);
            var interpretation = String(sample.interpretation || '');
            var sampleMessage = interpretation === 'reportable'
                ? (labels.reportableData || 'The sample threshold is met.')
                : (labels.exploratoryData || 'Exploratory data — the sample is too small for a stable score.');
            var insufficient = Array.isArray(sample.insufficient_metrics) ? sample.insufficient_metrics : [];
            if (interpretation !== 'reportable' && insufficient.length && Number(sample.metric_count || 0) > 0) {
                var metricNames = insufficient.map(function (metric) {
                    return actionMetricLabel(metric.metric_key);
                }).filter(function (name, index, all) {
                    return name && all.indexOf(name) === index;
                });
                sampleMessage = (labels.exploratoryMetricSummary ||
                    '{sufficient} of {total} metrics meet the evidence threshold. Still exploratory: {metrics}.')
                    .replace('{sufficient}', String(Number(sample.sufficient_metric_count || 0)))
                    .replace('{total}', String(Number(sample.metric_count || 0)))
                    .replace('{metrics}', metricNames.join(', '));
            }
            if (interpretation !== 'reportable' && Number(sample.additional_eligible_conversations_required || 0) > 0) {
                var additionalCount = Number(sample.additional_eligible_conversations_required || 0);
                sampleMessage += ' ' + (additionalCount === 1
                    ? (labels.additionalEligibleOne || '1 more eligible conversation is needed to reach the minimum sample of {minimum}.')
                    : (labels.additionalEligible || '{count} more eligible conversations are needed to reach the minimum sample of {minimum}.'))
                    .replace('{count}', String(Number(sample.additional_eligible_conversations_required || 0)))
                    .replace('{minimum}', String(Number(sample.minimum_required_sample_size || 0)));
            }
            card.appendChild(element('p', 'aiv-product-context__notice ' + (interpretation === 'reportable' ? 'is-reportable' : 'is-exploratory'), sampleMessage));
            var comparisonLabels = {
                comparable: labels.comparisonComparable || 'This measurement can be compared with results from the same cohort contract.',
                baseline_missing: labels.comparisonBaselineMissing || 'This is the first measurement for this cohort, so no earlier comparable baseline exists.',
                methodology_changed: labels.comparisonMethodologyChanged || 'The measurement methodology changed; compare this result only within the new series.',
                cohort_contract_changed: labels.comparisonCohortChanged || 'The measurement cohort changed; this result starts a new comparison series.',
                comparison_unavailable: labels.comparisonUnavailable || 'Comparable trend context is not available for this measurement.'
            };
            var comparisonKey = String(comparison.explanation_key || 'comparison_unavailable');
            card.appendChild(element(
                'p',
                'aiv-product-context__notice ' + (comparison.eligible ? 'is-reportable' : 'is-exploratory'),
                comparisonLabels[comparisonKey] || comparisonLabels.comparison_unavailable
            ));
            var details = element('details', 'aiv-product-context__technical');
            details.appendChild(element('summary', '', (labels.cohort || 'Cohort') + ' & ' + (labels.methodology || 'Methodology')));
            var cohort = String(measurement.cohort_hash || latest.cohort_hash || '—');
            details.appendChild(element('p', '', (labels.cohort || 'Cohort') + ': ' + cohort));
            details.appendChild(element('p', '', (labels.methodology || 'Methodology') + ': ' + (measurement.methodology_version || latest.methodology_version || '—')));
            if (Array.isArray(measurement.engine_keys) && measurement.engine_keys.length) {
                details.appendChild(element('p', '', (labels.engineTechnicalKey || 'Engine key') + ': ' + measurement.engine_keys.join(', ')));
            }
            if (comparison.series_break_reason) {
                details.appendChild(element('p', '', (labels.technicalReason || 'Technical reason') + ': ' + String(comparison.series_break_reason)));
            }
            card.appendChild(details);
        }
        panel.insertBefore(card, run);
        renderNextActions(panel, latest, detail.next_actions || []);
        if (latestActionDetail) { renderBaselineNotice(latestActionDetail); }
    }

    function renderBaselineNotice(detail) {
        latestActionDetail = detail || {};
        var target = root.querySelector('.aysa-ai-visibility__action-plan');
        if (!target) { return; }
        var old = target.querySelector('.aiv-product-baseline');
        if (old) { old.remove(); }
        var ids = detail.mode === 'bundle'
            ? [Number(detail.baseline_run_batch_id || 0)]
            : (detail.baseline_run_batch_ids || []).map(Number);
        ids = ids.filter(function (id, index, all) { return id > 0 && all.indexOf(id) === index; });
        if (!ids.length || !displayedRunId) { return; }
        var labels = shell();
        var message;
        var modifier = '';
        if (ids.length > 1) {
            message = labels.baselineMultiple || 'Recommendations from multiple baselines are shown.';
            modifier = ' is-warning';
        } else if (ids[0] !== displayedRunId) {
            message = (displayedRunId !== actualLatestRunId
                ? (labels.baselineDifferentSelected || 'These recommendations use measurement #{baseline}; you are viewing measurement #{selected}.')
                    .replace('{baseline}', String(ids[0])).replace('{selected}', String(displayedRunId))
                : (labels.baselineDifferent || 'These recommendations use measurement #{baseline}; the latest measurement is #{latest}.')
                    .replace('{baseline}', String(ids[0])).replace('{latest}', String(actualLatestRunId)));
            modifier = ' is-warning';
        } else {
            message = labels.baselineCurrent || 'Recommendations use the latest measurement as their baseline.';
        }
        var notice = element('p', 'aiv-product-baseline' + modifier, message);
        target.insertBefore(notice, target.firstChild);
    }

    buildNavigation();
    new MutationObserver(syncNavigation).observe(canonicalTabs, {
        subtree: true, attributes: true, attributeFilter: ['aria-selected']
    });
    root.addEventListener('aysa:aiv:overview-rendered', function (event) { renderOverviewContext(event.detail || {}); });
    root.addEventListener('aysa:aiv:action-plan-rendered', function (event) { renderBaselineNotice(event.detail || {}); });
    root.addEventListener('aysa:aiv:language-changed', function () {
        updateLabels();
        if (latestOverviewDetail) { renderOverviewContext(latestOverviewDetail); }
        if (latestActionDetail) { renderBaselineNotice(latestActionDetail); }
    });
}());
