// === GLOBAL INSIGHT ENGINE v6 - DOCKER + FASTAPI === // Updated: 2024-01-08-v10 const CONFIG = { maxCountries: 200, correlationThreshold: 0.3, outlierZScore: 2 }; let dataset = [], variableDefs = [], categories = [], selectedVar = null; let corrFilter = 'all', activeCategory = null, activeTab = 'explorer', peerMode = 'global'; let weights = {}, charts = {}, CURRENT_DATASET = null; let compareCountries = []; let currentDatasetId = 'builtin:embed'; // === API BASE === const API_BASE = window.location.origin; async function api(path, opts = {}) { const r = await fetch(`${API_BASE}${path}`, opts); if (!r.ok) throw new Error(await r.text()); return r.json(); } // === MATH === const M = { mean: a => a.length ? a.reduce((x, y) => x + y, 0) / a.length : 0, std: a => { const m = M.mean(a); return a.length > 1 ? Math.sqrt(a.reduce((x, y) => x + (y - m) ** 2, 0) / (a.length - 1)) : 0; }, pearson: (x, y) => { const n = x.length; if (n < 2 || n !== y.length) return 0; const mx = M.mean(x), my = M.mean(y); let num = 0, dx = 0, dy = 0; for (let i = 0; i < n; i++) { const xi = x[i] - mx, yi = y[i] - my; num += xi * yi; dx += xi * xi; dy += yi * yi; } const d = Math.sqrt(dx * dy); return d === 0 ? 0 : num / d; }, normalize: (v, arr) => { const mn = Math.min(...arr), mx = Math.max(...arr); return mx === mn ? 0.5 : (v - mn) / (mx - mn); }, percentile: (v, arr) => { let c = 0; for (let x of arr) if (x <= v) c++; return arr.length ? c / arr.length * 100 : 50; }, zscore: (v, arr) => { const m = M.mean(arr), s = M.std(arr); return s === 0 ? 0 : (v - m) / s; } }; function vals(key, data = dataset) { return data.map(d => d[key]).filter(v => v != null && !isNaN(v)); } function getCorrelations(key, data = dataset) { return variableDefs.filter(v => v.key !== key && data.some(d => d[v.key] != null)) .map(v => ({ ...v, r: M.pearson(vals(key, data), vals(v.key, data)) })) .filter(c => !isNaN(c.r)).sort((a, b) => Math.abs(b.r) - Math.abs(a.r)); } function corrStrength(r) { const a = Math.abs(r); return a >= 0.9 ? 'Very Strong' : a >= 0.7 ? 'Strong' : a >= 0.5 ? 'Moderate' : a >= 0.3 ? 'Weak' : 'Negligible'; } function showStatus(msg, pct) { const bar = document.getElementById('statusBar'); if (!bar) return; bar.classList.add('visible'); const st = document.getElementById('statusText'); if (st) st.textContent = msg; const sp = document.getElementById('statusProgress'); if (sp) sp.style.width = pct + '%'; const spt = document.getElementById('statusPercent'); if (spt) spt.textContent = pct + '%'; if (pct >= 100) setTimeout(() => bar.classList.remove('visible'), 800); } // === DATASET LOADING === const DATASET_PACKS = []; async function loadDefaultDataset() { showStatus('Loading dataset...', 10); try { // Try to load a curated preset from the backend const result = await api('/api/datasets/builtin/hdi_2022'); if (result && result.data && result.data.length > 0) { DATASET.length = 0; result.data.forEach(d => DATASET.push(d)); VARIABLE_DEFS.length = 0; result.indicators.forEach(v => VARIABLE_DEFS.push(v)); DATASET_PACKS.length = 0; DATASET_PACKS.push({ name: result.name, source: result.source, description: result.description, variableCount: VARIABLE_DEFS.length, lastUpdated: result.last_updated, requiresKey: false, dataset: DATASET, variables: VARIABLE_DEFS, loaded: true, file: 'builtin:hdi_2022' }); CURRENT_DATASET = DATASET_PACKS[0]; currentDatasetId = 'builtin:hdi_2022'; showStatus('Loaded Human Development Index', 50); return; } } catch (e) { console.log('Backend builtin unavailable, trying WB live', e); } try { const defaults = 'gdp_per_capita,life_expectancy,population,electricity_access,internet_users,co2_per_capita,renewable_energy,gini,unemployment,health_exp_per_capita,infant_mortality,sanitation'; const result = await api(`/api/worldbank/fetch?indicators=${defaults}&countries=all&date_range=2020:2023&latest_only=true`); if (result.data && result.data.length > 0) { DATASET.length = 0; result.data.forEach(d => DATASET.push(d)); const keys = Object.keys(DATASET[0]).filter(x => x !== 'country'); window.VARIABLE_DEFS = keys.map(x => ({ key: x, name: x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()), unit: '', category: 'General', desc: 'World Bank indicator', icon: 'bar-chart-3', higherIsBetter: null })); DATASET_PACKS.length = 0; DATASET_PACKS.push({ name: 'World Bank Live', source: 'backend', description: 'Live World Bank indicators', variableCount: VARIABLE_DEFS.length, lastUpdated: '2024', requiresKey: false, dataset: DATASET, variables: VARIABLE_DEFS, loaded: true, file: 'backend' }); CURRENT_DATASET = DATASET_PACKS[0]; currentDatasetId = 'builtin:wb_live'; showStatus('Live data loaded', 50); return; } } catch (e) { console.log('Backend unavailable, using embedded', e); } initDatasetSystem(); showStatus('Embedded data loaded', 50); } function initDatasetSystem() { DATASET_PACKS.length = 0; if (typeof DATASET !== 'undefined' && DATASET.length > 0) { if (typeof VARIABLE_DEFS === 'undefined' || !VARIABLE_DEFS.length) { const k = Object.keys(DATASET[0]).filter(x => !['country', 'code', 'region', 'income'].includes(x)); window.VARIABLE_DEFS = k.map(x => ({ key: x, name: x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()), unit: '', category: 'General', desc: 'Indicator', icon: 'bar-chart-3', higherIsBetter: null })); } DATASET_PACKS.push({ name: 'World Bank Core', source: 'dataset_embed.js', description: 'Economic, health, and social indicators', variableCount: VARIABLE_DEFS.length, lastUpdated: '2024', requiresKey: false, dataset: DATASET, variables: VARIABLE_DEFS, loaded: true, file: 'dataset_embed.js' }); CURRENT_DATASET = DATASET_PACKS[0]; } } function switchToDataset(packName) { const pack = DATASET_PACKS.find(p => p.name === packName); if (!pack) return false; DATASET.length = 0; pack.dataset.forEach(d => DATASET.push(d)); VARIABLE_DEFS.length = 0; pack.variables.forEach(v => VARIABLE_DEFS.push(v)); dataset = DATASET; variableDefs = VARIABLE_DEFS; categories = [...new Set(variableDefs.map(v => v.category))]; weights = {}; variableDefs.forEach(v => weights[v.key] = 1); selectedVar = null; corrFilter = 'all'; activeCategory = null; document.getElementById('emptyState').classList.remove('hidden'); document.getElementById('resultsArea').classList.add('hidden'); const vs = document.getElementById('varSearch'); if (vs) vs.value = ''; showStatus('Loaded ' + pack.name, 100); renderCategoryGrid(); renderVariableList(); initDecisionFramework(); initBenchmark(); initSimulatorUI(); initCompareUI(); lucide.createIcons(); CURRENT_DATASET = pack; const dp2 = document.getElementById('dataPointCount'); if (dp2) dp2.innerHTML = `${variableDefs.length} variables`; return true; } // === DATASET LIBRARY CATALOG === const DATASET_CATALOG = { builtin: [ { id: 'happiness_2023', name: 'World Happiness Report 2023', category: 'Wellbeing', source: 'UN SDSN', description: 'Happiness, social support, freedom, generosity, corruption perceptions', icon: 'heart', color: 'rose' }, { id: 'hdi_2022', name: 'Human Development Index 2021/2022', category: 'Development', source: 'UNDP', description: 'HDI, life expectancy, schooling, GNI per capita', icon: 'users', color: 'blue' }, { id: 'epi_2022', name: 'Environmental Performance Index 2022', category: 'Environment', source: 'Yale/Columbia', description: 'Ecosystem vitality, environmental health, air quality, biodiversity', icon: 'leaf', color: 'green' }, { id: 'peace_2023', name: 'Global Peace Index 2023', category: 'Security', source: 'IEP', description: 'Peace, safety, militarization, conflict, terrorism', icon: 'shield', color: 'indigo' }, { id: 'press_freedom_2023', name: 'Press Freedom Index 2023', category: 'Governance', source: 'RSF', description: 'Press freedom, safety of journalists, media independence', icon: 'newspaper', color: 'amber' }, { id: 'corruption_perceptions_2023', name: 'Corruption Perceptions Index 2023', category: 'Governance', source: 'Transparency Int.', description: 'Perceived public sector corruption, ranking', icon: 'scale', color: 'purple' }, { id: 'labor_rights_2023', name: 'Global Rights Index 2023', category: 'Labor', source: 'ITUC', description: 'Workers rights, collective bargaining, trade unions', icon: 'briefcase', color: 'orange' }, { id: 'cybersecurity_2023', name: 'Global Cybersecurity Index 2023', category: 'Technology', source: 'ITU', description: 'Cybersecurity readiness, legal, technical, cooperation', icon: 'lock', color: 'cyan' }, { id: 'food_security_2023', name: 'Global Food Security Index 2022', category: 'Food', source: 'Economist Impact', description: 'Food affordability, availability, quality, sustainability', icon: 'utensils', color: 'emerald' }, { id: 'innovation_2023', name: 'Global Innovation Index 2023', category: 'Innovation', source: 'WIPO', description: 'Innovation capacity, outputs, institutions, infrastructure', icon: 'lightbulb', color: 'yellow' }, { id: 'digital_competitiveness_2023', name: 'IMD Digital Competitiveness 2023', category: 'Digital', source: 'IMD', description: 'Knowledge, technology, future readiness of digital economies', icon: 'cpu', color: 'sky' }, { id: 'gini_ref_2022', name: 'Income Inequality Reference', category: 'Social', source: 'World Bank', description: 'Gini index, income shares, Palma ratio', icon: 'bar-chart-2', color: 'pink' }, ], wb_presets: [ { id: 'wb:economy', name: 'Economy', description: 'GDP, growth, debt, trade, FDI, industry', indicators: 25, icon: 'trending-up', color: 'emerald' }, { id: 'wb:health', name: 'Health', description: 'Life expectancy, mortality, health spending, disease', indicators: 25, icon: 'heart-pulse', color: 'rose' }, { id: 'wb:education', name: 'Education', description: 'Enrollment, literacy, years of schooling, spending', indicators: 20, icon: 'graduation-cap', color: 'blue' }, { id: 'wb:environment', name: 'Environment', description: 'CO2, renewables, forest, water, emissions, biodiversity', indicators: 25, icon: 'trees', color: 'green' }, { id: 'wb:social', name: 'Social & Demographics', description: 'Population, gender, inequality, migration', indicators: 20, icon: 'users', color: 'purple' }, { id: 'wb:governance', name: 'Governance & Business', description: 'Business climate, taxes, legal, women participation', indicators: 20, icon: 'landmark', color: 'amber' }, { id: 'wb:digital', name: 'Digital & Infrastructure', description: 'Internet, broadband, ICT, e-government', indicators: 15, icon: 'wifi', color: 'cyan' }, { id: 'wb:tourism', name: 'Tourism', description: 'International arrivals, tourism receipts', indicators: 5, icon: 'plane', color: 'sky' }, { id: 'wb:full', name: 'Full World Bank (120+)', description: 'Comprehensive set of all available indicators', indicators: 120, icon: 'database', color: 'slate' }, ] }; // === DATASET BROWSER === async function showDatasetBrowser() { let existing = document.getElementById('datasetBrowserModal'); if (existing) existing.remove(); const modal = document.createElement('div'); modal.id = 'datasetBrowserModal'; modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4'; modal.onclick = e => { if (e.target === modal) modal.remove(); }; // Build tab content as strings first const builtinCards = DATASET_CATALOG.builtin.map(ds => { const isActive = CURRENT_DATASET && CURRENT_DATASET.file === ds.id; return `
${ds.name}
${ds.source} · ${ds.category}
${isActive ? 'Active' : ''}
${ds.description}
`; }).join(''); const wbCards = DATASET_CATALOG.wb_presets.map(p => `
${p.name}
${p.indicators} variables
${p.description}
`).join(''); const categoryColors = { 'Economy': 'emerald', 'Health': 'rose', 'Education': 'blue', 'Environment': 'green', 'Social': 'purple', 'Governance': 'amber', 'Digital': 'cyan', 'Tourism': 'sky', 'Security': 'indigo', 'Wellbeing': 'pink', 'Innovation': 'yellow', 'Labor': 'orange', 'Food': 'emerald', 'Technology': 'cyan', 'Development': 'blue', 'General': 'slate', 'Climate': 'teal', 'Infrastructure': 'sky' }; modal.innerHTML = `

