(function ($) {
    'use strict';

    var nsVars = window.noesia_admin_vars || {};
    var strings = nsVars.strings || {};
    var modules = window.noesiaSwaAdminModules = window.noesiaSwaAdminModules || {};
    var state = {
        bound: false,
        initialized: false,
        developmentLoaded: false,
        digitalLoaded: false,
        populationLoaded: false,
        imfLoaded: false,
        oecdLoaded: false,
        healthLoaded: false,
        medicalLoaded: false,
        medicalQuery: '',
        medicalLanguage: 'any',
        compareLoaded: false
    };

    function str(key, fallback) {
        return strings[key] ? String(strings[key]) : String(fallback || '');
    }

    function root() {
        return $('[data-gdh-root="1"]').first();
    }

    function ajax(data) {
        var node = root();
        var ajaxUrl = node.attr('data-ajax-url') || nsVars.ajax_url || window.ajaxurl || '';
        var nonce = node.attr('data-nonce') || nsVars.nonce || '';
        return $.ajax({
            url: ajaxUrl,
            method: 'POST',
            dataType: 'json',
            data: $.extend({}, data || {}, { nonce: nonce })
        });
    }

    function escapeHtml(value) {
        return $('<div/>').text(String(value || '')).html();
    }

    function status(message, isError) {
        var node = root().find('[data-gdh-status="hero"]');
        node.text(String(message || '')).toggleClass('is-error', !!isError);
    }

    function setBusy(button, busy, idleText, busyText) {
        var node = $(button || []);
        if (!node.length) {
            return;
        }
        if (!node.data('gdhIdleText')) {
            node.data('gdhIdleText', $.trim(String(idleText || node.text() || '')));
        }
        node.prop('disabled', !!busy).toggleClass('is-busy', !!busy).text(busy ? String(busyText || 'Working…') : String(idleText || node.data('gdhIdleText') || ''));
    }

    function loadingHtml(message) {
        return '<div class="noesia-swa-gdh__loading"><span class="noesia-swa-gdh__spinner" aria-hidden="true"></span><span>' + escapeHtml(message || 'Loading…') + '</span></div>';
    }

    function renderOverview(cards) {
        var node = root().find('[data-gdh-overview="1"]');
        if (!node.length || !Array.isArray(cards)) {
            return;
        }
        node.html(cards.map(function (card) {
            return '<article class="noesia-swa-gdh__metric-card"><span>' + escapeHtml(card.label || '') + '</span><strong>' + escapeHtml(card.value || '—') + '</strong><small>' + escapeHtml(card.meta || '') + '</small></article>';
        }).join(''));
    }

    function renderMiniCards(target, cards, emptyMessage) {
        var node = root().find(target);
        if (!node.length) {
            return;
        }
        if (!Array.isArray(cards) || !cards.length) {
            node.html('<div class="noesia-swa-gdh__empty">' + escapeHtml(emptyMessage || 'No official values are available for the selected country yet.') + '</div>');
            return;
        }
        node.html(cards.map(function (card) {
            return '<article class="noesia-swa-gdh__mini-card"><span>' + escapeHtml(card.label || '') + '</span><strong>' + escapeHtml(card.value || '—') + '</strong><small>' + escapeHtml(card.meta || '') + '</small></article>';
        }).join(''));
    }

    function buildSeriesTable(series, datasetMode) {
        var rows = Array.isArray(series.rows) ? series.rows : [];
        var quarters = Array.isArray(series.quarters) ? series.quarters : [];
        var latest = series.latest || {};
        var blocks = '';

        blocks += '<div class="noesia-swa-gdh__cards-inline">' +
            '<article class="noesia-swa-gdh__mini-card"><span>Latest period</span><strong>' + escapeHtml(latest.formatted || '—') + '</strong><small>' + escapeHtml(latest.period_label || '') + '</small></article>' +
            '<article class="noesia-swa-gdh__mini-card"><span>Series</span><strong>' + escapeHtml(series.label || 'Official series') + '</strong><small>' + escapeHtml(series.selector || '') + '</small></article>' +
        '</div>';

        if (rows.length) {
            blocks += '<table class="noesia-swa-gdh__table"><thead><tr><th>Period</th><th>Official value</th></tr></thead><tbody>' + rows.map(function (row) {
                return '<tr><td>' + escapeHtml(row.period_label || row.period_raw || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
            }).join('') + '</tbody></table>';
        }

        if (quarters.length) {
            blocks += '<div class="noesia-swa-gdh__series-block"><h4>Quarter view</h4><table class="noesia-swa-gdh__table"><thead><tr><th>Quarter</th><th>' + escapeHtml(datasetMode === 'percentage' ? 'Average official value' : 'Official total') + '</th></tr></thead><tbody>' + quarters.map(function (row) {
                return '<tr><td>' + escapeHtml(row.period || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
            }).join('') + '</tbody></table></div>';
        }

        return blocks;
    }

    function renderDataset(slot, dataset) {
        var node = root().find('[data-gdh-dataset="' + slot + '"]');
        var series = dataset && Array.isArray(dataset.series) ? dataset.series : [];
        if (!node.length) {
            return;
        }
        if (!dataset || dataset.status !== 'ok' || !series.length) {
            node.html('<div class="noesia-swa-gdh__empty">' + escapeHtml(dataset && dataset.notice ? dataset.notice : 'Official data unavailable for this dataset and country.') + '</div>');
            return;
        }

        var meta = '<div class="noesia-swa-gdh__notice is-info"><strong>' + escapeHtml(dataset.source || 'Eurostat') + '</strong><p>' +
            escapeHtml((dataset.definition || '') + ' Dataset code: ' + (dataset.dataset_code || '') + (dataset.unit_label ? ' · Unit: ' + dataset.unit_label : '') + (dataset.updated ? ' · Last updated: ' + dataset.updated : '')) +
            '</p></div>';

        node.html(meta + series.map(function (item) {
            return '<div class="noesia-swa-gdh__series-block"><h4>' + escapeHtml(item.label || 'Official series') + '</h4>' + buildSeriesTable(item, dataset.mode || 'number') + '</div>';
        }).join(''));
    }

    function renderTourism(payload) {
        renderOverview(payload.overview_cards || []);
        renderMiniCards('[data-gdh-tourism-cards="1"]', payload.overview_cards || [], 'No official tourism card values are available for the selected country yet.');
        root().find('[data-gdh-tourism-note="1"]').text(String(payload.note || ''));
        renderDataset('arrivals', payload.datasets ? payload.datasets.arrivals : null);
        renderDataset('nights', payload.datasets ? payload.datasets.nights : null);
        renderDataset('occupancy', payload.datasets ? payload.datasets.occupancy : null);
    }

    function renderDevelopment(payload) {
        var indicators = payload && Array.isArray(payload.indicators) ? payload.indicators : [];
        var grouped = {};
        var order = [];

        renderMiniCards('[data-gdh-development-cards="1"]', payload.overview_cards || [], 'No strict World Bank WDI card values are available for the selected country yet.');
        root().find('[data-gdh-development-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var node = root().find('[data-gdh-development-indicators="1"]');
        if (!node.length) {
            return;
        }
        if (!indicators.length) {
            node.html('<div class="noesia-swa-gdh__empty">No strict World Bank indicators are available for the selected country yet.</div>');
            return;
        }

        indicators.forEach(function (item) {
            var group = String(item && item.group ? item.group : 'World Bank');
            if (!grouped[group]) {
                grouped[group] = [];
                order.push(group);
            }
            grouped[group].push(item);
        });

        node.html(order.map(function (group) {
            return '<section class="noesia-swa-gdh__indicator-section">' +
                '<div class="noesia-swa-gdh__section-head"><h4>' + escapeHtml(group) + '</h4></div>' +
                '<div class="noesia-swa-gdh__indicator-grid">' + grouped[group].map(function (item) {
                    var history = Array.isArray(item.history) && item.history.length ? '<table class="noesia-swa-gdh__table"><thead><tr><th>Year</th><th>Official value</th></tr></thead><tbody>' + item.history.map(function (row) {
                        return '<tr><td>' + escapeHtml(row.period_label || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
                    }).join('') + '</tbody></table>' : '<div class="noesia-swa-gdh__empty">' + escapeHtml(item.notice || 'No official values available.') + '</div>';
                    return '<article class="noesia-swa-gdh__indicator-card">' +
                        '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'Official indicator') + '</h3><p>' + escapeHtml(item.definition || '') + '</p></div></div>' +
                        '<div class="noesia-swa-gdh__cards-inline"><article class="noesia-swa-gdh__mini-card"><span>Latest value</span><strong>' + escapeHtml(item.latest && item.latest.formatted ? item.latest.formatted : '—') + '</strong><small>' + escapeHtml(item.latest && item.latest.period_label ? item.latest.period_label : '') + '</small></article><article class="noesia-swa-gdh__mini-card"><span>Indicator code</span><strong>' + escapeHtml(item.code || '') + '</strong><small>' + escapeHtml(item.source || 'World Bank Indicators API') + '</small></article></div>' +
                        '<div class="noesia-swa-gdh__notice is-info"><strong>Strict source</strong><p>' + escapeHtml(item.notice || 'Only the fixed official WDI indicator code is shown in this card.') + '</p></div>' +
                        history +
                    '</article>';
                }).join('') + '</div>' +
            '</section>';
        }).join(''));
    }

    function renderDigital(payload) {
        var indicators = payload && Array.isArray(payload.indicators) ? payload.indicators : [];
        var grouped = {};
        var order = [];

        renderMiniCards('[data-gdh-digital-cards="1"]', payload.overview_cards || [], 'No strict digital or connectivity card values are available for the selected country yet.');
        root().find('[data-gdh-digital-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var node = root().find('[data-gdh-digital-indicators="1"]');
        if (!node.length) {
            return;
        }
        if (!indicators.length) {
            node.html('<div class="noesia-swa-gdh__empty">No strict digital or connectivity indicators are available for the selected country yet.</div>');
            return;
        }

        indicators.forEach(function (item) {
            var group = String(item && item.group ? item.group : 'Digital / Connectivity');
            if (!grouped[group]) {
                grouped[group] = [];
                order.push(group);
            }
            grouped[group].push(item);
        });

        node.html(order.map(function (group) {
            return '<section class="noesia-swa-gdh__indicator-section">' +
                '<div class="noesia-swa-gdh__section-head"><h4>' + escapeHtml(group) + '</h4></div>' +
                '<div class="noesia-swa-gdh__indicator-grid">' + grouped[group].map(function (item) {
                    var history = Array.isArray(item.history) && item.history.length ? '<table class="noesia-swa-gdh__table"><thead><tr><th>Year</th><th>Official value</th></tr></thead><tbody>' + item.history.map(function (row) {
                        return '<tr><td>' + escapeHtml(row.period_label || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
                    }).join('') + '</tbody></table>' : '<div class="noesia-swa-gdh__empty">' + escapeHtml(item.notice || 'No official values available.') + '</div>';
                    return '<article class="noesia-swa-gdh__indicator-card">' +
                        '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'Official indicator') + '</h3><p>' + escapeHtml(item.definition || '') + '</p></div></div>' +
                        '<div class="noesia-swa-gdh__cards-inline"><article class="noesia-swa-gdh__mini-card"><span>Latest value</span><strong>' + escapeHtml(item.latest && item.latest.formatted ? item.latest.formatted : '—') + '</strong><small>' + escapeHtml(item.latest && item.latest.period_label ? item.latest.period_label : '') + '</small></article><article class="noesia-swa-gdh__mini-card"><span>Indicator code</span><strong>' + escapeHtml(item.code || '') + '</strong><small>' + escapeHtml(item.source || 'World Bank Indicators API (WDI)') + '</small></article></div>' +
                        '<div class="noesia-swa-gdh__notice is-info"><strong>Strict source</strong><p>' + escapeHtml(item.notice || 'Only the fixed official WDI ICT indicator code is shown in this card.') + '</p></div>' +
                        history +
                    '</article>';
                }).join('') + '</div>' +
            '</section>';
        }).join(''));
    }


    function renderPopulation(payload) {
        var indicators = payload && Array.isArray(payload.indicators) ? payload.indicators : [];
        var grouped = {};
        var order = [];

        renderMiniCards('[data-gdh-population-cards="1"]', payload.overview_cards || [], 'No strict population or society card values are available for the selected country yet.');
        root().find('[data-gdh-population-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var node = root().find('[data-gdh-population-indicators="1"]');
        if (!node.length) {
            return;
        }
        if (!indicators.length) {
            node.html('<div class="noesia-swa-gdh__empty">No strict population or society indicators are available for the selected country yet.</div>');
            return;
        }

        indicators.forEach(function (item) {
            var group = String(item && item.group ? item.group : 'Population & Society');
            if (!grouped[group]) {
                grouped[group] = [];
                order.push(group);
            }
            grouped[group].push(item);
        });

        node.html(order.map(function (group) {
            return '<section class="noesia-swa-gdh__indicator-section">' +
                '<div class="noesia-swa-gdh__section-head"><h4>' + escapeHtml(group) + '</h4></div>' +
                '<div class="noesia-swa-gdh__indicator-grid">' + grouped[group].map(function (item) {
                    var history = Array.isArray(item.history) && item.history.length ? '<table class="noesia-swa-gdh__table"><thead><tr><th>Year</th><th>Official value</th></tr></thead><tbody>' + item.history.map(function (row) {
                        return '<tr><td>' + escapeHtml(row.period_label || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
                    }).join('') + '</tbody></table>' : '<div class="noesia-swa-gdh__empty">' + escapeHtml(item.notice || 'No official values available.') + '</div>';
                    return '<article class="noesia-swa-gdh__indicator-card">' +
                        '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'Official indicator') + '</h3><p>' + escapeHtml(item.definition || '') + '</p></div></div>' +
                        '<div class="noesia-swa-gdh__cards-inline"><article class="noesia-swa-gdh__mini-card"><span>Latest value</span><strong>' + escapeHtml(item.latest && item.latest.formatted ? item.latest.formatted : '—') + '</strong><small>' + escapeHtml(item.latest && item.latest.period_label ? item.latest.period_label : '') + '</small></article><article class="noesia-swa-gdh__mini-card"><span>Indicator code</span><strong>' + escapeHtml(item.code || '') + '</strong><small>' + escapeHtml(item.source || 'World Bank Indicators API (WDI)') + '</small></article></div>' +
                        '<div class="noesia-swa-gdh__notice is-info"><strong>Strict source</strong><p>' + escapeHtml(item.notice || 'Only the fixed official WDI demographic or social indicator code is shown in this card.') + '</p></div>' +
                        history +
                    '</article>';
                }).join('') + '</div>' +
            '</section>';
        }).join(''));
    }



    function collectCompareCountries() {
        var countries = [];
        root().find('[data-gdh-compare-country]').each(function () {
            var value = $.trim(String($(this).val() || ''));
            if (value) {
                countries.push(value);
            }
        });
        return countries;
    }

    function renderCompare(payload) {
        var metrics = payload && Array.isArray(payload.metrics) ? payload.metrics : [];
        renderMiniCards('[data-gdh-compare-cards="1"]', payload.overview_cards || [], 'No strict comparison summary is available yet.');
        root().find('[data-gdh-compare-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var node = root().find('[data-gdh-compare-results="1"]');
        if (!node.length) {
            return;
        }
        if (!metrics.length) {
            node.html('<div class="noesia-swa-gdh__empty">No strict comparison metrics are available for the selected countries yet.</div>');
            return;
        }

        node.html('<div class="noesia-swa-gdh__indicator-grid">' + metrics.map(function (metric) {
            var rows = Array.isArray(metric.rows) ? metric.rows : [];
            var table = rows.length ? '<table class="noesia-swa-gdh__table"><thead><tr><th>Country</th><th>Latest value</th><th>Period</th><th>Detail</th></tr></thead><tbody>' + rows.map(function (row) {
                return '<tr><td>' + escapeHtml(row.country_label || row.country_code || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td><td>' + escapeHtml(row.period_label || '—') + '</td><td>' + escapeHtml(row.detail || row.notice || '') + '</td></tr>';
            }).join('') + '</tbody></table>' : '<div class="noesia-swa-gdh__empty">No official comparison rows are available for this metric.</div>';
            return '<article class="noesia-swa-gdh__indicator-card">' +
                '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(metric.title || 'Official comparison metric') + '</h3><p>' + escapeHtml(metric.definition || '') + '</p></div></div>' +
                '<div class="noesia-swa-gdh__cards-inline"><article class="noesia-swa-gdh__mini-card"><span>Provider</span><strong>' + escapeHtml(metric.provider || 'Official API') + '</strong><small>' + escapeHtml(metric.code || '') + '</small></article><article class="noesia-swa-gdh__mini-card"><span>Countries compared</span><strong>' + escapeHtml(String(rows.length || 0)) + '</strong><small>' + escapeHtml(metric.coverage_note || 'Latest official values only') + '</small></article></div>' +
                '<div class="noesia-swa-gdh__notice is-info"><strong>Strict source</strong><p>' + escapeHtml(metric.notice || 'Only fixed official metrics already enabled elsewhere in Global Data Hub are compared here.') + '</p></div>' +
                table +
            '</article>';
        }).join('') + '</div>');
    }

    function renderImf(payload) {
        var indicators = payload && Array.isArray(payload.indicators) ? payload.indicators : [];
        renderMiniCards('[data-gdh-imf-cards="1"]', payload.overview_cards || [], 'No strict IMF macro card values are available for the selected country yet.');
        root().find('[data-gdh-imf-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var node = root().find('[data-gdh-imf-indicators="1"]');
        if (!node.length) {
            return;
        }
        if (!indicators.length) {
            node.html('<div class="noesia-swa-gdh__empty">No strict IMF macro indicators are available for the selected country yet.</div>');
            return;
        }

        node.html('<div class="noesia-swa-gdh__indicator-grid">' + indicators.map(function (item) {
            var history = Array.isArray(item.history) && item.history.length ? '<table class="noesia-swa-gdh__table"><thead><tr><th>Year</th><th>Official value</th></tr></thead><tbody>' + item.history.map(function (row) {
                return '<tr><td>' + escapeHtml(row.period_label || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
            }).join('') + '</tbody></table>' : '<div class="noesia-swa-gdh__empty">' + escapeHtml(item.notice || 'No official values available.') + '</div>';
            return '<article class="noesia-swa-gdh__indicator-card">' +
                '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'Official indicator') + '</h3><p>' + escapeHtml(item.definition || '') + '</p></div></div>' +
                '<div class="noesia-swa-gdh__cards-inline"><article class="noesia-swa-gdh__mini-card"><span>Latest value</span><strong>' + escapeHtml(item.latest && item.latest.formatted ? item.latest.formatted : '—') + '</strong><small>' + escapeHtml(item.latest && item.latest.period_label ? item.latest.period_label : '') + '</small></article><article class="noesia-swa-gdh__mini-card"><span>Indicator code</span><strong>' + escapeHtml(item.code || '') + '</strong><small>' + escapeHtml(item.source || 'IMF DataMapper API') + '</small></article></div>' +
                '<div class="noesia-swa-gdh__notice is-info"><strong>Strict source</strong><p>' + escapeHtml(item.notice || 'Only the fixed official IMF indicator code is shown in this card.') + '</p></div>' +
                history +
            '</article>';
        }).join('') + '</div>');
    }


    function renderOecd(payload) {
        var indicators = payload && Array.isArray(payload.indicators) ? payload.indicators : [];
        renderMiniCards('[data-gdh-oecd-cards="1"]', payload.overview_cards || [], 'No strict OECD card values are available for the selected country yet.');
        root().find('[data-gdh-oecd-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var node = root().find('[data-gdh-oecd-indicators="1"]');
        if (!node.length) {
            return;
        }
        if (!indicators.length) {
            node.html('<div class="noesia-swa-gdh__empty">No strict OECD indicators are available for the selected country yet.</div>');
            return;
        }

        node.html('<div class="noesia-swa-gdh__indicator-grid">' + indicators.map(function (item) {
            var history = Array.isArray(item.history) && item.history.length ? '<table class="noesia-swa-gdh__table"><thead><tr><th>Period</th><th>Official value</th></tr></thead><tbody>' + item.history.map(function (row) {
                return '<tr><td>' + escapeHtml(row.period_label || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
            }).join('') + '</tbody></table>' : '<div class="noesia-swa-gdh__empty">' + escapeHtml(item.notice || 'No official values available.') + '</div>';
            return '<article class="noesia-swa-gdh__indicator-card">' +
                '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'Official indicator') + '</h3><p>' + escapeHtml(item.definition || '') + '</p></div></div>' +
                '<div class="noesia-swa-gdh__cards-inline"><article class="noesia-swa-gdh__mini-card"><span>Latest value</span><strong>' + escapeHtml(item.latest && item.latest.formatted ? item.latest.formatted : '—') + '</strong><small>' + escapeHtml(item.latest && item.latest.period_label ? item.latest.period_label : '') + '</small></article><article class="noesia-swa-gdh__mini-card"><span>Series code</span><strong>' + escapeHtml(item.code || '') + '</strong><small>' + escapeHtml(item.source || 'OECD Data Explorer API') + '</small></article></div>' +
                '<div class="noesia-swa-gdh__notice is-info"><strong>Strict source</strong><p>' + escapeHtml(item.notice || 'Only the fixed OECD selection is shown in this card.') + '</p></div>' +
                history +
            '</article>';
        }).join('') + '</div>');
    }



    function renderHealth(payload) {
        var indicators = payload && Array.isArray(payload.indicators) ? payload.indicators : [];
        var grouped = {};
        var order = [];

        renderMiniCards('[data-gdh-health-cards="1"]', payload.overview_cards || [], 'No strict WHO card values are available for the selected country yet.');
        root().find('[data-gdh-health-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var node = root().find('[data-gdh-health-indicators="1"]');
        if (!node.length) {
            return;
        }
        if (!indicators.length) {
            node.html('<div class="noesia-swa-gdh__empty">No strict WHO indicators are available for the selected country yet.</div>');
            return;
        }

        indicators.forEach(function (item) {
            var group = String(item && item.group ? item.group : 'WHO Health');
            if (!grouped[group]) {
                grouped[group] = [];
                order.push(group);
            }
            grouped[group].push(item);
        });

        node.html(order.map(function (group) {
            return '<section class="noesia-swa-gdh__indicator-section">' +
                '<div class="noesia-swa-gdh__section-head"><h4>' + escapeHtml(group) + '</h4></div>' +
                '<div class="noesia-swa-gdh__indicator-grid">' + grouped[group].map(function (item) {
                    var history = Array.isArray(item.history) && item.history.length ? '<table class="noesia-swa-gdh__table"><thead><tr><th>Year</th><th>Official value</th></tr></thead><tbody>' + item.history.map(function (row) {
                        return '<tr><td>' + escapeHtml(row.period_label || '') + '</td><td>' + escapeHtml(row.formatted || '—') + '</td></tr>';
                    }).join('') + '</tbody></table>' : '<div class="noesia-swa-gdh__empty">' + escapeHtml(item.notice || 'No official values available.') + '</div>';
                    return '<article class="noesia-swa-gdh__indicator-card">' +
                        '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'Official indicator') + '</h3><p>' + escapeHtml(item.definition || '') + '</p></div></div>' +
                        '<div class="noesia-swa-gdh__cards-inline"><article class="noesia-swa-gdh__mini-card"><span>Latest value</span><strong>' + escapeHtml(item.latest && item.latest.formatted ? item.latest.formatted : '—') + '</strong><small>' + escapeHtml(item.latest && item.latest.period_label ? item.latest.period_label : '') + '</small></article><article class="noesia-swa-gdh__mini-card"><span>Indicator code</span><strong>' + escapeHtml(item.code || '') + '</strong><small>' + escapeHtml(item.source || 'WHO Global Health Observatory') + '</small></article></div>' +
                        '<div class="noesia-swa-gdh__notice is-info"><strong>Strict source</strong><p>' + escapeHtml(item.notice || 'Only the exact official WHO indicator match is shown in this card.') + '</p></div>' +
                        history +
                    '</article>';
                }).join('') + '</div>' +
            '</section>';
        }).join(''));
    }

    function renderMedical(payload) {
        var pubmed = payload && payload.pubmed ? payload.pubmed : {};
        var trials = payload && payload.trials ? payload.trials : {};
        var pubmedItems = Array.isArray(pubmed.items) ? pubmed.items : [];
        var trialItems = Array.isArray(trials.items) ? trials.items : [];

        renderMiniCards('[data-gdh-medical-cards="1"]', payload.overview_cards || [], 'Run a medical evidence search to load official PubMed and ClinicalTrials.gov results.');
        root().find('[data-gdh-medical-note="1"]').text(String(payload && payload.note ? payload.note : ''));

        var pubmedNode = root().find('[data-gdh-medical-pubmed="1"]');
        var trialsNode = root().find('[data-gdh-medical-trials="1"]');

        if (pubmedNode.length) {
            if (!pubmedItems.length) {
                pubmedNode.html('<div class="noesia-swa-gdh__empty">' + escapeHtml(pubmed.notice || 'No official PubMed records matched this query.') + '</div>');
            } else {
                pubmedNode.html('<div class="noesia-swa-gdh__indicator-grid">' + pubmedItems.map(function (item) {
                    var link = item.source_url ? '<a class="button button-secondary noesia-swa-gdh__button noesia-swa-gdh__button--ghost" href="' + escapeHtml(item.source_url) + '" target="_blank" rel="noopener noreferrer">Open official source</a>' : '';
                    var types = item.publication_type ? '<p><strong>Type</strong> ' + escapeHtml(item.publication_type) + '</p>' : '';
                    var authors = item.authors ? '<p><strong>Authors</strong> ' + escapeHtml(item.authors) + '</p>' : '';
                    var articleLanguage = '';
                    return '<article class="noesia-swa-gdh__indicator-card">' +
                        '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'PubMed record') + '</h3><p>' + escapeHtml(item.journal || 'PubMed') + (item.pubdate ? ' · ' + escapeHtml(item.pubdate) : '') + '</p></div></div>' +
                        '<div class="noesia-swa-gdh__notice is-info"><strong>PubMed</strong><p>' + escapeHtml(item.snippet || '') + '</p></div>' +
                        '<p><strong>PMID</strong> ' + escapeHtml(item.pmid || '—') + '</p>' + articleLanguage + types + authors + link +
                    '</article>';
                }).join('') + '</div>');
            }
        }

        if (trialsNode.length) {
            if (!trialItems.length) {
                trialsNode.html('<div class="noesia-swa-gdh__empty">' + escapeHtml(trials.notice || 'No official ClinicalTrials.gov records matched this query.') + '</div>');
            } else {
                trialsNode.html('<div class="noesia-swa-gdh__indicator-grid">' + trialItems.map(function (item) {
                    var link = item.source_url ? '<a class="button button-secondary noesia-swa-gdh__button noesia-swa-gdh__button--ghost" href="' + escapeHtml(item.source_url) + '" target="_blank" rel="noopener noreferrer">Open official source</a>' : '';
                    return '<article class="noesia-swa-gdh__indicator-card">' +
                        '<div class="noesia-swa-gdh__card-head"><div><h3>' + escapeHtml(item.title || 'Clinical study') + '</h3><p>' + escapeHtml(item.nct_id || '') + '</p></div></div>' +
                        '<div class="noesia-swa-gdh__cards-inline">' +
                            '<article class="noesia-swa-gdh__mini-card"><span>Status</span><strong>' + escapeHtml(item.status || '—') + '</strong><small>ClinicalTrials.gov</small></article>' +
                            '<article class="noesia-swa-gdh__mini-card"><span>Phase</span><strong>' + escapeHtml(item.phase || '—') + '</strong><small>' + escapeHtml(item.sponsor || '—') + '</small></article>' +
                        '</div>' +
                        '<div class="noesia-swa-gdh__notice is-info"><strong>ClinicalTrials.gov</strong><p>' + escapeHtml(item.summary || '') + '</p></div>' +
                        '<p><strong>Conditions</strong> ' + escapeHtml(item.conditions || '—') + '</p>' +
                        '<p><strong>Interventions</strong> ' + escapeHtml(item.interventions || '—') + '</p>' + link +
                    '</article>';
                }).join('') + '</div>');
            }
        }
    }

    function loadMedical(query, force) {
        var cleaned = $.trim(String(query || root().find('[data-gdh-medical-query="1"]').val() || ''));
        var language = 'any';
        if (cleaned.length < 3) {
            var shortMessage = 'Use at least 3 characters to search Medical Evidence.';
            status(shortMessage, true);
            root().find('[data-gdh-medical-note="1"]').text(shortMessage);
            root().find('[data-gdh-medical-pubmed="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(shortMessage) + '</div>');
            root().find('[data-gdh-medical-trials="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(shortMessage) + '</div>');
            return;
        }
        root().find('[data-gdh-medical-query="1"]').val(cleaned);
        root().find('[data-gdh-medical-note="1"]').html(loadingHtml(str('gdh_loading_medical', 'Loading official medical evidence…')));
        root().find('[data-gdh-medical-pubmed="1"]').html(loadingHtml('Loading official PubMed evidence results…'));
        root().find('[data-gdh-medical-trials="1"]').html(loadingHtml('Loading official ClinicalTrials.gov registry results…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_medical_evidence', query: cleaned, language: language, force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official medical evidence failed to load.', true);
                return;
            }
            renderMedical(response.data || {});
            state.medicalLoaded = true;
            state.medicalQuery = cleaned;
            state.medicalLanguage = 'any';
            status('Official medical evidence loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official medical evidence failed to load.');
            status(message, true);
            root().find('[data-gdh-medical-note="1"]').text(message);
            root().find('[data-gdh-medical-pubmed="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
            root().find('[data-gdh-medical-trials="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }

    function loadHealth(force) {
        var note = root().find('[data-gdh-health-note="1"]');
        note.html(loadingHtml(str('gdh_loading_health', 'Loading official WHO health data…')));
        root().find('[data-gdh-health-indicators="1"]').html(loadingHtml('Loading strict WHO indicators…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_health', force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official WHO health data failed to load.', true);
                return;
            }
            renderHealth(response.data || {});
            state.healthLoaded = true;
            status('Official WHO health data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official WHO health data failed to load.');
            status(message, true);
            root().find('[data-gdh-health-note="1"]').text(message);
            root().find('[data-gdh-health-indicators="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }

    function loadOecd(force) {
        var note = root().find('[data-gdh-oecd-note="1"]');
        note.html(loadingHtml(str('gdh_loading_oecd', 'Loading official OECD labour and activity data…')));
        root().find('[data-gdh-oecd-indicators="1"]').html(loadingHtml('Loading strict OECD indicators…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_oecd', force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official OECD data failed to load.', true);
                return;
            }
            renderOecd(response.data || {});
            state.oecdLoaded = true;
            status('Official OECD data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official OECD data failed to load.');
            status(message, true);
            root().find('[data-gdh-oecd-note="1"]').text(message);
            root().find('[data-gdh-oecd-indicators="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }


    function loadShell() {
        ajax({ action: 'noesia_swa_global_data_hub_bootstrap' }).done(function (response) {
            if (!response || !response.success) {
                status('Global Data Hub bootstrap failed.', true);
                return;
            }
            renderOverview(response.data && response.data.overview ? response.data.overview : []);
            root().find('[data-gdh-tourism-note="1"]').text(String(response.data && response.data.note ? response.data.note : ''));
            root().find('[data-gdh-development-note="1"]').text(String(response.data && response.data.note ? response.data.note : ''));
            root().find('[data-gdh-imf-note="1"]').text(String(response.data && response.data.note ? response.data.note : ''));
            root().find('[data-gdh-digital-note="1"]').text(String(response.data && response.data.note ? response.data.note : ''));
            root().find('[data-gdh-population-note="1"]').text(String(response.data && response.data.note ? response.data.note : ''));
            root().find('[data-gdh-oecd-note="1"]').text(String(response.data && response.data.note ? response.data.note : ''));
            root().find('[data-gdh-health-note="1"]').text(String(response.data && response.data.note ? response.data.note : ''));
        }).fail(function (xhr) {
            status(extractError(xhr, 'Global Data Hub bootstrap failed.'), true);
        });
    }

    function loadTourism(force) {
        var note = root().find('[data-gdh-tourism-note="1"]');
        note.html(loadingHtml(str('gdh_loading', 'Loading official Eurostat tourism data…')));
        root().find('[data-gdh-dataset="arrivals"],[data-gdh-dataset="nights"],[data-gdh-dataset="occupancy"]').html(loadingHtml('Loading official series…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_tourism', force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official tourism data failed to load.', true);
                return;
            }
            renderTourism(response.data || {});
            status('Official Eurostat tourism data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official tourism data failed to load.');
            status(message, true);
            root().find('[data-gdh-tourism-note="1"]').text(message);
        });
    }

    function loadDevelopment(force) {
        var note = root().find('[data-gdh-development-note="1"]');
        note.html(loadingHtml(str('gdh_loading_development', 'Loading official World Bank WDI data…')));
        root().find('[data-gdh-development-indicators="1"]').html(loadingHtml('Loading strict World Bank WDI indicators…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_development', force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official World Bank data failed to load.', true);
                return;
            }
            renderDevelopment(response.data || {});
            state.developmentLoaded = true;
            status('Official World Bank WDI data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official World Bank data failed to load.');
            status(message, true);
            root().find('[data-gdh-development-note="1"]').text(message);
            root().find('[data-gdh-development-indicators="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }

    function loadDigital(force) {
        var note = root().find('[data-gdh-digital-note="1"]');
        note.html(loadingHtml(str('gdh_loading_digital', 'Loading official digital and connectivity data…')));
        root().find('[data-gdh-digital-indicators="1"]').html(loadingHtml('Loading strict digital and connectivity indicators…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_digital', force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official digital and connectivity data failed to load.', true);
                return;
            }
            renderDigital(response.data || {});
            state.digitalLoaded = true;
            status('Official digital and connectivity data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official digital and connectivity data failed to load.');
            status(message, true);
            root().find('[data-gdh-digital-note="1"]').text(message);
            root().find('[data-gdh-digital-indicators="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }


    function loadPopulation(force) {
        var note = root().find('[data-gdh-population-note="1"]');
        note.html(loadingHtml(str('gdh_loading_population', 'Loading official population and society data…')));
        root().find('[data-gdh-population-indicators="1"]').html(loadingHtml('Loading strict population and society indicators…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_population', force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official population and society data failed to load.', true);
                return;
            }
            renderPopulation(response.data || {});
            state.populationLoaded = true;
            status('Official population and society data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official population and society data failed to load.');
            status(message, true);
            root().find('[data-gdh-population-note="1"]').text(message);
            root().find('[data-gdh-population-indicators="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }



    function loadCompare(force) {
        var note = root().find('[data-gdh-compare-note="1"]');
        note.html(loadingHtml(str('gdh_loading_compare', 'Loading strict country comparison data…')));
        root().find('[data-gdh-compare-results="1"]').html(loadingHtml('Loading strict cross-country comparison metrics…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_compare', force: force ? 1 : 0, countries: collectCompareCountries() }).done(function (response) {
            if (!response || !response.success) {
                status('Official comparison data failed to load.', true);
                return;
            }
            renderCompare(response.data || {});
            state.compareLoaded = true;
            status('Official comparison data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official comparison data failed to load.');
            status(message, true);
            root().find('[data-gdh-compare-note="1"]').text(message);
            root().find('[data-gdh-compare-results="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }

    function loadImf(force) {
        var note = root().find('[data-gdh-imf-note="1"]');
        note.html(loadingHtml(str('gdh_loading_imf', 'Loading official IMF macro data…')));
        root().find('[data-gdh-imf-indicators="1"]').html(loadingHtml('Loading strict IMF indicators…'));
        ajax({ action: 'noesia_swa_global_data_hub_fetch_imf_macro', force: force ? 1 : 0 }).done(function (response) {
            if (!response || !response.success) {
                status('Official IMF macro data failed to load.', true);
                return;
            }
            renderImf(response.data || {});
            state.imfLoaded = true;
            status('Official IMF macro data loaded.', false);
        }).fail(function (xhr) {
            var message = extractError(xhr, 'Official IMF macro data failed to load.');
            status(message, true);
            root().find('[data-gdh-imf-note="1"]').text(message);
            root().find('[data-gdh-imf-indicators="1"]').html('<div class="noesia-swa-gdh__empty">' + escapeHtml(message) + '</div>');
        });
    }


    function extractError(xhr, fallback) {
        var message = fallback || 'Request failed.';
        if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            message = String(xhr.responseJSON.data.message);
        }
        return message;
    }

    function collectSettings() {
        var data = {};
        root().find('[data-gdh-setting]').each(function () {
            var field = $(this);
            data[String(field.data('gdhSetting'))] = $.trim(String(field.val() || ''));
        });
        return data;
    }

    function saveSettings(button) {
        setBusy(button, true, null, 'Saving settings…');
        status('Saving settings…', false);
        ajax({ action: 'noesia_swa_global_data_hub_save_settings', settings: collectSettings() }).done(function (response) {
            if (!response || !response.success) {
                status('Saving settings failed.', true);
                return;
            }
            status(String(response.data && response.data.message ? response.data.message : 'Global Data Hub settings saved.'), false);
            state.developmentLoaded = false;
            state.imfLoaded = false;
            state.digitalLoaded = false;
            state.populationLoaded = false;
            state.oecdLoaded = false;
            state.healthLoaded = false;
            state.medicalLoaded = false;
            state.medicalQuery = "";
            state.compareLoaded = false;
            root().find('[data-gdh-compare-country="0"]').val(root().find('[data-gdh-setting="country_code"]').val());
            loadShell();
            loadTourism(true);
            if (root().find('[data-gdh-tab="development"]').hasClass('is-active')) {
                loadDevelopment(true);
            }
            if (root().find('[data-gdh-tab="imf-macro"]').hasClass('is-active')) {
                loadImf(true);
            }
            if (root().find('[data-gdh-tab="digital-connectivity"]').hasClass('is-active')) {
                loadDigital(true);
            }
            if (root().find('[data-gdh-tab="population-society"]').hasClass('is-active')) {
                loadPopulation(true);
            }
            if (root().find('[data-gdh-tab="oecd-insights"]').hasClass('is-active')) {
                loadOecd(true);
            }
            if (root().find('[data-gdh-tab="health"]').hasClass('is-active')) {
                loadHealth(true);
            }
            if (root().find('[data-gdh-tab="medical-evidence"]').hasClass('is-active') && state.medicalQuery) {
                loadMedical(state.medicalQuery, true);
            }
            if (root().find('[data-gdh-tab="compare-countries"]').hasClass('is-active')) {
                loadCompare(true);
            }
        }).fail(function (xhr) {
            status(extractError(xhr, 'Saving settings failed.'), true);
        }).always(function () {
            setBusy(button, false, null, 'Save Settings');
        });
    }

    function bindEvents() {
        if (state.bound) {
            return;
        }
        state.bound = true;

        $(document)
            .on('click', '[data-gdh-tab-target]', function () {
                var target = String($(this).data('gdhTabTarget') || '');
                var wrap = root();
                if (!wrap.length) {
                    return;
                }
                wrap.find('[data-gdh-tab-target]').removeClass('is-active');
                $(this).addClass('is-active');
                wrap.find('[data-gdh-tab]').removeClass('is-active');
                wrap.find('[data-gdh-tab="' + target + '"]').addClass('is-active');
                if ('development' === target && !state.developmentLoaded) {
                    loadDevelopment(false);
                }
                if ('imf-macro' === target && !state.imfLoaded) {
                    loadImf(false);
                }
                if ('digital-connectivity' === target && !state.digitalLoaded) {
                    loadDigital(false);
                }
                if ('population-society' === target && !state.populationLoaded) {
                    loadPopulation(false);
                }
                if ('oecd-insights' === target && !state.oecdLoaded) {
                    loadOecd(false);
                }
                if ('health' === target && !state.healthLoaded) {
                    loadHealth(false);
                }
                if ('medical-evidence' === target && state.medicalQuery && !state.medicalLoaded) {
                    loadMedical(state.medicalQuery, false);
                }
                if ('compare-countries' === target && !state.compareLoaded) {
                    loadCompare(false);
                }
            })
            .on('click', '[data-gdh-refresh]', function () {
                loadTourism(true);
                if (state.developmentLoaded || root().find('[data-gdh-tab="development"]').hasClass('is-active')) {
                    loadDevelopment(true);
                }
                if (state.imfLoaded || root().find('[data-gdh-tab="imf-macro"]').hasClass('is-active')) {
                    loadImf(true);
                }
                if (state.digitalLoaded || root().find('[data-gdh-tab="digital-connectivity"]').hasClass('is-active')) {
                    loadDigital(true);
                }
                if (state.populationLoaded || root().find('[data-gdh-tab="population-society"]').hasClass('is-active')) {
                    loadPopulation(true);
                }
                if (state.oecdLoaded || root().find('[data-gdh-tab="oecd-insights"]').hasClass('is-active')) {
                    loadOecd(true);
                }
                if (state.healthLoaded || root().find('[data-gdh-tab="health"]').hasClass('is-active')) {
                    loadHealth(true);
                }
                if (state.medicalQuery && (state.medicalLoaded || root().find('[data-gdh-tab="medical-evidence"]').hasClass('is-active'))) {
                    loadMedical(state.medicalQuery, true);
                }
                if (state.compareLoaded || root().find('[data-gdh-tab="compare-countries"]').hasClass('is-active')) {
                    loadCompare(true);
                }
            })
            .on('click', '[data-gdh-compare-load]', function () {
                loadCompare(true);
            })
            .on('click', '[data-gdh-medical-search]', function () {
                loadMedical(root().find('[data-gdh-medical-query="1"]').val(), true);
            })
            .on('keydown', '[data-gdh-medical-query="1"]', function (event) {
                if (13 === event.which) {
                    event.preventDefault();
                    loadMedical($(this).val(), true);
                }
            })
            .on('click', '[data-gdh-save]', function () {
                saveSettings(this);
            });
    }

    function init() {
        if (!root().length) {
            state.initialized = false;
            return;
        }
        bindEvents();
        if (state.initialized) {
            return;
        }
        state.initialized = true;
        loadShell();
        loadTourism(false);
    }

    modules.globalDataHub = { init: init };

    $(document).ready(function () {
        init();
        $(document).on('noesia:shell-updated noesia:section-loaded', init);
    });
})(jQuery);
