colesr commited on
Commit
cfe9bb8
·
verified ·
1 Parent(s): 8e40b25

Add 12 built-in reference datasets, 120+ WB indicators, 9 WB presets, redesigned Data Library UI

Browse files
Files changed (1) hide show
  1. static/app.js +218 -43
static/app.js CHANGED
@@ -1,5 +1,5 @@
1
  // === GLOBAL INSIGHT ENGINE v6 - DOCKER + FASTAPI ===
2
- // Updated: 2024-01-08-v5
3
  const CONFIG = { maxCountries: 200, correlationThreshold: 0.3, outlierZScore: 2 };
4
  let dataset = [], variableDefs = [], categories = [], selectedVar = null;
5
  let corrFilter = 'all', activeCategory = null, activeTab = 'explorer', peerMode = 'global';
@@ -50,12 +50,26 @@ const DATASET_PACKS = [];
50
 
51
  async function loadDefaultDataset() {
52
  showStatus('Loading dataset...', 10);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  try {
54
  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';
55
  const result = await api(`/api/worldbank/fetch?indicators=${defaults}&countries=all&date_range=2020:2023&latest_only=true`);
56
  if (result.data && result.data.length > 0) {
57
  DATASET.length = 0; result.data.forEach(d => DATASET.push(d));
58
- // Always build VARIABLE_DEFS from fetched data (ignore embedded definitions)
59
  const keys = Object.keys(DATASET[0]).filter(x => x !== 'country');
60
  window.VARIABLE_DEFS = keys.map(x => ({
61
  key: x, name: x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
@@ -105,65 +119,226 @@ function switchToDataset(packName) {
105
  return true;
106
  }
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  // === DATASET BROWSER ===
109
  async function showDatasetBrowser() {
110
  let existing = document.getElementById('datasetBrowserModal'); if (existing) existing.remove();
111
  const modal = document.createElement('div');
112
- modal.id = 'datasetBrowserModal'; modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4';
113
  modal.onclick = e => { if (e.target === modal) modal.remove(); };
114
- let builtinCards = DATASET_PACKS.map(p => `
115
- <div class="glass-light rounded-xl p-5 cursor-pointer transition-all hover:bg-brand-500/10 hover:border-brand-500/30 border border-transparent ${CURRENT_DATASET && CURRENT_DATASET.name === p.name ? 'border-brand-500/40 bg-brand-500/5' : ''}" onclick="selectDatasetPack('${p.name}');document.getElementById('datasetBrowserModal').remove()">
116
- <div class="flex items-center justify-between mb-3"><div class="flex items-center gap-2"><div class="w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center"><i data-lucide="database" class="w-4 h-4 text-brand-400"></i></div><span class="text-sm font-semibold text-white">${p.name}</span></div>${CURRENT_DATASET && CURRENT_DATASET.name === p.name ? '<span class="text-[0.65rem] px-2 py-0.5 rounded-full bg-brand-500/20 text-brand-300">Active</span>' : ''}</div>
117
- <div class="text-xs text-slate-400 mb-3">${p.description}</div>
118
- <div class="flex items-center gap-3 text-[0.65rem] text-slate-500"><span>${p.variableCount} variables</span></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  </div>
120
  `).join('');
121
- let apiSection = '';
122
- try {
123
- const wb = await api('/api/worldbank/indicators');
124
- if (wb.indicators) {
125
- const indList = wb.indicators.map(i => `<option value="${i.id}">${i.name} (${i.wb_code})</option>`).join('');
126
- apiSection = `
127
- <div class="mt-6 p-4 rounded-xl bg-slate-800/30 border border-slate-700/30">
128
- <div class="text-xs font-semibold text-white mb-2">Fetch World Bank Data</div>
129
- <p class="text-[0.65rem] text-slate-400 mb-3">Select indicators to fetch live data.</p>
130
- <select id="wbIndicatorSelect" multiple class="w-full h-32 px-3 py-2 rounded-lg bg-slate-800/80 border border-slate-700/50 text-xs text-white mb-2 overflow-y-auto">${indList}</select>
131
- <button onclick="fetchWorldBankData()" class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-600/80 text-xs text-white hover:bg-brand-500 transition-colors">
132
- <i data-lucide="download" class="w-3.5 h-3.5"></i>Fetch & Load
133
- </button>
134
- </div>
135
- <div class="mt-4 p-4 rounded-xl bg-slate-800/30 border border-slate-700/30">
136
- <div class="text-xs font-semibold text-white mb-2">Fetch Climate Data</div>
137
- <button onclick="fetchClimateData()" class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-600/80 text-xs text-white hover:bg-brand-500 transition-colors">
138
- <i data-lucide="cloud" class="w-3.5 h-3.5"></i>Fetch Capital City Climate
139
- </button>
140
- </div>
141
- `;
142
- }
143
- } catch (e) { apiSection = `<div class="mt-4 p-3 rounded-lg bg-red-500/10 text-red-300 text-xs">Backend API not available. Using embedded data only.</div>`; }
144
  modal.innerHTML = `
145
- <div class="glass rounded-2xl w-full max-w-2xl max-h-[80vh] overflow-hidden flex flex-col">
146
  <div class="flex items-center justify-between p-5 border-b border-slate-700/50">
147
- <h3 class="text-lg font-bold text-white">Data Sources</h3>
148
  <button onclick="document.getElementById('datasetBrowserModal').remove()" class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-slate-700/50"><i data-lucide="x" class="w-4 h-4 text-slate-400"></i></button>
149
  </div>
 
 
 
 
 
150
  <div class="overflow-auto p-5 flex-1">
151
- <div class="text-[0.65rem] text-slate-500 mb-2 uppercase tracking-wider font-medium">Built-in Datasets</div>
152
- <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">${builtinCards}</div>
153
- ${apiSection}
154
- <div class="mt-6 p-4 rounded-xl bg-slate-800/30 border border-slate-700/30">
155
- <div class="text-xs font-semibold text-white mb-2">Upload Custom Data</div>
156
- <p class="text-[0.65rem] text-slate-400 mb-3">Import CSV or JSON.</p>
157
- <label class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-600/80 text-xs text-white hover:bg-brand-500 cursor-pointer">
158
- <i data-lucide="file-up" class="w-3.5 h-3.5"></i>Choose File
159
- <input type="file" accept=".json,.csv" class="hidden" onchange="handleFileUpload(event);document.getElementById('datasetBrowserModal').remove()">
160
- </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  </div>
162
  </div>
163
  </div>`;
164
  document.body.appendChild(modal); lucide.createIcons();
165
  }
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  async function fetchWorldBankData() {
168
  const sel = document.getElementById('wbIndicatorSelect'); if (!sel) return;
169
  const selected = Array.from(sel.selectedOptions).map(o => o.value);
 
1
  // === GLOBAL INSIGHT ENGINE v6 - DOCKER + FASTAPI ===
2
+ // Updated: 2024-01-08-v9
3
  const CONFIG = { maxCountries: 200, correlationThreshold: 0.3, outlierZScore: 2 };
4
  let dataset = [], variableDefs = [], categories = [], selectedVar = null;
5
  let corrFilter = 'all', activeCategory = null, activeTab = 'explorer', peerMode = 'global';
 
50
 
51
  async function loadDefaultDataset() {
52
  showStatus('Loading dataset...', 10);
53
+ try {
54
+ // Try to load a curated preset from the backend
55
+ const result = await api('/api/datasets/builtin/hdi_2022');
56
+ if (result && result.data && result.data.length > 0) {
57
+ DATASET.length = 0; result.data.forEach(d => DATASET.push(d));
58
+ VARIABLE_DEFS.length = 0; result.indicators.forEach(v => VARIABLE_DEFS.push(v));
59
+ DATASET_PACKS.length = 0;
60
+ 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' });
61
+ CURRENT_DATASET = DATASET_PACKS[0];
62
+ currentDatasetId = 'builtin:hdi_2022';
63
+ showStatus('Loaded Human Development Index', 50);
64
+ return;
65
+ }
66
+ } catch (e) { console.log('Backend builtin unavailable, trying WB live', e); }
67
+
68
  try {
69
  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';
70
  const result = await api(`/api/worldbank/fetch?indicators=${defaults}&countries=all&date_range=2020:2023&latest_only=true`);
71
  if (result.data && result.data.length > 0) {
72
  DATASET.length = 0; result.data.forEach(d => DATASET.push(d));
 
73
  const keys = Object.keys(DATASET[0]).filter(x => x !== 'country');
74
  window.VARIABLE_DEFS = keys.map(x => ({
75
  key: x, name: x.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
 
119
  return true;
120
  }
121
 
122
+ // === DATASET LIBRARY CATALOG ===
123
+ const DATASET_CATALOG = {
124
+ builtin: [
125
+ { 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' },
126
+ { 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' },
127
+ { 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' },
128
+ { id: 'peace_2023', name: 'Global Peace Index 2023', category: 'Security', source: 'IEP', description: 'Peace, safety, militarization, conflict, terrorism', icon: 'shield', color: 'indigo' },
129
+ { 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' },
130
+ { id: 'corruption_perceptions_2023', name: 'Corruption Perceptions Index 2023', category: 'Governance', source: 'Transparency Int.', description: 'Perceived public sector corruption, ranking', icon: 'scale', color: 'purple' },
131
+ { id: 'labor_rights_2023', name: 'Global Rights Index 2023', category: 'Labor', source: 'ITUC', description: 'Workers rights, collective bargaining, trade unions', icon: 'briefcase', color: 'orange' },
132
+ { id: 'cybersecurity_2023', name: 'Global Cybersecurity Index 2023', category: 'Technology', source: 'ITU', description: 'Cybersecurity readiness, legal, technical, cooperation', icon: 'lock', color: 'cyan' },
133
+ { 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' },
134
+ { id: 'innovation_2023', name: 'Global Innovation Index 2023', category: 'Innovation', source: 'WIPO', description: 'Innovation capacity, outputs, institutions, infrastructure', icon: 'lightbulb', color: 'yellow' },
135
+ { 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' },
136
+ { 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' },
137
+ ],
138
+ wb_presets: [
139
+ { id: 'wb:economy', name: 'Economy', description: 'GDP, growth, debt, trade, FDI, industry', indicators: 25, icon: 'trending-up', color: 'emerald' },
140
+ { id: 'wb:health', name: 'Health', description: 'Life expectancy, mortality, health spending, disease', indicators: 25, icon: 'heart-pulse', color: 'rose' },
141
+ { id: 'wb:education', name: 'Education', description: 'Enrollment, literacy, years of schooling, spending', indicators: 20, icon: 'graduation-cap', color: 'blue' },
142
+ { id: 'wb:environment', name: 'Environment', description: 'CO2, renewables, forest, water, emissions, biodiversity', indicators: 25, icon: 'trees', color: 'green' },
143
+ { id: 'wb:social', name: 'Social & Demographics', description: 'Population, gender, inequality, migration', indicators: 20, icon: 'users', color: 'purple' },
144
+ { id: 'wb:governance', name: 'Governance & Business', description: 'Business climate, taxes, legal, women participation', indicators: 20, icon: 'landmark', color: 'amber' },
145
+ { id: 'wb:digital', name: 'Digital & Infrastructure', description: 'Internet, broadband, ICT, e-government', indicators: 15, icon: 'wifi', color: 'cyan' },
146
+ { id: 'wb:tourism', name: 'Tourism', description: 'International arrivals, tourism receipts', indicators: 5, icon: 'plane', color: 'sky' },
147
+ { id: 'wb:full', name: 'Full World Bank (120+)', description: 'Comprehensive set of all available indicators', indicators: 120, icon: 'database', color: 'slate' },
148
+ ]
149
+ };
150
+
151
  // === DATASET BROWSER ===
152
  async function showDatasetBrowser() {
153
  let existing = document.getElementById('datasetBrowserModal'); if (existing) existing.remove();
154
  const modal = document.createElement('div');
155
+ modal.id = 'datasetBrowserModal'; modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4';
156
  modal.onclick = e => { if (e.target === modal) modal.remove(); };
157
+
158
+ // Build tab content as strings first
159
+ const builtinCards = DATASET_CATALOG.builtin.map(ds => {
160
+ const isActive = CURRENT_DATASET && CURRENT_DATASET.file === ds.id;
161
+ return `
162
+ <div class="glass-light rounded-xl p-4 cursor-pointer transition-all hover:bg-brand-500/10 hover:border-brand-500/30 border border-transparent ${isActive ? 'border-brand-500/40 bg-brand-500/5' : ''}" onclick="loadBuiltinDataset('${ds.id}');document.getElementById('datasetBrowserModal').remove()">
163
+ <div class="flex items-center justify-between mb-2">
164
+ <div class="flex items-center gap-2">
165
+ <div class="w-8 h-8 rounded-lg bg-${ds.color}-500/15 flex items-center justify-center"><i data-lucide="${ds.icon}" class="w-4 h-4 text-${ds.color}-400"></i></div>
166
+ <div><div class="text-sm font-semibold text-white">${ds.name}</div><div class="text-[0.65rem] text-slate-400">${ds.source} · ${ds.category}</div></div>
167
+ </div>
168
+ ${isActive ? '<span class="text-[0.65rem] px-2 py-0.5 rounded-full bg-brand-500/20 text-brand-300">Active</span>' : ''}
169
+ </div>
170
+ <div class="text-xs text-slate-400">${ds.description}</div>
171
+ </div>`;
172
+ }).join('');
173
+
174
+ const wbCards = DATASET_CATALOG.wb_presets.map(p => `
175
+ <div class="glass-light rounded-xl p-4 cursor-pointer transition-all hover:bg-brand-500/10 hover:border-brand-500/30 border border-transparent" onclick="fetchWorldBankPreset('${p.id}');document.getElementById('datasetBrowserModal').remove()">
176
+ <div class="flex items-center gap-2 mb-2">
177
+ <div class="w-8 h-8 rounded-lg bg-${p.color}-500/15 flex items-center justify-center"><i data-lucide="${p.icon}" class="w-4 h-4 text-${p.color}-400"></i></div>
178
+ <div><div class="text-sm font-semibold text-white">${p.name}</div><div class="text-[0.65rem] text-slate-400">${p.indicators} variables</div></div>
179
+ </div>
180
+ <div class="text-xs text-slate-400">${p.description}</div>
181
  </div>
182
  `).join('');
183
+
184
+ const categoryColors = {
185
+ 'Economy': 'emerald', 'Health': 'rose', 'Education': 'blue', 'Environment': 'green',
186
+ 'Social': 'purple', 'Governance': 'amber', 'Digital': 'cyan', 'Tourism': 'sky',
187
+ 'Security': 'indigo', 'Wellbeing': 'pink', 'Innovation': 'yellow', 'Labor': 'orange',
188
+ 'Food': 'emerald', 'Technology': 'cyan', 'Development': 'blue', 'General': 'slate',
189
+ 'Climate': 'teal', 'Infrastructure': 'sky'
190
+ };
191
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  modal.innerHTML = `
193
+ <div class="glass rounded-2xl w-full max-w-3xl max-h-[85vh] overflow-hidden flex flex-col">
194
  <div class="flex items-center justify-between p-5 border-b border-slate-700/50">
195
+ <h3 class="text-lg font-bold text-white flex items-center gap-2"><i data-lucide="library" class="w-5 h-5 text-brand-400"></i>Data Library</h3>
196
  <button onclick="document.getElementById('datasetBrowserModal').remove()" class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-slate-700/50"><i data-lucide="x" class="w-4 h-4 text-slate-400"></i></button>
197
  </div>
198
+ <div class="flex border-b border-slate-700/50">
199
+ <button id="libTab-curated" onclick="switchLibTab('curated')" class="lib-tab px-4 py-3 text-xs font-medium text-brand-300 border-b-2 border-brand-500 transition-colors">Curated Datasets</button>
200
+ <button id="libTab-live" onclick="switchLibTab('live')" class="lib-tab px-4 py-3 text-xs font-medium text-slate-400 border-b-2 border-transparent hover:text-white transition-colors">Live APIs</button>
201
+ <button id="libTab-upload" onclick="switchLibTab('upload')" class="lib-tab px-4 py-3 text-xs font-medium text-slate-400 border-b-2 border-transparent hover:text-white transition-colors">Upload</button>
202
+ </div>
203
  <div class="overflow-auto p-5 flex-1">
204
+ <div id="libPane-curated">
205
+ <div class="mb-4">
206
+ <div class="text-[0.65rem] text-slate-500 mb-2 uppercase tracking-wider font-medium">Built-in Reference Datasets</div>
207
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">${builtinCards}</div>
208
+ </div>
209
+ </div>
210
+ <div id="libPane-live" class="hidden">
211
+ <div class="mb-4">
212
+ <div class="text-[0.65rem] text-slate-500 mb-2 uppercase tracking-wider font-medium">World Bank Presets</div>
213
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">${wbCards}</div>
214
+ </div>
215
+ <div class="mb-4">
216
+ <div class="text-[0.65rem] text-slate-500 mb-2 uppercase tracking-wider font-medium">Other Live Sources</div>
217
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
218
+ <div class="glass-light rounded-xl p-4 cursor-pointer transition-all hover:bg-brand-500/10 hover:border-brand-500/30 border border-transparent" onclick="fetchClimateData();document.getElementById('datasetBrowserModal').remove()">
219
+ <div class="flex items-center gap-2 mb-2">
220
+ <div class="w-8 h-8 rounded-lg bg-teal-500/15 flex items-center justify-center"><i data-lucide="cloud" class="w-4 h-4 text-teal-400"></i></div>
221
+ <div><div class="text-sm font-semibold text-white">Capital City Climate</div><div class="text-[0.65rem] text-slate-400">Open-Meteo · 195+ cities</div></div>
222
+ </div>
223
+ <div class="text-xs text-slate-400">Temperature and precipitation averages for capital cities worldwide</div>
224
+ </div>
225
+ <div class="glass-light rounded-xl p-4 cursor-pointer transition-all hover:bg-brand-500/10 hover:border-brand-500/30 border border-transparent" onclick="fetchCustomWBIndicators();document.getElementById('datasetBrowserModal').remove()">
226
+ <div class="flex items-center gap-2 mb-2">
227
+ <div class="w-8 h-8 rounded-lg bg-slate-500/15 flex items-center justify-center"><i data-lucide="list-filter" class="w-4 h-4 text-slate-400"></i></div>
228
+ <div><div class="text-sm font-semibold text-white">Custom World Bank</div><div class="text-[0.65rem] text-slate-400">120+ indicators</div></div>
229
+ </div>
230
+ <div class="text-xs text-slate-400">Select individual indicators from the full World Bank catalog</div>
231
+ </div>
232
+ </div>
233
+ </div>
234
+ </div>
235
+ <div id="libPane-upload" class="hidden">
236
+ <div class="glass-light rounded-xl p-6 text-center">
237
+ <div class="w-12 h-12 rounded-full bg-brand-500/15 flex items-center justify-center mx-auto mb-3"><i data-lucide="upload-cloud" class="w-6 h-6 text-brand-400"></i></div>
238
+ <div class="text-sm font-semibold text-white mb-2">Upload Custom Dataset</div>
239
+ <p class="text-xs text-slate-400 mb-4 max-w-sm mx-auto">Import a CSV or JSON file with country rows and indicator columns. The first column should be "country".</p>
240
+ <label class="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-brand-600/80 text-sm text-white hover:bg-brand-500 cursor-pointer transition-colors">
241
+ <i data-lucide="file-up" class="w-4 h-4"></i>Choose File
242
+ <input type="file" accept=".json,.csv" class="hidden" onchange="handleFileUpload(event);document.getElementById('datasetBrowserModal').remove()">
243
+ </label>
244
+ </div>
245
  </div>
246
  </div>
247
  </div>`;
248
  document.body.appendChild(modal); lucide.createIcons();
249
  }
250
 
251
+ function switchLibTab(tab) {
252
+ document.querySelectorAll('.lib-tab').forEach(t => { t.classList.remove('text-brand-300', 'border-brand-500'); t.classList.add('text-slate-400', 'border-transparent'); });
253
+ document.getElementById('libTab-' + tab).classList.remove('text-slate-400', 'border-transparent');
254
+ document.getElementById('libTab-' + tab).classList.add('text-brand-300', 'border-brand-500');
255
+ ['curated','live','upload'].forEach(t => document.getElementById('libPane-' + t).classList.add('hidden'));
256
+ document.getElementById('libPane-' + tab).classList.remove('hidden');
257
+ }
258
+
259
+ async function loadBuiltinDataset(datasetId) {
260
+ showStatus('Loading ' + datasetId + '...', 20);
261
+ try {
262
+ const result = await api('/api/datasets/builtin/' + datasetId);
263
+ if (!result || !result.data || !result.data.length) { showStatus('No data returned', 100); return; }
264
+ DATASET.length = 0; result.data.forEach(d => DATASET.push(d));
265
+ VARIABLE_DEFS.length = 0; result.indicators.forEach(v => VARIABLE_DEFS.push(v));
266
+ dataset = DATASET; variableDefs = VARIABLE_DEFS;
267
+ categories = [...new Set(variableDefs.map(v => v.category))];
268
+ weights = {}; variableDefs.forEach(v => weights[v.key] = 1);
269
+ selectedVar = null; corrFilter = 'all'; activeCategory = null;
270
+ document.getElementById('emptyState').classList.remove('hidden');
271
+ document.getElementById('resultsArea').classList.add('hidden');
272
+ const vs = document.getElementById('varSearch'); if (vs) vs.value = '';
273
+ showStatus('Loaded ' + result.name, 100);
274
+ renderCategoryGrid(); renderVariableList(); initDecisionFramework();
275
+ initBenchmark(); initSimulatorUI(); initCompareUI();
276
+ lucide.createIcons();
277
+ 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 };
278
+ const dp2 = document.getElementById('dataPointCount');
279
+ if (dp2) dp2.innerHTML = `<span class="w-2 h-2 rounded-full bg-emerald-400 pulse-dot"></span><span>${variableDefs.length} variables</span>`;
280
+ } catch (e) { showStatus('Failed: ' + e.message, 100); console.error(e); }
281
+ }
282
+
283
+ async function fetchWorldBankPreset(presetId) {
284
+ const preset = DATASET_CATALOG.wb_presets.find(p => p.id === presetId);
285
+ if (!preset) { showStatus('Preset not found', 100); return; }
286
+ showStatus('Fetching ' + preset.name + '...', 20);
287
+ try {
288
+ const sources = await api('/api/sources/list');
289
+ const p = sources.worldbank_presets.find(x => x.id === presetId);
290
+ if (!p) { showStatus('Preset not found on server', 100); return; }
291
+ const result = await api(`/api/worldbank/fetch?indicators=${p.indicators}&countries=all&date_range=2020:2023`);
292
+ if (!result.data || !result.data.length) { showStatus('No data returned', 100); return; }
293
+ const keys = Object.keys(result.data[0]).filter(x => x !== 'country');
294
+ 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 }));
295
+ DATASET.length = 0; result.data.forEach(d => DATASET.push(d));
296
+ VARIABLE_DEFS.length = 0; vars.forEach(v => VARIABLE_DEFS.push(v));
297
+ dataset = DATASET; variableDefs = VARIABLE_DEFS;
298
+ categories = [...new Set(variableDefs.map(v => v.category))];
299
+ weights = {}; variableDefs.forEach(v => weights[v.key] = 1);
300
+ selectedVar = null; corrFilter = 'all'; activeCategory = null;
301
+ document.getElementById('emptyState').classList.remove('hidden');
302
+ document.getElementById('resultsArea').classList.add('hidden');
303
+ showStatus(`Loaded ${preset.name} (${vars.length} variables)`, 100);
304
+ renderCategoryGrid(); renderVariableList(); initDecisionFramework();
305
+ initBenchmark(); initSimulatorUI(); initCompareUI();
306
+ lucide.createIcons();
307
+ 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 };
308
+ const dp2 = document.getElementById('dataPointCount');
309
+ if (dp2) dp2.innerHTML = `<span class="w-2 h-2 rounded-full bg-emerald-400 pulse-dot"></span><span>${variableDefs.length} variables</span>`;
310
+ } catch (e) { showStatus('Fetch failed: ' + e.message, 100); }
311
+ }
312
+
313
+ async function fetchCustomWBIndicators() {
314
+ showStatus('Loading indicator catalog...', 10);
315
+ try {
316
+ const wb = await api('/api/worldbank/indicators');
317
+ if (!wb.indicators) { showStatus('Catalog unavailable', 100); return; }
318
+ const indList = wb.indicators.map(i => `<option value="${i.id}">${i.name} [${i.wb_code}] (${i.category})</option>`).join('');
319
+ let modal = document.createElement('div');
320
+ modal.id = 'customWBModal'; modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4';
321
+ modal.onclick = e => { if (e.target === modal) modal.remove(); };
322
+ modal.innerHTML = `
323
+ <div class="glass rounded-2xl w-full max-w-lg max-h-[80vh] overflow-hidden flex flex-col">
324
+ <div class="flex items-center justify-between p-5 border-b border-slate-700/50">
325
+ <h3 class="text-lg font-bold text-white">Custom World Bank Indicators</h3>
326
+ <button onclick="document.getElementById('customWBModal').remove()" class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-slate-700/50"><i data-lucide="x" class="w-4 h-4 text-slate-400"></i></button>
327
+ </div>
328
+ <div class="p-5 flex-1 overflow-auto">
329
+ <p class="text-xs text-slate-400 mb-3">Hold Ctrl/Cmd to select multiple. Selected: <span id="wbSelCount" class="text-brand-300 font-semibold">0</span></p>
330
+ <select id="wbIndicatorSelect" multiple class="w-full h-64 px-3 py-2 rounded-lg bg-slate-800/80 border border-slate-700/50 text-xs text-white mb-3 overflow-y-auto">${indList}</select>
331
+ <button onclick="fetchWorldBankData()" class="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-brand-600/80 text-sm text-white hover:bg-brand-500 transition-colors">
332
+ <i data-lucide="download" class="w-4 h-4"></i>Fetch & Load
333
+ </button>
334
+ </div>
335
+ </div>`;
336
+ document.body.appendChild(modal); lucide.createIcons();
337
+ const sel = document.getElementById('wbIndicatorSelect');
338
+ if (sel) sel.addEventListener('change', () => { const cnt = document.getElementById('wbSelCount'); if (cnt) cnt.textContent = sel.selectedOptions.length; });
339
+ } catch (e) { showStatus('Catalog load failed', 100); }
340
+ }
341
+
342
  async function fetchWorldBankData() {
343
  const sel = document.getElementById('wbIndicatorSelect'); if (!sel) return;
344
  const selected = Array.from(sel.selectedOptions).map(o => o.value);