Data Library

Built-in Reference Datasets
${builtinCards}
`; document.body.appendChild(modal); lucide.createIcons(); } function switchLibTab(tab) { document.querySelectorAll('.lib-tab').forEach(t => { t.classList.remove('text-brand-300', 'border-brand-500'); t.classList.add('text-slate-400', 'border-transparent'); }); document.getElementById('libTab-' + tab).classList.remove('text-slate-400', 'border-transparent'); document.getElementById('libTab-' + tab).classList.add('text-brand-300', 'border-brand-500'); ['curated','live','upload'].forEach(t => document.getElementById('libPane-' + t).classList.add('hidden')); document.getElementById('libPane-' + tab).classList.remove('hidden'); } async function loadBuiltinDataset(datasetId) { showStatus('Loading ' + datasetId + '...', 20); try { const result = await api('/api/datasets/builtin/' + datasetId); if (!result || !result.data || !result.data.length) { showStatus('No data returned', 100); return; } DATASET.length = 0; result.data.forEach(d => DATASET.push(d)); VARIABLE_DEFS.length = 0; result.indicators.forEach(v => VARIABLE_DEFS.push(v)); dataset = DATASET; variableDefs = VARIABLE_DEFS; categories = [...new Set(variableDefs.map(v => v.category))]; weights = {}; variableDefs.forEach(v => weights[v.key] = 1); selectedVar = null; corrFilter = 'all'; activeCategory = null; document.getElementById('emptyState').classList.remove('hidden'); document.getElementById('resultsArea').classList.add('hidden'); const vs = document.getElementById('varSearch'); if (vs) vs.value = ''; showStatus('Loaded ' + result.name, 100); renderCategoryGrid(); renderVariableList(); initDecisionFramework(); initBenchmark(); initSimulatorUI(); initCompareUI(); lucide.createIcons(); CURRENT_DATASET = { name: result.name, source: result.source, description: result.description, variableCount: variableDefs.length, lastUpdated: result.last_updated, requiresKey: false, dataset: DATASET, variables: VARIABLE_DEFS, loaded: true, file: datasetId }; const dp2 = document.getElementById('dataPointCount'); if (dp2) dp2.innerHTML = `${variableDefs.length} variables`; } catch (e) { showStatus('Failed: ' + e.message, 100); console.error(e); } } async function fetchWorldBankPreset(presetId) { const preset = DATASET_CATALOG.wb_presets.find(p => p.id === presetId); if (!preset) { showStatus('Preset not found', 100); return; } showStatus('Fetching ' + preset.name + '...', 20); try { const resp = await api('/api/sources/list'); const p = (resp.sources && resp.sources.worldbank_presets || []).find(x => x.id === presetId); if (!p) { showStatus('Preset not found on server', 100); return; } const result = await api(`/api/worldbank/fetch?indicators=${p.indicators}&countries=all&date_range=2020:2023`); if (!result.data || !result.data.length) { showStatus('No data returned', 100); return; } const keys = Object.keys(result.data[0]).filter(x => x !== 'country'); const vars = keys.map(x => ({ key: x, name: x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()), unit: '', category: preset.name, desc: 'World Bank indicator', icon: 'bar-chart-3', higherIsBetter: null })); DATASET.length = 0; result.data.forEach(d => DATASET.push(d)); VARIABLE_DEFS.length = 0; vars.forEach(v => VARIABLE_DEFS.push(v)); dataset = DATASET; variableDefs = VARIABLE_DEFS; categories = [...new Set(variableDefs.map(v => v.category))]; weights = {}; variableDefs.forEach(v => weights[v.key] = 1); selectedVar = null; corrFilter = 'all'; activeCategory = null; document.getElementById('emptyState').classList.remove('hidden'); document.getElementById('resultsArea').classList.add('hidden'); showStatus(`Loaded ${preset.name} (${vars.length} variables)`, 100); renderCategoryGrid(); renderVariableList(); initDecisionFramework(); initBenchmark(); initSimulatorUI(); initCompareUI(); lucide.createIcons(); CURRENT_DATASET = { name: 'WB: ' + preset.name, source: 'World Bank API', description: preset.description, variableCount: vars.length, lastUpdated: '2024', requiresKey: false, dataset: DATASET, variables: VARIABLE_DEFS, loaded: true, file: presetId }; const dp2 = document.getElementById('dataPointCount'); if (dp2) dp2.innerHTML = `${variableDefs.length} variables`; } catch (e) { showStatus('Fetch failed: ' + e.message, 100); } } async function fetchCustomWBIndicators() { showStatus('Loading indicator catalog...', 10); try { const wb = await api('/api/worldbank/indicators'); if (!wb.indicators) { showStatus('Catalog unavailable', 100); return; } const indList = wb.indicators.map(i => ``).join(''); let modal = document.createElement('div'); modal.id = 'customWBModal'; modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4'; modal.onclick = e => { if (e.target === modal) modal.remove(); }; modal.innerHTML = `

