`;
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 ' + selected.length + ' indicators from World Bank...', 5);
_abortController = new AbortController();
startLiveTicker();
try {
const result = await apiWithSignal(`/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(); initMapping();
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...', 5);
_abortController = new AbortController();
startLiveTicker();
try {
const result = await apiWithSignal('/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(); initMapping();
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); }
// === LANDING PAGE ===
function dismissLanding(datasetId) {
const overlay = document.getElementById('landingOverlay');
if (overlay) {
overlay.style.opacity = '0';
setTimeout(() => overlay.remove(), 500);
}
if (datasetId) {
if (datasetId.startsWith('wb:')) {
fetchWorldBankPreset(datasetId);
} else {
loadBuiltinDataset(datasetId);
}
}
}
function dismissLandingAndOpenSources() {
const overlay = document.getElementById('landingOverlay');
if (overlay) {
overlay.style.opacity = '0';
setTimeout(() => overlay.remove(), 500);
}
showDatasetBrowser();
}
// === INSIGHT GUIDE CHATBOT ===
let chatHistory = [];
function openChatbot(mode, contextData) {
const panel = document.getElementById('chatbotPanel');
const backdrop = document.getElementById('chatbotBackdrop');
if (!panel) return;
panel.classList.remove('translate-x-full');
if (backdrop) { backdrop.classList.remove('hidden'); setTimeout(() => backdrop.classList.remove('opacity-0'), 10); }
lucide.createIcons();
if (mode === 'general') {
updateChatbotContext('general', 'Global Insight Engine');
} else if (mode === 'chart' && contextData) {
updateChatbotContext('chart', contextData);
}
}
function closeChatbot() {
const panel = document.getElementById('chatbotPanel');
const backdrop = document.getElementById('chatbotBackdrop');
if (panel) panel.classList.add('translate-x-full');
if (backdrop) { backdrop.classList.add('opacity-0'); setTimeout(() => backdrop.classList.add('hidden'), 300); }
}
function updateChatbotContext(type, label) {
const pill = document.getElementById('chatbotContextPill');
const text = document.getElementById('chatbotContextText');
if (pill && text) {
if (type === 'general') {
pill.classList.add('hidden');
} else {
pill.classList.remove('hidden');
text.textContent = 'Looking at: ' + label;
}
}
}
function openChatbotFor(chartName) {
const chartLabels = {
'mapping': 'the Mapping canvas',
'distribution': 'the Distribution chart',
'network': 'the Network Diagram',
'correlations': 'the Correlations section',
'scatter': 'the Scatter Plot',
'heatmap': 'the Heatmap',
'radar': 'the Radar Comparison',
'compare-heatmap': 'the Difference Heatmap',
'outliers': 'the Outliers view',
'decisions': 'the Rank tab',
'weight-sliders': 'the Priority Sliders',
'decision-results': 'the Top Recommendations',
'benchmark': 'the Profile benchmark',
'simulator': 'the Scenario Builder'
};
const selected = selectedVar ? (variableDefs.find(v => v.key === selectedVar) || {}).name || 'selected variable' : 'selected variable';
const msg = `I'm looking at ${chartLabels[chartName] || 'this chart'} for ${selected}. Can you explain in detail how to read this visual, what it means, and how it was made?`;
openChatbot('chart', chartLabels[chartName]);
sendChatbotMessage(msg, true);
}
function appendChatMessage(role, text, isTyping) {
const container = document.getElementById('chatbotMessages');
if (!container) return;
const div = document.createElement('div');
div.className = 'flex gap-3 fade-in';
const isUser = role === 'user';
const iconBg = isUser ? 'bg-slate-600' : 'bg-gradient-to-br from-brand-400 to-brand-600';
const icon = isUser ? 'user' : 'sparkles';
const textColor = isUser ? 'text-white' : 'text-slate-300';
div.innerHTML = `
${isTyping ? '' : formatChatText(text)}
`;
container.appendChild(div);
container.scrollTop = container.scrollHeight;
lucide.createIcons();
}
function formatChatText(text) {
// Simple markdown-ish formatting: bold, paragraphs, bullet lists
let html = text
.replace(/\*\*(.+?)\*\*/g, '$1')
.replace(/^\* (.+)$/gm, '
›$1
')
.replace(/\n\n/g, '
')
.replace(/\n/g, ' ');
// Wrap in p if not already
if (!html.startsWith('
';
return html;
}
function sendChatbotMessage(text, skipUI) {
const input = document.getElementById('chatbotInput');
const msg = text || (input ? input.value.trim() : '');
if (!msg) return;
if (input && !text) input.value = '';
if (!skipUI) appendChatMessage('user', msg);
chatHistory.push({ role: 'user', text: msg });
// Show typing indicator
appendChatMessage('assistant', '', true);
// Generate response based on context
setTimeout(() => {
// Remove typing indicator (last child)
const container = document.getElementById('chatbotMessages');
if (container && container.lastChild) container.lastChild.remove();
const response = generateChatResponse(msg);
appendChatMessage('assistant', response);
chatHistory.push({ role: 'assistant', text: response });
}, 600 + Math.random() * 800);
}
function generateChatResponse(userMsg) {
const msg = userMsg.toLowerCase();
const currentVar = selectedVar ? (variableDefs.find(v => v.key === selectedVar) || {}) : {};
const varName = currentVar.name || 'the selected variable';
const varDesc = currentVar.desc || 'a development indicator';
// Chart-specific explanations
if (msg.includes('distribution') || msg.includes('histogram') || msg.includes('bar chart')) {
return `**The Distribution chart** shows how ${varName} is spread across all the data points currently loaded.
Here's what you're seeing:
* The **horizontal axis** (x-axis) shows the range of values — from the lowest to the highest score for ${varName}.
* The **vertical bars** tell you how many countries fall into each "bucket" or range. A tall bar means many countries have similar scores.
* If the bars cluster on the left, most countries score low. If they cluster on the right, most score high. A bell-shaped curve suggests a "normal" spread.
**How it's built:** The app takes every country's value for ${varName}, sorts them, then groups them into about 15 equal-width ranges (called "bins"). Each bar's height is simply the count of countries in that bin. This is the most straightforward way to see if a variable is evenly distributed or skewed toward one end.`;
}
if (msg.includes('network') || msg.includes('diagram') || msg.includes('node')) {
return `**The Network Diagram** shows which other variables are most closely related to ${varName}.
Here's how to read it:
* **The big node in the center** is ${varName} itself — this is your "anchor."
* **Surrounding nodes** are other variables. The closer a node sits to the center, the stronger its connection to ${varName}.
* **Lines (edges)** connect related variables. Thicker = stronger relationship. The color shifts from cool (weak) to warm (strong).
* **Node size** reflects how many connections that variable has overall — a large node is a "hub" that connects to many things.
**How it's built:** The app calculates the **Pearson correlation coefficient** (a number from -1 to +1) between every pair of numeric variables. Only relationships above a threshold (default 0.3) are drawn. The layout uses a simple force-directed algorithm: related nodes attract each other, unrelated ones repel. It's a bit like watching magnets sort themselves out.`;
}
if (msg.includes('correlation') || msg.includes('pearson') || msg.includes('r=') || msg.includes('link')) {
return `**Correlations** tell you whether two variables "move together."
* A score of **+1.0** means perfect lockstep: when one goes up, the other always goes up by a predictable amount.
* A score of **-1.0** means perfect opposition: when one goes up, the other always goes down.
* **0.0** means no relationship at all — they're independent.
**Rule of thumb for reading the numbers:**
* **0.0 to 0.3** — Weak or negligible. Probably coincidence.
* **0.3 to 0.5** — Moderate. Worth noting, but don't bet the farm on it.
* **0.5 to 0.7** — Strong. There's a real pattern here.
* **0.7 to 1.0** — Very strong. These variables are deeply connected.
**Important caveat:** Correlation does **not** mean causation. Just because ice cream sales and drowning incidents correlate doesn't mean ice cream causes drowning. Both just rise in summer. The app shows *that* things are related — figuring out *why* requires deeper investigation.`;
}
if (msg.includes('scatter') || msg.includes('explore') || msg.includes('plot') || msg.includes('point')) {
const scatterVar = document.getElementById('scatterVarSelect');
const scatterName = scatterVar ? scatterVar.options[scatterVar.selectedIndex]?.text || 'another variable' : 'another variable';
return `**The Scatter Plot** compares ${varName} against ${scatterName} — one dot per country.
* **Each dot** is one country. Its horizontal position is its ${varName} score; its vertical position is its ${scatterName} score.
* **The trend line** (a straight gray line through the cloud) shows the general direction. Sloping up = positive relationship. Sloping down = negative. Flat = no relationship.
* **Dots far from the line** are outliers — countries that break the pattern. Hovering (or selecting) them lets you investigate why.
**How it's built:** The app uses simple linear regression (the least-squares method) to find the "best fit" line through all the points. The equation of that line is printed at the top of the chart. The closer the dots hug the line, the stronger the relationship.`;
}
if (msg.includes('heatmap') || msg.includes('color grid') || msg.includes('matrix')) {
return `**The Heatmap** is a color-coded "correlation matrix" — a bird's-eye view of how *every* variable relates to *every other* variable.
* **Rows and columns** are the same list of variables, so the matrix is symmetrical (the top-right mirrors the bottom-left).
* **Color intensity** shows strength. Deep blue = strong positive correlation. Deep red = strong negative. Pale or white = weak or none.
* **The diagonal** (top-left to bottom-right) is always solid — that's a variable correlated with itself, so it's always +1.0.
**How it's built:** The app computes Pearson correlations between every pair of variables, then maps the -1.0 to +1.0 range onto a blue-to-red color gradient. This view is incredibly useful for spotting "clusters" of variables that all move together — for example, you might notice that GDP, education, and health all share a deep blue block, suggesting they rise and fall as a group.`;
}
if (msg.includes('outlier') || msg.includes('z-score') || msg.includes('unusual')) {
return `**The Outliers view** flags countries that are statistically unusual — in a good way or a bad way.
* **Z-score** is the key number. It measures how many "standard deviations" a country's value is from the average.
* A **z-score of +2.0** means that country scores two full "spread units" above the mean — it's in the top ~2.5%.
* A **z-score of -2.0** means it's two units below — in the bottom ~2.5%.
* The app flags anything with an absolute z-score above **2.0** (you can change this threshold in settings).
**How it's built:** For each variable, the app calculates the mean and standard deviation across all countries. Then it subtracts the mean from each country's value and divides by the standard deviation. That's it — elegantly simple, yet powerful. Countries that show up here are worth a second look: they might be policy success stories, data anomalies, or simply unique cases.`;
}
if (msg.includes('radar') || msg.includes('spider') || msg.includes('comparison')) {
return `**The Radar Chart** (sometimes called a "spider chart") lets you compare two countries across multiple variables at once.
* **Each spoke** (axis pointing outward) is one variable. The further a dot is from the center on that spoke, the higher that country's score.
* **The colored polygon** connects the dots, creating a "shape" that represents that country's overall profile.
* Two countries with similar shapes have similar profiles. Two with very different shapes are structurally different.
**How it's built:** The app normalizes every variable to a 0–100 scale (so variables with wildly different units can be compared side by side), then plots each country's normalized scores on evenly-spaced radial axes. It's one of the best ways to see the *balance* of strengths and weaknesses in a single glance.`;
}
if (msg.includes('decision') || msg.includes('framework') || msg.includes('score') || msg.includes('priority')) {
return `**The Rank tab** helps you weigh multiple variables into a single "goodness" score for each country.
Here's how it works:
* **You set weights** (sliders) for each variable. Want GDP to matter more? Slide it up. Want pollution to penalize a country? Keep it high — but note that "higher is better" variables add points, while "lower is better" ones subtract.
* **The app multiplies** each country's score by your weight, sums them up, and ranks countries.
* **Priority actions** are auto-generated suggestions: countries with low scores get recommendations based on which variables drag them down the most.
**How it's built:** It's essentially a weighted linear combination. Each variable is first normalized (0–100) so units don't matter. Then: Score = Σ (normalized_value × weight × direction). The direction is +1 for "higher is better" and -1 for "lower is better." Simple math, but the power is in *your* judgment via the sliders.`;
}
if (msg.includes('weight') && (msg.includes('slider') || msg.includes('priority') || msg.includes('how') || msg.includes('use'))) {
const sliderCount = variableDefs.length || 'several';
return `**The Priority Sliders** are how you tell the app what matters *to you*.
Here's how to think about them:
* **Each slider** is one variable (like GDP per Capita, Life Expectancy, CO₂ Emissions). Slide it right = "this matters a lot." Slide it left = "this barely matters."
* **All sliders add up to 100%** (the Total Weight bar at the bottom shows this). You don't have to hit exactly 100 — the app normalizes your choices automatically — but it's a helpful mental check.
* **"Higher is better" vs "Lower is better"** — some variables (like happiness) you want more of. Others (like corruption or pollution) you want less of. The app automatically knows which is which and flips the math behind the scenes. You don't need to "invert" anything yourself.
**A practical tip:** Start with everything at 1 (neutral). Then crank up the 2–3 variables you actually care about. The rankings will shift dramatically. If two variables are equally important, give them the same weight. If one is twice as important, double its slider.
**What happens when you move a slider?** The app instantly recalculates every country's composite score, re-sorts them, and updates the Top Recommendations list. It's real-time policy simulation — no "submit" button needed.`;
}
if (msg.includes('recommendation') || msg.includes('top') || msg.includes('score') || msg.includes('rank') || msg.includes('decision-result')) {
return `**Top Recommendations** is the ranked list of countries that best match *your* priorities.
Here's what each number means:
* **Composite Score** — a single number from 0 to 100 that averages every variable, weighted by your slider settings. 100 = perfect alignment with what you said matters. 0 = worst alignment.
* **The colored bar** visualizes this score. Long green bar = great fit. Short red bar = poor fit.
* **Rank** — simply the sorted position. #1 is your "ideal" country given your current weights.
**How to use this:**
* If you're a policymaker, look at the top performers and study what they do differently.
* If you're an investor, the top-ranked countries might represent stable, high-growth environments given your criteria.
* If you're a researcher, flip the weights and watch how the rankings change. That's often where the real insights hide.
**Behind the scenes:** Every country's raw values are first normalized (so GDP in dollars and life expectancy in years can be compared apples-to-apples). Then each is multiplied by your weight and the variable's "direction" (+1 for "more is better", -1 for "less is better"). Sum across all variables = composite score. Sort = ranking. It's transparent, tweakable, and fast.`;
}
if (msg.includes('benchmark') || msg.includes('profile') || msg.includes('percentile') || msg.includes('rank')) {
return `**The Profile / Benchmark view** shows where a specific country stands compared to its peers.
* **Percentiles** tell you the story: "Denmark is at the 94th percentile for Life Expectancy" means Denmark scores better than 94% of countries.
* **Peer comparison** lets you choose "global" peers (all countries) or "regional" peers (same continent/region). A country might look mediocre globally but exceptional regionally — or vice versa.
* **Strengths & weaknesses** are auto-flagged: variables where the country is above the 75th percentile are "Strengths"; below 25th are "Challenges."
**How it's built:** The app sorts all countries for each variable and finds each country's position in that sorted list. Percentile = (position ÷ total) × 100. Regional grouping uses the metadata from the REST Countries API. This view is perfect for quick country briefings.`;
}
if (msg.includes('simulator') || msg.includes('what if') || msg.includes('scenario')) {
return `**The Scenario Builder** lets you play "what if" with the data.
* **Choose a country** and a variable. The app shows that country's current value and the global average.
* **Adjust the slider** to set a hypothetical new value. The app instantly recalculates what would change: correlations, rankings, and percentile shifts.
* **Scenario cards** (pre-built) let you run common hypotheticals: "What if every country matched the top performer?" or "What if the lowest 20% caught up to the median?"
**How it's built:** When you change a value, the app temporarily replaces that data point, re-runs all calculations (correlations, percentiles, rankings), and shows you the delta. It's all client-side — no server needed — so it's fast and private. Think of it as a sandbox for policy imagination.`;
}
if (msg.includes('variable') && (msg.includes('this') || msg.includes('current') || msg.includes('selected'))) {
return `**${varName}** is ${varDesc}.
Currently, the app is analyzing this variable across ${dataset.length} data points. When you select a variable, the app does a few things automatically:
1. **Distribution** — shows how the values spread across all countries
2. **Network** — finds which other variables move together with ${varName}
3. **Correlations** — ranks every other variable by statistical similarity
4. **Narrative** — generates a plain-language summary of the top and bottom performers
You can click any of these sections and then hit the **"Explain"** button next to a chart to get a deeper walkthrough.`;
}
if (msg.includes('how') && (msg.includes('use') || msg.includes('start') || msg.includes('begin'))) {
return `Here's how to get the most out of the Insight Engine:
1. **Load a dataset** — click **Sources** in the top right, or pick one of the quick-start cards on the landing page. Each dataset has a different theme (happiness, environment, economy, etc.).
2. **Pick a variable** — the left sidebar shows all available variables. Click one, or search by name. The charts will update instantly.
3. **Explore the tabs** — **Explorer** for deep-dive charts, **Scenario Builder** for "what if" scenarios, **Compare** for side-by-side country analysis, **Discover** for unique insights, **Mapping** for relationship diagrams, and more.
4. **Ask me anything** — click the **Guide** button (or this panel) anytime. I can explain charts, numbers, methodology, or help you interpret what you're seeing.
5. **Export** — hit the **Export** button in the header to download reports, CSVs, or chart images.`;
}
if (msg.includes('data') && (msg.includes('source') || msg.includes('from') || msg.includes('where'))) {
return `The Insight Engine pulls from several trusted public sources:
* **World Bank Open Data** — the backbone. 120+ development indicators covering economy, health, education, environment, governance, and more. Updated regularly.
* **UNDP Human Development Index** — composite scores for life expectancy, education, and income.
* **World Happiness Report (UN SDSN)** — survey-based wellbeing data.
* **Yale Environmental Performance Index** — ecosystem and environmental health.
* **Institute for Economics & Peace** — peace, conflict, and security metrics.
* **Open-Meteo** — real climate data (temperature, precipitation) for capital cities.
* **Reporters Without Borders, Transparency International, WIPO, IMD** — press freedom, corruption, innovation, digital competitiveness.
All data is fetched live from APIs where possible, or served from curated built-in datasets. You can also upload your own CSV or JSON.`;
}
if (msg.includes('method') || msg.includes('how') || msg.includes('calculated') || msg.includes('algorithm')) {
return `Most of the heavy lifting in this app is done with classic, well-understood statistical methods:
* **Pearson correlation** — measures linear relationships. It's the standard "r" value you see in the correlations section.
* **Z-scores** — for outlier detection. (value − mean) ÷ standard deviation.
* **Percentiles** — rank-based positioning. Simple sorting and division.
* **Linear regression** — the trend line in scatter plots. Least-squares fitting.
* **Normalization** — scaling everything to 0–100 so different units can be compared in radar charts and the Rank tab.
Nothing here is exotic or opaque. The goal is transparency: you should be able to understand *how* every number was produced, not just trust a black box. That's why every chart has an **Explain** button.`;
}
if (msg.includes('mapping') || msg.includes('concept map') || msg.includes('diagram') || msg.includes('connect card')) {
return `**The Mapping tab** is a freeform canvas for exploring relationships between ideas, variables, and countries.
* **Add cards** to the canvas with the + button. Each card has a note you can edit inline.
* **Drag cards** anywhere on the canvas to organize your thinking.
* **Connect cards** by clicking "connect" on one card, then clicking the target card. A dashed arrow appears showing the relationship.
* **Use it for:** tracing cause-and-effect chains, building research hypotheses, mapping policy pathways, or documenting your own analytical narrative.
The canvas persists in your browser via localStorage, so your maps survive reloads. Cards automatically pick up the color of the currently selected variable's category, helping you visually group related concepts.`;
}
// Fallback
return `Great question! Let me break that down for you.
The Insight Engine analyzes ${varName} and ${dataset.length ? dataset.length + ' data points' : 'the loaded dataset'} to find patterns, relationships, and outliers. Every chart and number is built from straightforward statistics — correlations, distributions, rankings — and designed to be readable without a PhD.
If you're looking at something specific, just tell me the name of the chart or section (like "Network Diagram" or "Correlations"), and I'll walk you through exactly what it means, how to read it, and how it was constructed.
You can also click the **Explain** button next to any chart for instant context.`;
}
// === 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);
initTheme();
initTabDragDrop();
initTooltips();
lucide.createIcons(); initTabs(); initExplorer();
initDecisionFramework(); initBenchmark();
initSimulatorUI(); initCompareUI(); initMapping();
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');
if (tab === 'mapping') { setTimeout(() => { renderMappingCards(); renderMappingLines(); }, 50); }
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);
}
// === SHARE-TO-MAPPING bridges for context-bound buttons ===
window.shareCurrentVariable = function() {
if (!selectedVar) return;
const v = variableDefs.find(d => d.key === selectedVar);
if (!v) return;
const values = vals(selectedVar);
const mean = M.mean(values), std = M.std(values);
const corrs = getCorrelations(selectedVar);
const top = corrs.filter(c => Math.abs(c.r) >= 0.3).slice(0, 3).map(c => c.name + ' (r=' + (c.r >= 0 ? '+' : '') + c.r.toFixed(2) + ')');
const body = v.name + ' (' + v.category + '): mean ' + mean.toFixed(1) + ' ' + (v.unit || '') + ', std ' + std.toFixed(2) + '.' + (top.length ? ' Top correlations: ' + top.join(', ') + '.' : '');
if (typeof window.shareToMapping === 'function') {
window.shareToMapping({
sourceType: 'variable',
title: v.name,
body: body,
tags: ['variable', v.category.toLowerCase().replace(/\s+/g,'-'), v.key],
color: '#06b6d4'
});
}
};
window.shareCurrentNarrative = function() {
if (!selectedVar) return;
const v = variableDefs.find(d => d.key === selectedVar);
if (!v) return;
const textEl = document.getElementById('narrativeText');
const text = textEl ? textEl.textContent.trim() : '';
if (!text) return;
if (typeof window.shareToMapping === 'function') {
window.shareToMapping({
sourceType: 'narrative',
title: v.name + ' — Narrative',
body: text,
tags: ['narrative', v.category.toLowerCase().replace(/\s+/g,'-'), v.key],
color: '#06b6d4'
});
}
};
// === 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];
const payload = encodeURIComponent(JSON.stringify({
sourceType: 'risk',
title: 'Risk: ' + v.name + ' ↔ ' + r.name,
body: 'Higher ' + v.name.toLowerCase() + ' linked to lower ' + r.name.toLowerCase() + ' (r=' + r.r.toFixed(2) + ').',
tags: ['risk', v.category.toLowerCase().replace(/\s+/g,'-'), r.category.toLowerCase().replace(/\s+/g,'-')],
color: '#f43f5e'
}));
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];
const payload = encodeURIComponent(JSON.stringify({
sourceType: 'opportunity',
title: 'Opportunity: ' + v.name + ' ↔ ' + o.name,
body: 'Strong positive link between ' + v.name.toLowerCase() + ' and ' + o.name.toLowerCase() + ' (r=' + o.r.toFixed(2) + '). Coordinated investment may yield dual returns.',
tags: ['opportunity', v.category.toLowerCase().replace(/\s+/g,'-'), o.category.toLowerCase().replace(/\s+/g,'-')],
color: '#10b981'
}));
html += `
${strong.length} of ${corrs.length} variables show |r| >= 0.5.
${mkShare({sourceType:'banner',title:'Summary: '+v.name,body:strong.length+' of '+corrs.length+' variables show |r| ≥ 0.5 with '+v.name+'.',tags:['banner','summary',v.category.toLowerCase().replace(/\s+/g,'-')],color:'#a855f7'})}