Custom World Bank Indicators

Hold Ctrl/Cmd to select multiple. Selected: 0

`; document.body.appendChild(modal); lucide.createIcons(); const sel = document.getElementById('wbIndicatorSelect'); if (sel) sel.addEventListener('change', () => { const cnt = document.getElementById('wbSelCount'); if (cnt) cnt.textContent = sel.selectedOptions.length; }); } catch (e) { showStatus('Catalog load failed', 100); } } async function fetchWorldBankData() { const sel = document.getElementById('wbIndicatorSelect'); if (!sel) return; const selected = Array.from(sel.selectedOptions).map(o => o.value); if (!selected.length) { showStatus('Select at least one indicator', 100); return; } showStatus('Fetching World Bank data...', 30); try { const result = await api(`/api/worldbank/fetch?indicators=${selected.join(',')}&countries=all&date_range=2020:2023`); if (!result.data || !result.data.length) { showStatus('No data returned', 100); return; } const keys = Object.keys(result.data[0]).filter(x => x !== 'country'); const vars = keys.map(x => ({ key: x, name: x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()), unit: '', category: 'World Bank', desc: 'World Bank indicator', icon: 'bar-chart-3', higherIsBetter: null })); DATASET.length = 0; result.data.forEach(d => DATASET.push(d)); VARIABLE_DEFS.length = 0; vars.forEach(v => VARIABLE_DEFS.push(v)); dataset = DATASET; variableDefs = VARIABLE_DEFS; categories = [...new Set(variableDefs.map(v => v.category))]; weights = {}; variableDefs.forEach(v => weights[v.key] = 1); selectedVar = null; corrFilter = 'all'; activeCategory = null; document.getElementById('emptyState').classList.remove('hidden'); document.getElementById('resultsArea').classList.add('hidden'); const vs = document.getElementById('varSearch'); if (vs) vs.value = ''; CURRENT_DATASET = { name: 'World Bank Custom', source: 'backend', description: `${selected.length} indicators fetched`, variableCount: vars.length }; showStatus(`Loaded ${vars.length} variables`, 100); renderCategoryGrid(); renderVariableList(); initDecisionFramework(); initBenchmark(); initSimulatorUI(); initCompareUI(); lucide.createIcons(); const dp3 = document.getElementById('dataPointCount'); if (dp3) dp3.innerHTML = `${variableDefs.length} variables`; } catch (e) { showStatus('Fetch failed: ' + e.message, 100); } } async function fetchClimateData() { showStatus('Fetching climate data...', 30); try { const result = await api('/api/climate/fetch'); if (!result.data || !result.data.length) { showStatus('No climate data', 100); return; } const keys = Object.keys(result.data[0]).filter(x => x !== 'country'); const vars = keys.map(x => ({ key: x, name: x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()), unit: '', category: 'Climate', desc: 'Open-Meteo climate data', icon: 'cloud', higherIsBetter: null })); DATASET.length = 0; result.data.forEach(d => DATASET.push(d)); VARIABLE_DEFS.length = 0; vars.forEach(v => VARIABLE_DEFS.push(v)); dataset = DATASET; variableDefs = VARIABLE_DEFS; categories = [...new Set(variableDefs.map(v => v.category))]; weights = {}; variableDefs.forEach(v => weights[v.key] = 1); selectedVar = null; CURRENT_DATASET = { name: 'Climate Data', source: 'Open-Meteo', description: 'Capital city climate averages', variableCount: vars.length }; showStatus(`Loaded ${vars.length} variables`, 100); renderCategoryGrid(); renderVariableList(); initDecisionFramework(); initBenchmark(); initSimulatorUI(); initCompareUI(); lucide.createIcons(); const dp4 = document.getElementById('dataPointCount'); if (dp4) dp4.innerHTML = `${variableDefs.length} variables`; } catch (e) { showStatus('Climate fetch failed: ' + e.message, 100); } } function selectDatasetPack(name) { switchToDataset(name); } // === CORE === async function init() { showStatus('Initializing...', 10); await loadDefaultDataset(); dataset = DATASET; variableDefs = VARIABLE_DEFS; categories = [...new Set(variableDefs.map(v => v.category))]; variableDefs.forEach(v => weights[v.key] = 1); showStatus('Processing...', 40); lucide.createIcons(); initTabs(); initExplorer(); initDecisionFramework(); initBenchmark(); initSimulatorUI(); initCompareUI(); restoreFromURL(); showStatus('Ready', 100); const dp = document.getElementById('dataPointCount'); if (dp) dp.innerHTML = `${variableDefs.length} variables`; } function initTabs() { document.querySelectorAll('.tab-btn').forEach(btn => { btn.addEventListener('click', () => switchTab(btn.dataset.tab)); }); } function switchTab(tab) { activeTab = tab; document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden')); const tc = document.getElementById('tab-' + tab); if (tc) tc.classList.remove('hidden'); document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active')); const tbtn = document.getElementById('tab-btn-' + tab); if (tbtn) tbtn.classList.add('active'); if (tab === 'outliers') renderOutliers(); if (tab === 'decisions') calculateDecisionScores(); if (tab === 'discover') renderGemDiscovery(); if (tab === 'compare') renderCompareResults(); lucide.createIcons(); pushURLState(); } // === URL STATE === function pushURLState() { const state = { tab: activeTab, var: selectedVar, cat: activeCategory, corr: corrFilter, peers: peerMode, compare: compareCountries }; const hash = btoa(JSON.stringify(state)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); history.replaceState(null, '', '#' + hash); } function restoreFromURL() { try { const hash = location.hash.slice(1); if (!hash) return; const state = JSON.parse(atob(hash.replace(/-/g, '+').replace(/_/g, '/'))); if (state.tab && document.getElementById('tab-btn-' + state.tab)) switchTab(state.tab); if (state.cat) selectCategory(state.cat); if (state.corr) setCorrFilter(state.corr); if (state.peers) setPeerMode(state.peers); if (state.compare) { compareCountries = state.compare; renderCompareResults(); } if (state.var) setTimeout(() => selectVariable(state.var), 300); } catch (e) { /* ignore */ } } function shareSession() { pushURLState(); navigator.clipboard.writeText(location.href).then(() => { showStatus('Share link copied!', 100); }); } // === EXPLORER === function initExplorer() { renderCategoryGrid(); renderVariableList(); } function renderCategoryGrid() { const cont = document.getElementById('categoryGrid'); if (!cont) return; cont.innerHTML = categories.map(cat => ` `).join(''); lucide.createIcons(); } function selectCategory(cat) { if (activeCategory === cat) { clearCategoryFilter(); return; } activeCategory = cat; const vs = document.getElementById('varSearch'); if (vs) vs.value = ''; renderCategoryGrid(); renderVariableList(); } function clearCategoryFilter() { activeCategory = null; const vs = document.getElementById('varSearch'); if (vs) vs.value = ''; renderCategoryGrid(); renderVariableList(); } function renderVariableList() { const searchEl = document.getElementById('varSearch'); const search = searchEl ? searchEl.value.toLowerCase().trim() : ''; const filtered = variableDefs.filter(v => { const ms = v.name.toLowerCase().includes(search) || v.category.toLowerCase().includes(search); const mc = !activeCategory || v.category === activeCategory; return ms && mc; }); const vc = document.getElementById('varCount'); if (vc) vc.textContent = filtered.length + ' available'; const listEl = document.getElementById('variableList'); const clearWrap = document.getElementById('clearCatWrap'); const shouldShow = activeCategory !== null || search.length > 0; if (shouldShow) { if (listEl) { listEl.classList.remove('hidden'); listEl.innerHTML = filtered.map(v => ` `).join(''); } if (clearWrap) clearWrap.classList.toggle('hidden', activeCategory === null); } else { if (listEl) { listEl.classList.add('hidden'); listEl.innerHTML = ''; } if (clearWrap) clearWrap.classList.add('hidden'); } lucide.createIcons(); } function filterVariables() { renderVariableList(); } // === PEER MODE === function setPeerMode(mode) { peerMode = mode; document.querySelectorAll('.peer-toggle').forEach(el => el.classList.remove('active')); const el = document.getElementById('peer' + (mode === 'global' ? 'Global' : 'Regional')); if (el) el.classList.add('active'); if (selectedVar) updateExplorer(); pushURLState(); } function getPeerData(country) { if (peerMode === 'global') return dataset; const d = dataset.find(x => x.country === country); if (!d || !d.region) return dataset; return dataset.filter(x => x.region === d.region); } // === VARIABLE SELECTION === function selectVariable(key) { selectedVar = key; document.getElementById('emptyState').classList.add('hidden'); document.getElementById('resultsArea').classList.remove('hidden'); const pc = document.getElementById('peerToggleContainer'); if (pc) pc.style.display = 'flex'; renderVariableList(); updateExplorer(); pushURLState(); } function updateExplorer() { const v = variableDefs.find(d => d.key === selectedVar); if (!v) return; const values = vals(selectedVar); const corrs = getCorrelations(selectedVar); const hc = document.getElementById('heroCategory'); if (hc) hc.textContent = v.category; const ht = document.getElementById('heroType'); if (ht) ht.textContent = v.unit; const hn = document.getElementById('heroName'); if (hn) hn.textContent = v.name; const hd = document.getElementById('heroDesc'); if (hd) hd.textContent = v.desc; const hm = document.getElementById('heroMean'); if (hm) hm.textContent = M.mean(values).toFixed(1); const hs = document.getElementById('heroStd'); if (hs) hs.textContent = M.std(values).toFixed(2); const hr = document.getElementById('heroRange'); if (hr) hr.textContent = Math.min(...values).toFixed(1) + '-' + Math.max(...values).toFixed(1); renderRiskOpportunity(v, corrs); renderInsightBanners(v, corrs); renderDistribution(values, v); renderNetworkGraph(v, corrs); renderCorrelationBars(corrs); initScatterSelect(corrs); updateScatterPlot(); renderInsightCards(v, corrs); renderHeatmap(); generateNarrative(v, corrs); } // === NARRATIVE === function generateNarrative(v, corrs) { const panel = document.getElementById('narrativePanel'); const textEl = document.getElementById('narrativeText'); if (!panel || !textEl) return; panel.classList.remove('hidden'); const strongest = corrs[0]; const neg = corrs.filter(c => c.r < -0.3).sort((a, b) => a.r - b.r)[0]; const pos = corrs.filter(c => c.r > 0.5).sort((a, b) => b.r - a.r)[0]; const cross = corrs.find(c => Math.abs(c.r) >= 0.5 && c.category !== v.category); const topCountry = [...dataset].sort((a, b) => (b[v.key] || 0) - (a[v.key] || 0))[0]; const bottomCountry = [...dataset].sort((a, b) => (a[v.key] || 0) - (b[v.key] || 0))[0]; let narrative = `${v.name} (${v.category}) varies widely. `; if (topCountry && topCountry[v.key] != null && bottomCountry && bottomCountry[v.key] != null) { narrative += `${topCountry.country} leads with ${topCountry[v.key].toFixed(1)} ${v.unit}, while ${bottomCountry.country} records ${bottomCountry[v.key].toFixed(1)} ${v.unit}. `; } if (strongest) { narrative += `Its ${strongest.r >= 0 ? 'strongest positive' : 'strongest negative'} link is with ${strongest.name} (${corrStrength(strongest.r)}, r=${strongest.r.toFixed(2)}). `; } if (cross) { narrative += `Notably, ${v.name.toLowerCase()} shows a ${corrStrength(cross.r)} cross-domain relationship with ${cross.name} (${cross.category}), suggesting interconnected policy levers. `; } if (neg) { narrative += `There is a risk signal: higher ${v.name.toLowerCase()} is associated with lower ${neg.name.toLowerCase()} (r=${neg.r.toFixed(2)}). `; } if (pos) { narrative += `An opportunity emerges: ${v.name.toLowerCase()} and ${pos.name.toLowerCase()} move together (r=${pos.r.toFixed(2)}), suggesting coordinated investment may yield dual returns.`; } textEl.textContent = narrative; } // === RISK / OPPORTUNITY / BANNERS === function renderRiskOpportunity(v, corrs) { const cont = document.getElementById('riskOpportunityBanner'); if (!cont) return; const risks = corrs.filter(c => c.r < -0.3).sort((a, b) => a.r - b.r); const opps = corrs.filter(c => c.r > 0.5).sort((a, b) => b.r - a.r); let html = ''; if (risks.length > 0) { const r = risks[0]; html += `
RISK FACTOR
${v.name} ↔ ${r.name}
Higher ${v.name.toLowerCase()} linked to lower ${r.name.toLowerCase()}.
`; } if (opps.length > 0) { const o = opps[0]; html += `
OPPORTUNITY
${v.name} ↔ ${o.name}
Strong positive link.
`; } cont.innerHTML = html; lucide.createIcons(); } function renderInsightBanners(v, corrs) { const cont = document.getElementById('insightBanners'); if (!cont) return; if (!corrs.length) { cont.innerHTML = ''; return; } const strongest = corrs[0]; const neg = corrs.filter(c => c.r < 0); const strong = corrs.filter(c => Math.abs(c.r) >= 0.5); let html = `
Strongest Connection
${v.name} → ${strongest.name}
${corrStrength(strongest.r)} ${strongest.r >= 0 ? 'positive' : 'negative'} (r=${strongest.r.toFixed(3)}).
`; if (neg.length > 0) { const n = neg.sort((a, b) => a.r - b.r)[0]; html += `
Inverse Relationship
${v.name} ↯ ${n.name}
As ${v.name.toLowerCase()} rises, ${n.name.toLowerCase()} tends to fall (r=${n.r.toFixed(3)}).
`; } const cross = corrs.find(c => Math.abs(c.r) >= 0.5 && c.category !== v.category); if (cross) { html += `
Cross-Domain Insight
${v.name} ↔ ${cross.name}
${v.category} ↔ ${cross.category}: hidden relationship!
`; } html += `
Summary
${strong.length} strong connections
${strong.length} of ${corrs.length} variables show |r| >= 0.5.
`; cont.innerHTML = html; lucide.createIcons(); } // === DISTRIBUTION CHART === function renderDistribution(values, v) { const mn = Math.min(...values), mx = Math.max(...values); const bins = 12, bw = (mx - mn) / bins || 1; const hist = new Array(bins).fill(0); values.forEach(val => { let idx = Math.floor((val - mn) / bw); if (idx >= bins) idx = bins - 1; hist[idx]++; }); const labels = hist.map((_, i) => (mn + i * bw).toFixed(0)); if (charts.distribution) charts.distribution.destroy(); const el = document.getElementById('distributionChart'); if (!el) return; charts.distribution = new Chart(el, { type: 'bar', data: { labels, datasets: [{ data: hist, backgroundColor: 'rgba(6,182,212,0.3)', borderColor: 'rgba(6,182,212,0.7)', borderWidth: 1, borderRadius: 4 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { grid: { color: 'rgba(148,163,184,0.05)' }, ticks: { color: '#64748b', font: { size: 10 } } }, y: { grid: { color: 'rgba(148,163,184,0.05)' }, ticks: { color: '#64748b', font: { size: 10 } } } } } }); } // === NETWORK GRAPH === function renderNetworkGraph(v, corrs) { const canvas = document.getElementById('networkCanvas'); if (!canvas) return; const rect = canvas.parentElement.getBoundingClientRect(); if (rect.width < 10 || rect.height < 10) return; canvas.width = rect.width * 2; canvas.height = rect.height * 2; canvas.style.width = rect.width + 'px'; canvas.style.height = rect.height + 'px'; const ctx = canvas.getContext('2d'); ctx.scale(2, 2); const w = rect.width, h = rect.height; ctx.clearRect(0, 0, w, h); const centerNode = { x: w / 2, y: h / 2, label: v.name, color: '#22d3ee' }; const nodes = corrs.slice(0, 12).map((c, i) => { const angle = (i / 12) * Math.PI * 2 - Math.PI / 2; const dist = 60 + Math.abs(c.r) * 60; return { x: w / 2 + Math.cos(angle) * dist, y: h / 2 + Math.sin(angle) * dist, label: c.name, r: c.r, color: c.r >= 0 ? '#22d3ee' : '#f43f5e', category: c.category }; }); nodes.forEach(node => { ctx.beginPath(); ctx.moveTo(centerNode.x, centerNode.y); ctx.lineTo(node.x, node.y); ctx.strokeStyle = node.r >= 0 ? `rgba(34,211,238,${Math.abs(node.r) * 0.5})` : `rgba(244,63,94,${Math.abs(node.r) * 0.5})`; ctx.lineWidth = Math.abs(node.r) * 3; ctx.stroke(); }); ctx.beginPath(); ctx.arc(centerNode.x, centerNode.y, 20, 0, Math.PI * 2); ctx.fillStyle = 'rgba(6,182,212,0.25)'; ctx.fill(); ctx.strokeStyle = '#22d3ee'; ctx.lineWidth = 2; ctx.stroke(); ctx.fillStyle = '#fff'; ctx.font = '500 9px Inter'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(centerNode.label.slice(0, 12), centerNode.x, centerNode.y); nodes.forEach(node => { ctx.beginPath(); ctx.arc(node.x, node.y, 8 + Math.abs(node.r) * 6, 0, Math.PI * 2); ctx.fillStyle = node.r >= 0 ? `rgba(34,211,238,${0.15 + Math.abs(node.r) * 0.3})` : `rgba(244,63,94,${0.15 + Math.abs(node.r) * 0.3})`; ctx.fill(); ctx.strokeStyle = node.color; ctx.lineWidth = 1.5; ctx.stroke(); ctx.fillStyle = '#94a3b8'; ctx.font = '400 8px Inter'; ctx.fillText(node.label.slice(0, 14), node.x, node.y + 18); }); } // === CORRELATION BARS === function renderCorrelationBars(corrs) { let filtered = corrs; if (corrFilter === 'positive') filtered = corrs.filter(c => c.r > 0); if (corrFilter === 'negative') filtered = corrs.filter(c => c.r < 0); const el = document.getElementById('correlationBars'); if (!el) return; el.innerHTML = filtered.slice(0, 20).map((c, i) => `
${c.name}
${c.r >= 0 ? '+' : ''}${c.r.toFixed(3)}
`).join(''); lucide.createIcons(); } function setCorrFilter(f) { corrFilter = f; ['filterAll', 'filterPos', 'filterNeg'].forEach(id => { const el = document.getElementById(id); if (!el) return; const isActive = (id === 'filterAll' && f === 'all') || (id === 'filterPos' && f === 'positive') || (id === 'filterNeg' && f === 'negative'); el.className = isActive ? 'px-3 py-1 rounded-md text-xs bg-brand-500/20 text-brand-300 border border-brand-500/30' : 'px-3 py-1 rounded-md text-xs bg-slate-800/50 text-slate-400 border border-slate-700/50 hover:border-slate-600'; }); renderCorrelationBars(getCorrelations(selectedVar)); pushURLState(); } // === SCATTER PLOT === function initScatterSelect(corrs) { const el = document.getElementById('scatterVarSelect'); if (el) el.innerHTML = corrs.map(c => ``).join(''); } function updateScatterPlot() { const v1 = selectedVar, v2El = document.getElementById('scatterVarSelect'); if (!v2El) return; const v2 = v2El.value; if (!v1 || !v2) return; const d1 = variableDefs.find(v => v.key === v1), d2 = variableDefs.find(v => v.key === v2); const data = dataset.map(d => ({ x: d[v1], y: d[v2], label: d.country })).filter(p => p.x != null && p.y != null); if (charts.scatter) charts.scatter.destroy(); const el = document.getElementById('scatterChart'); if (!el) return; charts.scatter = new Chart(el, { type: 'scatter', data: { datasets: [{ data, backgroundColor: 'rgba(6,182,212,0.5)', borderColor: 'rgba(148,163,184,0.2)', borderWidth: 1, pointRadius: 5, pointHoverRadius: 7 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { callbacks: { label: ctx => `${ctx.raw.label}: (${d1.name}=${ctx.raw.x?.toFixed(1)}, ${d2.name}=${ctx.raw.y?.toFixed(1)})` } } }, scales: { x: { title: { display: true, text: `${d1.name} (${d1.unit})`, color: '#94a3b8', font: { size: 11 } }, grid: { color: 'rgba(148,163,184,0.05)' }, ticks: { color: '#64748b', font: { size: 10 } } }, y: { title: { display: true, text: `${d2.name} (${d2.unit})`, color: '#94a3b8', font: { size: 11 } }, grid: { color: 'rgba(148,163,184,0.05)' }, ticks: { color: '#64748b', font: { size: 10 } } } } } }); } // === HEATMAP === function renderHeatmap() { const canvas = document.getElementById('heatmapCanvas'); if (!canvas) return; const n = Math.min(20, variableDefs.length); const vars = variableDefs.slice(0, n); const cellSize = 28, padding = 120; const width = n * cellSize + padding, height = n * cellSize + padding; canvas.width = width * 2; canvas.height = height * 2; canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; const ctx = canvas.getContext('2d'); ctx.scale(2, 2); ctx.clearRect(0, 0, width, height); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { const r = i === j ? 1 : M.pearson(vals(vars[i].key), vals(vars[j].key)); const intensity = Math.abs(r); const hue = r >= 0 ? 190 : 350; ctx.fillStyle = `hsla(${hue}, 80%, 50%, ${0.05 + intensity * 0.45})`; ctx.fillRect(padding + j * cellSize, padding + i * cellSize, cellSize - 1, cellSize - 1); if (Math.abs(r) > 0.5) { ctx.fillStyle = 'rgba(255,255,255,0.7)'; ctx.font = '400 7px Inter'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(r.toFixed(2), padding + j * cellSize + cellSize / 2, padding + i * cellSize + cellSize / 2); } } } ctx.fillStyle = '#94a3b8'; ctx.font = '400 8px Inter'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; for (let i = 0; i < n; i++) { ctx.fillText(vars[i].name.slice(0, 18), padding - 6, padding + i * cellSize + cellSize / 2); } ctx.textAlign = 'left'; ctx.textBaseline = 'bottom'; for (let j = 0; j < n; j++) { ctx.save(); ctx.translate(padding + j * cellSize + cellSize / 2, padding - 4); ctx.rotate(-Math.PI / 4); ctx.fillText(vars[j].name.slice(0, 18), 0, 0); ctx.restore(); } } // === INSIGHT CARDS === function renderInsightCards(v, corrs) { const cont = document.getElementById('insightCards'); if (!cont) return; const top = corrs.filter(c => Math.abs(c.r) >= 0.3).slice(0, 8); let html = ''; top.forEach((c, i) => { const isCross = c.category !== v.category; const practical = getPracticalInsight(v.key, c.key, c.r); if (!practical) return; html += `
${c.name}
${isCross ? 'Cross-domain' : ''}${c.r >= 0 ? '+' : ''}${c.r.toFixed(3)}
${practical}
`; }); cont.innerHTML = html; lucide.createIcons(); } function getPracticalInsight(vk, ck, r) { const v = variableDefs.find(x => x.key === vk), c = variableDefs.find(x => x.key === ck); if (!v || !c) return null; if (r >= 0.7) return `Very strong positive: when ${v.name.toLowerCase()} improves, ${c.name.toLowerCase()} follows.`; if (r >= 0.5) return `Moderate positive: ${v.name.toLowerCase()} and ${c.name.toLowerCase()} move together.`; if (r >= 0.3) return `Weak positive trend between ${v.name.toLowerCase()} and ${c.name.toLowerCase()}.`; if (r <= -0.7) return `Strong inverse: higher ${v.name.toLowerCase()} linked to lower ${c.name.toLowerCase()}.`; if (r <= -0.5) return `Moderate inverse: ${v.name.toLowerCase()} and ${c.name.toLowerCase()} oppose.`; if (r <= -0.3) return `Weak negative trend.`; return null; } // === DECISIONS === function initDecisionFramework() { const cont = document.getElementById('weightSliders'); if (!cont) return; cont.innerHTML = variableDefs.map(v => `
${v.name}1
`).join(''); lucide.createIcons(); calculateDecisionScores(); } function updateWeight(key, val) { weights[key] = parseInt(val); const el = document.getElementById('weight-val-' + key); if (el) el.textContent = val; const total = Object.values(weights).reduce((a, b) => a + b, 0); const bar = document.getElementById('weightTotalBar'), txt = document.getElementById('weightTotalText'); if (bar) bar.style.width = Math.min(100, total) + '%'; if (txt) txt.textContent = total + ' / 100'; calculateDecisionScores(); } function resetWeights() { variableDefs.forEach(v => { weights[v.key] = 1; const el = document.getElementById('weight-' + v.key); if (el) el.value = 1; const vl = document.getElementById('weight-val-' + v.key); if (vl) vl.textContent = '1'; }); const bar = document.getElementById('weightTotalBar'), txt = document.getElementById('weightTotalText'); if (bar) bar.style.width = '100%'; if (txt) txt.textContent = '100%'; calculateDecisionScores(); } function calculateDecisionScores() { const totalWeight = Object.values(weights).reduce((a, b) => a + b, 0) || 1; const scores = dataset.map(d => { let score = 0; for (let v of variableDefs) { const val = d[v.key]; if (val == null) continue; const arr = vals(v.key); const norm = M.normalize(val, arr); const w = weights[v.key] / totalWeight; if (v.higherIsBetter === true) score += norm * w; else if (v.higherIsBetter === false) score += (1 - norm) * w; else score += norm * w; } return { country: d.country, score }; }).sort((a, b) => b.score - a.score); renderDecisionResults(scores.slice(0, 10)); renderRadarChart(scores.slice(0, 3)); } function renderDecisionResults(top) { const el = document.getElementById('decisionResults'); if (!el) return; el.innerHTML = top.map((s, i) => `
${i + 1}
${s.country}${Math.round(s.score * 100)}%
`).join(''); } function renderRadarChart(top3) { const canvas = document.getElementById('radarChart'); if (!canvas) return; const rect = canvas.parentElement.getBoundingClientRect(); if (rect.width < 10 || rect.height < 10) return; canvas.width = rect.width * 2; canvas.height = rect.height * 2; canvas.style.width = rect.width + 'px'; canvas.style.height = rect.height + 'px'; const ctx = canvas.getContext('2d'); ctx.scale(2, 2); const w = rect.width, h = rect.height; ctx.clearRect(0, 0, w, h); const cx = w / 2, cy = h / 2, rad = Math.min(cx, cy) - 50; const n = Math.min(8, variableDefs.length); const selectedVars = variableDefs.slice(0, n); const colors = ['#22d3ee', '#f59e0b', '#f43f5e']; for (let i = 1; i <= 5; i++) { ctx.beginPath(); ctx.arc(cx, cy, rad * i / 5, 0, Math.PI * 2); ctx.strokeStyle = 'rgba(148,163,184,0.1)'; ctx.lineWidth = 1; ctx.stroke(); } for (let i = 0; i < n; i++) { const a = -Math.PI / 2 + i * (2 * Math.PI) / n; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(a) * rad, cy + Math.sin(a) * rad); ctx.strokeStyle = 'rgba(148,163,184,0.1)'; ctx.stroke(); ctx.fillStyle = '#94a3b8'; ctx.font = '500 8px Inter'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; const lx = cx + Math.cos(a) * (rad + 18), ly = cy + Math.sin(a) * (rad + 18); ctx.fillText(selectedVars[i].name.slice(0, 10), lx, ly); } top3.forEach((s, si) => { const country = dataset.find(d => d.country === s.country); const pts = selectedVars.map((v, i) => { const a = -Math.PI / 2 + i * (2 * Math.PI) / n; const arr = vals(v.key); const norm = country && country[v.key] != null ? M.normalize(country[v.key], arr) : 0; return { x: cx + Math.cos(a) * rad * norm, y: cy + Math.sin(a) * rad * norm }; }); ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y); pts.slice(1).forEach(p => ctx.lineTo(p.x, p.y)); ctx.closePath(); ctx.fillStyle = colors[si] + '18'; ctx.fill(); ctx.strokeStyle = colors[si]; ctx.lineWidth = 2; ctx.stroke(); ctx.fillStyle = colors[si]; ctx.font = '500 10px Inter'; ctx.textAlign = 'left'; ctx.fillText(s.country, 20, 20 + si * 16); }); } // === BENCHMARK === function initBenchmark() { const cont = document.getElementById('benchmarkInputs'); if (!cont) return; cont.innerHTML = variableDefs.map(v => `
`).join(''); const sel = document.getElementById('benchmarkCountrySelect'); if (sel) sel.innerHTML = '' + dataset.map(d => ``).join(''); } function fillBenchmarkFromCountry() { const cEl = document.getElementById('benchmarkCountrySelect'); if (!cEl) return; const c = cEl.value; if (!c) return; const d = dataset.find(x => x.country === c); variableDefs.forEach(v => { const el = document.getElementById('bench-' + v.key); if (el && d && d[v.key] != null) el.value = d[v.key]; }); } function calculateBenchmark() { const user = { country: 'You' }; variableDefs.forEach(v => { const el = document.getElementById('bench-' + v.key); if (!el) return; const val = parseFloat(el.value); if (!isNaN(val)) user[v.key] = val; }); const results = document.getElementById('benchmarkResults'); if (results) results.classList.remove('hidden'); const pb = document.getElementById('percentileBars'); if (pb) { pb.innerHTML = variableDefs.map((v, i) => { if (user[v.key] == null) return ''; const data = getPeerData('You'); const p = M.percentile(user[v.key], vals(v.key, data)); const color = p > 75 ? 'bg-emerald-500' : p > 50 ? 'bg-brand-500' : p > 25 ? 'bg-amber-500' : 'bg-red-500'; const peerLabel = peerMode === 'regional' ? ' (regional)' : ' (global)'; return `
${v.name}
${p.toFixed(0)}th percentile${peerLabel}
`; }).join(''); } let best = null, bestDiff = Infinity; for (let d of dataset) { let diff = 0, count = 0; for (let v of variableDefs) { if (user[v.key] != null && d[v.key] != null) { const arr = vals(v.key); diff += Math.abs(M.normalize(user[v.key], arr) - M.normalize(d[v.key], arr)); count++; } } if (count > 0 && diff / count < bestDiff) { bestDiff = diff / count; best = d; } } const cm = document.getElementById('closestMatch'); if (cm) { cm.innerHTML = `
Your profile most closely matches
${best ? best.country : 'N/A'}
Similarity: ${best ? Math.max(0, 100 - bestDiff * 100).toFixed(0) : 0}%
`; } const priorities = variableDefs.map(v => ({ key: v.key, name: v.name, percentile: user[v.key] != null ? M.percentile(user[v.key], vals(v.key)) : 50, higherIsBetter: v.higherIsBetter, icon: v.icon })).filter(v => v.higherIsBetter !== null).sort((a, b) => { const aScore = a.higherIsBetter ? a.percentile : 100 - a.percentile; const bScore = b.higherIsBetter ? b.percentile : 100 - b.percentile; return aScore - bScore; }).slice(0, 5); const pa = document.getElementById('priorityActions'); if (pa) { pa.innerHTML = priorities.map(p => { const isLow = p.higherIsBetter ? p.percentile < 50 : p.percentile > 50; const action = p.higherIsBetter ? (p.percentile < 30 ? 'Critical gap -- prioritize' : p.percentile < 50 ? 'Below average -- improve' : 'Solid foundation') : (p.percentile > 70 ? 'Critical risk -- reduce' : p.percentile > 50 ? 'Above average risk -- monitor' : 'Manageable level'); return `
${p.name}: ${p.percentile.toFixed(0)}th percentile
${action}
`; }).join(''); } lucide.createIcons(); } // === OUTLIERS === function renderOutliers() { const outliers = findOutliers(); const cont = document.getElementById('outlierList'); if (!cont) return; cont.innerHTML = outliers.slice(0, 12).map((o, i) => `
${o.country}
${o.deviations.length} anomalous metric${o.deviations.length > 1 ? 's' : ''}
${o.deviations.slice(0, 3).map(d => `${d.name}: ${d.z > 0 ? '+' : ''}${d.z.toFixed(1)}σ`).join('')}
${getOutlierExplanation(o.country, o.deviations)}
`).join(''); lucide.createIcons(); } function findOutliers() { const outliers = []; const keys = variableDefs.map(v => v.key); for (let k of keys) { const arr = vals(k); if (arr.length < 5) continue; const m = M.mean(arr), s = M.std(arr); if (s === 0) continue; for (let d of dataset) { if (d[k] == null) continue; const z = (d[k] - m) / s; if (Math.abs(z) > CONFIG.outlierZScore) { const existing = outliers.find(o => o.country === d.country); const vdef = variableDefs.find(v => v.key === k); if (existing) { existing.deviations.push({ key: k, z, name: vdef.name, value: d[k] }); } else { outliers.push({ country: d.country, deviations: [{ key: k, z, name: vdef.name, value: d[k] }] }); } } } } return outliers.map(o => ({ ...o, deviations: o.deviations.sort((a, b) => Math.abs(b.z) - Math.abs(a.z)) })).sort((a, b) => Math.abs(b.deviations[0].z) - Math.abs(a.deviations[0].z)); } function getOutlierExplanation(country, deviations) { const top = deviations[0]; const v = variableDefs.find(x => x.key === top.key); if (!v) return ''; const direction = top.z > 0 ? 'much higher' : 'much lower'; let explanation = `${country} is ${direction} than expected in ${v.name} (${top.value.toFixed(1)} ${v.unit}). `; if (country === 'United States' && top.key === 'health_expenditure_pct_gdp') explanation += 'Despite high spending, outcomes lag.'; else if (top.key === 'co2_per_capita' && top.z > 0) explanation += 'High carbon intensity signals fossil fuel dependency.'; else if (top.key === 'gini_index' && top.z > 0) explanation += 'Extreme inequality erodes social cohesion.'; else if (top.key === 'intentional_homicides' && top.z > 0) explanation += 'Elevated violence signals social stress.'; else if (top.key === 'women_in_parliament' && top.z < 0) explanation += 'Low female political representation limits policy diversity.'; else if (top.key === 'internet_users_pct' && top.z < 0) explanation += 'Low connectivity limits economic opportunity.'; else explanation += 'Investigate whether driven by policy, geography, culture, or data anomaly.'; return explanation; } // === SIMULATOR === function initSimulatorUI() { const sel = document.getElementById('simVariable'); if (!sel) return; sel.innerHTML = variableDefs.map(v => ``).join(''); initSimulator(); } function initSimulator() { const sel = document.getElementById('simVariable'); if (!sel) return; const key = sel.value; const v = variableDefs.find(x => x.key === key); if (!v) return; const values = vals(key); const mean = M.mean(values); document.getElementById('simLabel').textContent = v.name; document.getElementById('simSlider').value = 0; document.getElementById('simValue').textContent = '0% change (from ' + mean.toFixed(1) + ')'; runSimulation(0); } function runSimulation(pctChange) { const sel = document.getElementById('simVariable'); if (!sel) return; const key = sel.value; const v = variableDefs.find(x => x.key === key); if (!v) return; const values = vals(key); const mean = M.mean(values); const newValue = mean * (1 + pctChange / 100); document.getElementById('simValue').textContent = (pctChange >= 0 ? '+' : '') + pctChange + '% (' + newValue.toFixed(1) + ')'; const corrs = getCorrelations(key); const affected = corrs.filter(c => Math.abs(c.r) >= 0.3).map(c => { const cValues = vals(c.key); const cMean = M.mean(cValues); const projectedChange = cMean * (c.r * pctChange / 100); return { ...c, projected: cMean + projectedChange, delta: projectedChange }; }).sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta)); document.getElementById('simAffectedCount').textContent = affected.length; const results = document.getElementById('simResults'); if (results) { results.innerHTML = affected.slice(0, 15).map(a => `
${a.name}
${a.delta > 0 ? '+' : ''}${a.delta.toFixed(1)} (${(a.r * 100).toFixed(0)}% correlation)
`).join(''); lucide.createIcons(); } renderSimChart(v, affected.slice(0, 10)); } function renderSimChart(v, affected) { if (charts.simChart) charts.simChart.destroy(); const el = document.getElementById('simChart'); if (!el) return; charts.simChart = new Chart(el, { type: 'bar', data: { labels: affected.map(a => a.name.slice(0, 20)), datasets: [{ label: 'Projected Change', data: affected.map(a => a.delta), backgroundColor: affected.map(a => a.delta >= 0 ? 'rgba(34,211,238,0.4)' : 'rgba(244,63,94,0.4)'), borderColor: affected.map(a => a.delta >= 0 ? 'rgba(34,211,238,0.7)' : 'rgba(244,63,94,0.7)'), borderWidth: 1, borderRadius: 4 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { grid: { color: 'rgba(148,163,184,0.05)' }, ticks: { color: '#64748b', font: { size: 9 }, maxRotation: 45 } }, y: { grid: { color: 'rgba(148,163,184,0.05)' }, ticks: { color: '#64748b', font: { size: 10 } } } } } }); } // === GEM DISCOVERY === function renderGemDiscovery() { const cont = document.getElementById('gemList'); if (!cont) return; const gems = findHiddenGems(); cont.innerHTML = gems.slice(0, 15).map((g, i) => `
Unexpected Connection
${g.v1.name} ↔ ${g.v2.name}
${g.r >= 0 ? '+' : ''}${g.r.toFixed(2)}
${g.v1.category} ${g.v2.category} ${g.surprise.toFixed(1)}σ unexpected

${g.explanation}

·
`).join(''); lucide.createIcons(); } function findHiddenGems() { const gems = []; for (let i = 0; i < variableDefs.length; i++) { for (let j = i + 1; j < variableDefs.length; j++) { const v1 = variableDefs[i], v2 = variableDefs[j]; if (v1.category === v2.category) continue; const r = M.pearson(vals(v1.key), vals(v2.key)); if (Math.abs(r) < 0.3) continue; const expectedR = 0.1; const surprise = (Math.abs(r) - expectedR) / 0.15; let explanation = `A ${corrStrength(r)} ${r >= 0 ? 'positive' : 'negative'} correlation between ${v1.category.toLowerCase()} (${v1.name.toLowerCase()}) and ${v2.category.toLowerCase()} (${v2.name.toLowerCase()}). `; if (r >= 0.6) explanation += `This suggests ${v1.name.toLowerCase()} may be a leading indicator for ${v2.name.toLowerCase()}.`; else if (r <= -0.4) explanation += `This inverse relationship hints at policy trade-offs between these domains.`; else explanation += `While not dominant, this connection could reveal hidden structural linkages.`; gems.push({ v1, v2, r, surprise, explanation }); } } return gems.sort((a, b) => b.surprise - a.surprise); } // === COMPARE === function initCompareUI() { const sel = document.getElementById('compareSelect'); if (!sel) return; sel.innerHTML = '' + dataset.map(d => ``).join(''); } function addCompareCountry(country) { if (!country || compareCountries.includes(country)) return; compareCountries.push(country); renderCompareTags(); if (compareCountries.length >= 2) renderCompareResults(); pushURLState(); } function removeCompareCountry(country) { compareCountries = compareCountries.filter(c => c !== country); renderCompareTags(); if (compareCountries.length < 2) { document.getElementById('compareResults').classList.add('hidden'); document.getElementById('compareEmpty').classList.remove('hidden'); } else { renderCompareResults(); } pushURLState(); } function renderCompareTags() { const cont = document.getElementById('compareTags'); if (!cont) return; cont.innerHTML = compareCountries.map(c => ` ${c} `).join(''); lucide.createIcons(); } function renderCompareResults() { if (compareCountries.length < 2) return; document.getElementById('compareResults').classList.remove('hidden'); document.getElementById('compareEmpty').classList.add('hidden'); const n = Math.min(8, variableDefs.length); const vars = variableDefs.slice(0, n); const colors = ['#22d3ee', '#f59e0b', '#f43f5e', '#a78bfa', '#34d399']; const radarCanvas = document.getElementById('compareRadarCanvas'); if (radarCanvas) { const rect = radarCanvas.parentElement.getBoundingClientRect(); if (rect.width >= 10 && rect.height >= 10) { radarCanvas.width = rect.width * 2; radarCanvas.height = rect.height * 2; radarCanvas.style.width = rect.width + 'px'; radarCanvas.style.height = rect.height + 'px'; const ctx = radarCanvas.getContext('2d'); ctx.scale(2, 2); const w = rect.width, h = rect.height, cx = w / 2, cy = h / 2, rad = Math.min(cx, cy) - 40; ctx.clearRect(0, 0, w, h); for (let i = 1; i <= 5; i++) { ctx.beginPath(); ctx.arc(cx, cy, rad * i / 5, 0, Math.PI * 2); ctx.strokeStyle = 'rgba(148,163,184,0.1)'; ctx.lineWidth = 1; ctx.stroke(); } for (let i = 0; i < n; i++) { const a = -Math.PI / 2 + i * (2 * Math.PI) / n; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(a) * rad, cy + Math.sin(a) * rad); ctx.strokeStyle = 'rgba(148,163,184,0.1)'; ctx.stroke(); ctx.fillStyle = '#94a3b8'; ctx.font = '500 8px Inter'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(vars[i].name.slice(0, 10), cx + Math.cos(a) * (rad + 16), cy + Math.sin(a) * (rad + 16)); } compareCountries.forEach((cname, ci) => { const country = dataset.find(d => d.country === cname); const pts = vars.map((v, i) => { const a = -Math.PI / 2 + i * (2 * Math.PI) / n; const arr = vals(v.key); const norm = country && country[v.key] != null ? M.normalize(country[v.key], arr) : 0; return { x: cx + Math.cos(a) * rad * norm, y: cy + Math.sin(a) * rad * norm }; }); ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y); pts.slice(1).forEach(p => ctx.lineTo(p.x, p.y)); ctx.closePath(); ctx.fillStyle = colors[ci % colors.length] + '12'; ctx.fill(); ctx.strokeStyle = colors[ci % colors.length]; ctx.lineWidth = 2; ctx.stroke(); ctx.fillStyle = colors[ci % colors.length]; ctx.font = '500 10px Inter'; ctx.textAlign = 'left'; ctx.fillText(cname, 15, 18 + ci * 16); }); } } const table = document.getElementById('compareTable'); if (table) { const keys = variableDefs.slice(0, 12).map(v => v.key); let html = ''; html += ''; compareCountries.forEach(c => { html += ``; }); html += ''; variableDefs.slice(0, 12).forEach(v => { html += ''; html += ``; compareCountries.forEach(cname => { const d = dataset.find(x => x.country === cname); const val = d && d[v.key] != null ? d[v.key].toFixed(1) : '-'; html += ``; }); html += ''; }); html += '
Indicator${c}
${v.name}${val}
'; table.innerHTML = html; } const diffCanvas = document.getElementById('compareHeatmapCanvas'); if (diffCanvas) { const keys = variableDefs.slice(0, 15).map(v => v.key); const cellSize = 36, padding = 100; const width = compareCountries.length * cellSize + padding; const height = keys.length * cellSize + 30; diffCanvas.width = width * 2; diffCanvas.height = height * 2; diffCanvas.style.width = width + 'px'; diffCanvas.style.height = height + 'px'; const ctx = diffCanvas.getContext('2d'); ctx.scale(2, 2); ctx.clearRect(0, 0, width, height); const maxVal = dataset.map(d => keys.map(k => d[k] || 0).filter(v => v != null)).flat(); const globalMax = Math.max(...maxVal) || 1; keys.forEach((k, i) => { const v = variableDefs.find(x => x.key === k); compareCountries.forEach((c, j) => { const d = dataset.find(x => x.country === c); const val = d && d[k] != null ? d[k] : 0; const intensity = val / globalMax; ctx.fillStyle = `hsla(190, 80%, 50%, ${0.05 + intensity * 0.5})`; ctx.fillRect(padding + j * cellSize, i * cellSize, cellSize - 1, cellSize - 1); if (intensity > 0.3) { ctx.fillStyle = 'rgba(255,255,255,0.7)'; ctx.font = '400 8px Inter'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(val.toFixed(0), padding + j * cellSize + cellSize / 2, i * cellSize + cellSize / 2); } }); ctx.fillStyle = '#94a3b8'; ctx.font = '400 9px Inter'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillText(v.name.slice(0, 22), padding - 6, i * cellSize + cellSize / 2); }); compareCountries.forEach((c, j) => { ctx.fillStyle = '#94a3b8'; ctx.font = '500 9px Inter'; ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; ctx.fillText(c, padding + j * cellSize + cellSize / 2, height - 4); }); } } // === EXPORT === function exportInsights(format) { if (!selectedVar) { showStatus('Select a variable first', 100); return; } const v = variableDefs.find(d => d.key === selectedVar); const corrs = getCorrelations(selectedVar); if (format === 'txt') { let text = `Insight Engine — Analysis Report\n${'='.repeat(50)}\n\nSelected: ${v.name} (${v.category})\n${v.desc}\nMean: ${M.mean(vals(selectedVar)).toFixed(2)} | Std: ${M.std(vals(selectedVar)).toFixed(2)}\n\nCorrelations:\n${'-'.repeat(50)}\n`; corrs.forEach((c, i) => { text += `${i + 1}. ${c.name} (r=${c.r >= 0 ? '+' : ''}${c.r.toFixed(3)}) — ${corrStrength(c.r)}\n`; }); const blob = new Blob([text], { type: 'text/plain' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `insight-${v.key}-report.txt`; a.click(); } else if (format === 'csv') { let csv = 'Variable,Correlation,Strength,Category\n'; corrs.forEach(c => { csv += `"${c.name}",${c.r.toFixed(4)},"${corrStrength(c.r)}","${c.category}"\n`; }); const blob = new Blob([csv], { type: 'text/csv' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `insight-${v.key}-correlations.csv`; a.click(); } else if (format === 'png') { ['distributionChart', 'scatterChart', 'networkCanvas', 'heatmapCanvas'].forEach(id => { const canvas = document.getElementById(id); if (!canvas) return; const a = document.createElement('a'); a.href = canvas.toDataURL('image/png'); a.download = `insight-${v.key}-${id}.png`; a.click(); }); } document.getElementById('exportMenu').classList.remove('show'); } // === MODALS & UTILS === function showDatasetModal() { const modal = document.getElementById('datasetModal'); if (!modal) return; modal.classList.remove('hidden'); modal.classList.add('flex'); const keys = ['country', 'region', 'income', ...variableDefs.map(v => v.key)]; const thead = document.getElementById('datasetThead'); if (thead) thead.innerHTML = '' + keys.map(k => { const v = k === 'country' ? { name: 'Country' } : k === 'region' ? { name: 'Region' } : k === 'income' ? { name: 'Income' } : variableDefs.find(d => d.key === k); return `${v ? v.name : k}`; }).join('') + ''; const tbody = document.getElementById('datasetTbody'); if (tbody) tbody.innerHTML = dataset.map(d => '' + keys.map(k => { const val = d[k]; return `${typeof val === 'number' ? (val >= 1000 ? val.toLocaleString(undefined, { maximumFractionDigits: 0 }) : val.toFixed(1)) : val || '-'}`; }).join('') + '').join(''); } function closeDatasetModal() { const modal = document.getElementById('datasetModal'); if (!modal) return; modal.classList.add('hidden'); modal.classList.remove('flex'); } function handleFileUpload(event) { const file = event.target.files[0]; if (!file) return; showStatus('Reading file...', 30); const reader = new FileReader(); reader.onload = function (e) { try { let data; if (file.name.endsWith('.json')) data = JSON.parse(e.target.result); else if (file.name.endsWith('.csv')) data = parseCSV(e.target.result); else { showStatus('Use .json or .csv', 100); return; } loadCustomDataset(data); showStatus(`Loaded ${data.length} records`, 100); } catch (err) { showStatus('Error: ' + err.message, 100); } }; reader.readAsText(file); } function parseCSV(text) { const lines = text.trim().split('\n'); const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, '')); return lines.slice(1).map(line => { const obj = {}; const values = line.split(','); headers.forEach((h, i) => { const val = values[i] ? values[i].trim().replace(/^"|"$/g, '') : ''; obj[h] = isNaN(val) || val === '' ? val : parseFloat(val); }); return obj; }); } function loadCustomDataset(data) { if (!Array.isArray(data) || data.length === 0) return; DATASET.length = 0; data.forEach(d => DATASET.push(d)); const keys = Object.keys(data[0]).filter(k => k !== 'country'); VARIABLE_DEFS.length = 0; keys.forEach(k => { VARIABLE_DEFS.push({ key: k, name: k.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()), unit: 'units', category: 'Custom', desc: 'User-uploaded', icon: 'circle', higherIsBetter: null }); }); init(); } window.addEventListener('resize', () => { if (selectedVar) { const corrs = getCorrelations(selectedVar); const v = variableDefs.find(d => d.key === selectedVar); } }); document.addEventListener('DOMContentLoaded', init); // Force deploy Fri May 8 07:19:24 UTC 2026 // Deploy timestamp: Fri May 8 07:21:55 UTC 2026 // force deploy 1778227178