Datasets:

Modalities:
Document
Languages:
English
Size:
< 1K
Libraries:
Datasets
License:
File size: 35,009 Bytes
c6d7739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>BTI Data Exporter - ARAC International</title>

  <link rel="icon" type="image/png" href="https://quanta-analytica.mnshakoor.com/logo-mns120.png">
  <meta name="title" content="BTI Data Exporter - ARAC International">
  <meta name="description" content="Stream the BTI Parquet dataset, filter by region, country, and year, select indicators, and export curated CSV. Powered by DuckDB-WASM.">

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

  <style>

    :root{ --bg:#fff; --fg:#222; --panel:#f6f6f6; --line:#e5e5e5; --accent:#0a84ff; --danger:#d9534f; }

    .dark-mode{ --bg:#1e1e1e; --fg:#f2f2f2; --panel:#2b2b2b; --line:#444; --accent:#3399ff; --danger:#e06666; }

    html,body{height:100%;}

    body{margin:0; font-family: Inter, system-ui, Segoe UI, Roboto, Arial, sans-serif; background:var(--bg); color:var(--fg); display:flex; flex-direction:column; overflow:hidden;}

    #navbar{display:flex; align-items:center; gap:.5rem; padding:.6rem 1rem; background:var(--panel); border-bottom:1px solid var(--line);}

    #navbar h1{font-size:1.05rem; margin:0; flex:1;}

    .nav-button, button{ padding:.4rem .7rem; background:var(--panel); border:1px solid var(--line); border-radius:6px; cursor:pointer; color:var(--fg);}

    .primary{ background:var(--accent); color:#fff; border-color:var(--accent); }

    #content{flex:1; display:flex; overflow:hidden;}

    #control{width:270px; background:var(--panel); border-right:1px solid var(--line); overflow:auto; padding:1rem;}

    #main{flex:1; display:flex; flex-direction:column; overflow:hidden; min-width:0;}

    #map{height:280px; border-bottom:1px solid var(--line); z-index:0;}

    #grid{flex:1; overflow:auto; padding:1rem;}

    h3{margin:.8rem 0 .4rem 0; font-size:1rem;}

    select{width:100%; padding:.35rem .4rem; border:1px solid var(--line); border-radius:6px; background:var(--bg); color:var(--fg);}

    .row{display:flex; gap:.5rem;} .row > *{flex:1;}

    table{width:100%; border-collapse:collapse; font-size:.9rem;}

    th,td{border:1px solid var(--line); padding:.45rem .5rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;}

    th{position:sticky; top:0; background:var(--panel); z-index:1;}

    .spinner{ display:none; position:absolute; inset:0; background:rgba(0,0,0,.12); align-items:center; justify-content:center; z-index:9; }

    .spinner::after{ content:""; width:56px; height:56px; border:8px solid var(--panel); border-top:8px solid var(--accent); border-radius:50%; animation:spin 1s linear infinite; }

    @keyframes spin{to{transform:rotate(360deg)}}

    .note{font-size:.85rem; opacity:.85;}

    .foot{font-size:.8rem; opacity:.8; margin-top:.8rem;}

    .stack{display:flex; flex-direction:column; gap:.4rem;}

  </style>
</head>
<body>
  <div id="overlay" class="spinner" aria-hidden="true"></div>

  <div id="navbar">
    <h1>BTI Data Exporter - ARAC International</h1>
    <button id="btnTheme" class="nav-button">Toggle Theme</button>
    <button id="btnAbout" class="nav-button">About</button>
  </div>

  <div id="content">
    <aside id="control">
      <div class="stack">
        <div>
          <h3>Indicators</h3>
          <select id="selIndicators" multiple size="10" title="Select one or more indicators"></select>
          <div class="note">List is auto-built from BTI columns. Use Ctrl or Cmd to multi-select.</div>
        </div>
        <div>
          <h3>Region</h3>
          <select id="selRegions" multiple size="6"></select>
        </div>
        <div>
          <h3>Country</h3>
          <select id="selCountries" multiple size="10"></select>
        </div>
        <div>
          <h3>Year Range</h3>
          <div class="row">
            <select id="selY1"></select>
            <select id="selY2"></select>
          </div>
        </div>
        <div>
          <h3>Actions</h3>
          <div class="row">
            <button id="btnReset">Reset</button>
            <button id="btnExport" class="primary">Export CSV</button>
          </div>
        </div>
        <div class="foot">Data streams from Parquet via HTTP range requests.</div>
      </div>
    </aside>

    <main id="main">
      <div id="map"></div>
      <div id="grid">
        <p style="text-align:center;margin-top:2rem;">Choose filters and indicators to render the table below.</p>
        <div id="tableWrap"></div>
      </div>
    </main>
  </div>

  <dialog id="aboutDlg" style="max-width:900px;width:90%;border:1px solid var(--line);border-radius:8px;background:var(--panel);color:var(--fg);">
    <form method="dialog" style="margin:0;">
      <div style="display:flex;justify-content:space-between;align-items:center;gap:.5rem;padding:.8rem 1rem;border-bottom:1px solid var(--line);">
        <strong>About BTI</strong>
        <button>OK</button>
      </div>
      <div style="padding:1rem;max-height:65vh;overflow:auto;">
        <p class="note">
          The Transformation Index BTI aggregates 17 criteria and 49 indicators into the Status Index and Governance Index using expert reports, peer review, and regional plus interregional calibration. See the PDFs in this repository for details.
        </p>
	<a href="https://huggingface.co/datasets/ARACInt/bti-data/tree/main"

   target="_blank" rel="noopener noreferrer"

   style="display:inline-block;padding:8px 12px;border:1px solid #0a84ff;border-radius:6px;text-decoration:none;color:#fff;background:#0a84ff;">
  View the dataset on Hugging Face
</a>
	
      </div>
<div id="bti-citation" style="line-height:1.45">
  <p><strong>Recommended BTI citation</strong></p>
  <p>
    Bertelsmann Stiftung. <em>BTI 2024: Transformation Index</em>. Gütersloh: Bertelsmann Stiftung, 2024.
    Available at
    <a href="https://www.bti-project.org" target="_blank" rel="noopener noreferrer">https://www.bti-project.org</a>.
  </p>
</div>

	<div id="about-bti" style="line-height:1.45">
  <h2>The Bertelsmann Transformation Index</h2>

  <h3>What it is</h3>
  <p>
    The Transformation Index BTI is a comparative assessment of political and economic transformation and the quality of governance in 137 developing and transition countries. BTI publishes two composite rankings: the <strong>Status Index</strong> and the <strong>Governance Index</strong>. Scores are based on standardized expert assessments using a 10 to 1 scale anchored by descriptive benchmarks.
  </p>

  <h3>History and purpose</h3>
  <ul>
    <li><strong>Origins and cadence</strong> The BTI has been produced by Bertelsmann Stiftung since 2003 and appears biennially.</li>
    <li><strong>Scope</strong> Focuses on transformation contexts by excluding long consolidated OECD democracies.</li>
    <li><strong>Purpose</strong> Provide transparent, comparable evidence to guide policy, research, and practice toward democracy under the rule of law and a socially responsible market economy.</li>
  </ul>

  <h3>How the methodology works</h3>
  <ul>
    <li><strong>Framework</strong> 17 criteria and 49 indicators organized into Democracy, Market Economy, and Governance.</li>
    <li><strong>Expert process</strong> One country author drafts a report and ratings. A second expert independently reviews. Scores undergo regional and interregional calibration and final board review to ensure cross country comparability.</li>
    <li><strong>Scale</strong> Indicators are rated 10 to 1 with anchored descriptors so that like conditions receive like scores across countries and time.</li>
    <li><strong>Indices</strong>
      <ul>
        <li><strong>Status Index</strong> Average of political transformation and economic transformation.</li>
        <li><strong>Governance Index</strong> Average of governance criteria, interpreted in light of the Level of Difficulty.</li>
        <li><strong>Level of Difficulty</strong> Captures structural constraints that shape feasible governance performance.</li>
      </ul>
    </li>
  </ul>

  <hr>

  <h3>Complete indicator structure</h3>
  <p class="note">Below are all 17 criteria and 49 indicators. Each entry includes what it measures and why it matters.</p>

  <details open>
    <summary><strong>Democracy</strong> 5 criteria, 18 indicators</summary>
    <ol>
      <li><strong>Stateness</strong>
        <ol>
          <li><strong>Monopoly on the use of force</strong> Measures state control of security across territory. <em>Why</em> Without it, rules cannot be enforced.</li>
          <li><strong>State identity</strong> Measures acceptance of citizenship and the nation state. <em>Why</em> Disputed nationhood destabilizes institutions.</li>
          <li><strong>No interference of religious dogmas</strong> Measures secular operation of law and institutions. <em>Why</em> Prevents non plural restrictions on rights.</li>
          <li><strong>Basic administration</strong> Measures reach and functionality of core services. <em>Why</em> Administration is the operating system of democracy.</li>
        </ol>
      </li>

      <li><strong>Political participation</strong>
        <ol>
          <li><strong>Free and fair elections</strong> Measures integrity and competitiveness of elections. <em>Why</em> Provides democratic mandate.</li>
          <li><strong>Effective power to govern</strong> Measures freedom from veto actors. <em>Why</em> Ensures elected authority is real authority.</li>
          <li><strong>Association and assembly rights</strong> Measures ability to form groups and assemble. <em>Why</em> Enables organized participation and oversight.</li>
          <li><strong>Freedom of expression</strong> Measures protection of speech and media pluralism. <em>Why</em> Supports accountability and policy debate.</li>
        </ol>
      </li>

      <li><strong>Rule of law</strong>
        <ol>
          <li><strong>Separation of powers</strong> Measures checks and balances in practice. <em>Why</em> Limits abuse and arbitrariness.</li>
          <li><strong>Independent judiciary</strong> Measures autonomy, capacity, and integrity of courts. <em>Why</em> Safeguards rights and constrains executives.</li>
          <li><strong>Prosecution of office abuse</strong> Measures investigation and sanction of corruption. <em>Why</em> Reduces impunity and restores trust.</li>
          <li><strong>Civil rights</strong> Measures protection and equal access to justice. <em>Why</em> Constitutes substantive citizenship.</li>
        </ol>
      </li>

      <li><strong>Stability of democratic institutions</strong>
        <ol>
          <li><strong>Performance of democratic institutions</strong> Measures effectiveness and reliability of bodies. <em>Why</em> Converts rules into results.</li>
          <li><strong>Commitment to democratic institutions</strong> Measures acceptance by key actors. <em>Why</em> Legitimacy prevents disruptive vetoes.</li>
        </ol>
      </li>

      <li><strong>Political and social integration</strong>
        <ol>
          <li><strong>Party system</strong> Measures rootedness, fragmentation, polarization, volatility. <em>Why</em> Stable competition aggregates interests.</li>
          <li><strong>Interest groups</strong> Measures breadth and balance of organized interests. <em>Why</em> Inclusive intermediation limits capture.</li>
          <li><strong>Approval of democracy</strong> Measures public support for norms and institutions. <em>Why</em> Mass legitimacy builds resilience.</li>
          <li><strong>Social capital</strong> Measures trust and self organization. <em>Why</em> Enables cooperation beyond the state.</li>
        </ol>
      </li>
    </ol>
  </details>

  <details>
    <summary><strong>Market economy</strong> 7 criteria, 14 indicators</summary>
    <ol start="6">
      <li><strong>Level of socioeconomic development</strong>
        <ol>
          <li><strong>Socioeconomic barriers</strong> Measures poverty and inequality that exclude participation. <em>Why</em> Structural exclusion limits opportunity.</li>
        </ol>
      </li>

      <li><strong>Organization of the market and competition</strong>
        <ol>
          <li><strong>Market organization</strong> Measures open entry, free pricing, non discrimination. <em>Why</em> Predictable rules enable competition.</li>
          <li><strong>Competition policy</strong> Measures antitrust framework and enforcement. <em>Why</em> Prevents monopolistic distortions.</li>
          <li><strong>Liberalization of foreign trade</strong> Measures tariff and non tariff openness. <em>Why</em> Integration improves efficiency and choice.</li>
          <li><strong>Banking system</strong> Measures supervision and financial stability. <em>Why</em> Sound finance underpins investment.</li>
        </ol>
      </li>

      <li><strong>Monetary and fiscal stability</strong>
        <ol>
          <li><strong>Monetary stability</strong> Measures credibility of anti inflation policy. <em>Why</em> Reduces uncertainty in transactions.</li>
          <li><strong>Fiscal stability</strong> Measures sustainability of public finances. <em>Why</em> Preserves policy space and confidence.</li>
        </ol>
      </li>

      <li><strong>Private property</strong>
        <ol>
          <li><strong>Property rights</strong> Measures clarity and enforcement of rights. <em>Why</em> Security of ownership motivates investment.</li>
          <li><strong>Private enterprise</strong> Measures fair treatment of private firms and hard budget constraints. <em>Why</em> Encourages entrepreneurship and discipline.</li>
        </ol>
      </li>

      <li><strong>Welfare regime</strong>
        <ol>
          <li><strong>Social safety nets</strong> Measures coverage and effectiveness of protection. <em>Why</em> Shields vulnerable groups against shocks.</li>
          <li><strong>Equal opportunity</strong> Measures access to education, jobs, and services without discrimination. <em>Why</em> Inclusion supports sustainable growth.</li>
        </ol>
      </li>

      <li><strong>Economic performance</strong>
        <ol>
          <li><strong>Output strength</strong> Measures growth, employment, investment, and external balance. <em>Why</em> Summarizes macro outcomes.</li>
        </ol>
      </li>

      <li><strong>Sustainability</strong>
        <ol>
          <li><strong>Environmental policy</strong> Measures conservation, climate action, and resource management. <em>Why</em> Protects long run prosperity.</li>
          <li><strong>Education and R&amp;D policy</strong> Measures human capital and innovation policy. <em>Why</em> Drives productivity and competitiveness.</li>
        </ol>
      </li>
    </ol>
  </details>

  <details>
    <summary><strong>Governance</strong> 5 criteria, 17 indicators plus Level of Difficulty context</summary>
    <ol start="13">
      <li><strong>Level of difficulty</strong>
        <ol>
          <li><strong>Structural constraints</strong> Measures geography, infrastructure, disasters, resource limits. <em>Why</em> Sets baseline difficulty for governing.</li>
          <li><strong>Civil society traditions</strong> Measures associational density and engagement legacies. <em>Why</em> Affects participation capacity.</li>
          <li><strong>Conflict intensity</strong> Measures incidence and severity of violent conflict. <em>Why</em> Violence impedes governance and reform.</li>
        </ol>
      </li>

      <li><strong>Steering capability</strong>
        <ol>
          <li><strong>Prioritization</strong> Measures clarity and consistency of strategic goals. <em>Why</em> Guides action under constraints.</li>
          <li><strong>Implementation</strong> Measures execution of policy and reform. <em>Why</em> Delivers outcomes, not just plans.</li>
          <li><strong>Policy learning</strong> Measures adaptation, evaluation, and evidence use. <em>Why</em> Improves fit to changing conditions.</li>
        </ol>
      </li>

      <li><strong>Resource efficiency</strong>
        <ol>
          <li><strong>Efficient use of assets</strong> Measures fiscal, administrative, and human resource efficiency. <em>Why</em> Maximizes scarce capacity.</li>
          <li><strong>Policy coordination</strong> Measures coherence across ministries and levels. <em>Why</em> Reduces duplication and contradictions.</li>
          <li><strong>Anti corruption policy</strong> Measures prevention, enforcement, and integrity systems. <em>Why</em> Protects resources and trust.</li>
        </ol>
      </li>

      <li><strong>Consensus building</strong>
        <ol>
          <li><strong>Consensus on goals</strong> Measures elite commitment to democracy and market economy. <em>Why</em> Aligns reform direction.</li>
          <li><strong>Anti democratic actors</strong> Measures how leadership addresses spoilers. <em>Why</em> Limits rollback risks.</li>
          <li><strong>Cleavage and conflict management</strong> Measures mediation of ethnic, religious, regional divides. <em>Why</em> Prevents polarization and violence.</li>
          <li><strong>Civil society participation</strong> Measures inclusion of CSOs in policy making. <em>Why</em> Improves legitimacy and information.</li>
          <li><strong>Reconciliation</strong> Measures acknowledgement of past injustice and healing steps. <em>Why</em> Builds social cohesion.</li>
        </ol>
      </li>

      <li><strong>International cooperation</strong>
        <ol>
          <li><strong>Effective use of support</strong> Measures alignment with and absorption of external assistance. <em>Why</em> Multiplies domestic capacity.</li>
          <li><strong>Credibility</strong> Measures reliability and rule consistent behavior with partners. <em>Why</em> Sustains cooperation and investment.</li>
          <li><strong>Regional cooperation</strong> Measures constructive engagement with neighbors and regional bodies. <em>Why</em> Addresses cross border challenges.</li>
        </ol>
      </li>
    </ol>
  </details>

  <hr>

  <h3>How to read BTI scores in this app</h3>
  <ul>
    <li>Scores run from 10 high to 1 low and are comparable across countries and time.</li>
    <li>Status Index reflects the average of political and economic transformation blocks. Governance Index reflects leadership performance in context.</li>
    <li>Use filters to select regions, countries, and years then export a curated CSV for analysis.</li>
  </ul>
</div>

    </form>
  </dialog>

  <script type="module">

    import * as duckdb from 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';



    // Config

    const AppConfig = {

      DATA_URL: 'https://huggingface.co/datasets/ARACInt/bti-data/resolve/main/2024-2006-bti-data.parquet',

      patterns: { country:/^country$/i, region:/^region$/i, year:/^year$/i },

      indicatorTokens: [

        'status index','democracy status','economy status','governance index','governance performance',

        'stateness','political participation','rule of law','stability of democratic institutions',

        'political and social integration','level of socioeconomic development','organization of the market','competition',

        'monetary','private property','welfare regime','economic performance','sustainability',

        'level of difficulty','steering capability','resource efficiency','consensus','international cooperation',

        'q1','q2','q3','q4','q5','q6','q7','q8','q9','q10','q11','q12','q13','q14','q15','q16','q17'

      ],

      previewRows: 500

    };



    // State

    const State = {

      db:null, conn:null, schema:[], mapping:{},

      keyCols:{country:null, region:null, year:null},

      indicatorList:[], years:[],

      geojson:null, map:null, mapLayer:null, name2iso:{}

    };



    // Utils

    const showOverlay = (on=true)=>{ document.getElementById('overlay').style.display = on ? 'flex' : 'none'; };

    const norm = (s)=> s.replace(/\s+/g,' ').trim().replace(/[|/()\u2013\u2014\-]+/g,' ').replace(/\s+/g,' ').toLowerCase();

    const safe = (s)=> norm(s).replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'');

    const asNum = v => (typeof v === 'bigint' ? Number(v) : (typeof v === 'string' ? Number(v) : v));

    const asStr = v => (v == null ? '' : (typeof v === 'bigint' ? v.toString() : String(v)));

    const normalizeName = s => (s ?? '')

      .normalize('NFD').replace(/[\u0300-\u036f]/g,'')

      .replace(/’/g,"'").toLowerCase()

      .replace(/[^a-z'& ]+/g,' ').replace(/\s+/g,' ').trim();



    const BTI_ALIASES = {

      "drc": "democratic republic of the congo",

      "dr congo": "democratic republic of the congo",

      "congo, dem. rep.": "democratic republic of the congo",

      "republic of congo": "republic of the congo",

      "cote d'ivoire": "cote d'ivoire",

      "cote d ivoire": "cote d'ivoire",

      "czech republic": "czechia",

      "türkiye": "turkey",

      "turkiye": "turkey",

      "serbia": "serbia",

      "tanzania": "tanzania",

      "united republic of tanzania": "tanzania"

    };



    const yearExpr = (col) => `

      CASE

        WHEN TRY_CAST(${col} AS INT) IS NOT NULL THEN CAST(${col} AS INT)

        WHEN ${col} ~ '^[0-9]{4}$' THEN CAST(${col} AS INT)

        WHEN ${col} LIKE '%/%/%' THEN EXTRACT(YEAR FROM STRPTIME(${col}, '%m/%d/%Y'))

        WHEN ${col} LIKE '____-__-__' THEN EXTRACT(YEAR FROM STRPTIME(${col}, '%Y-%m-%d'))

        ELSE NULL

      END

    `;



    async function initDuckDB(){

      showOverlay(true);

      try{

        const bundles = duckdb.getJsDelivrBundles();

        const bundle = await duckdb.selectBundle(bundles);

        const worker = await duckdb.createWorker(bundle.mainWorker);

        const db = new duckdb.AsyncDuckDB(new duckdb.ConsoleLogger(), worker);

        await db.instantiate(bundle.mainModule, bundle.pthreadWorker);

        const conn = await db.connect();

        await conn.query(`INSTALL httpfs; LOAD httpfs; SET enable_http_metadata_cache=true;`);

        State.db = db; State.conn = conn;

      }finally{ showOverlay(false); }

    }



    async function buildView(){

      showOverlay(true);

      try{

        await State.conn.query(`CREATE OR REPLACE VIEW raw_bti AS SELECT * FROM read_parquet('${AppConfig.DATA_URL}')`);

        const info = await State.conn.query(`PRAGMA table_info('raw_bti')`);

        const cols = info.toArray().map(r => r.name);

        State.schema = cols;

        State.mapping = cols.reduce((acc,c)=>{ acc[c]=safe(c); return acc; },{});



        function findKey(pattern){ for(const raw of cols){ if(pattern.test(raw)) return {raw, as: State.mapping[raw]}; } return null; }

        State.keyCols = {

          country: findKey(AppConfig.patterns.country),

          region:  findKey(AppConfig.patterns.region),

          year:    findKey(AppConfig.patterns.year)

        };



        const selectList = cols.map(raw => `"${raw}" AS ${State.mapping[raw]}`).join(', ');

        await State.conn.query(`CREATE OR REPLACE VIEW bti AS SELECT ${selectList} FROM raw_bti`);



        if(State.keyCols.year){

          const yrs = await State.conn.query(`

            SELECT DISTINCT ${yearExpr(State.keyCols.year.as)} AS y

            FROM bti WHERE ${State.keyCols.year.as} IS NOT NULL

            ORDER BY 1

          `);

          State.years = yrs.toArray().map(r => asNum(r.y)).filter(n => Number.isFinite(n));

        }



        const indicatorCandidates = cols

          .map(raw => ({ raw, as: State.mapping[raw], label: raw }))

          .filter(c=>{

            const L = norm(c.label);

            if(Object.values(State.keyCols).some(k => k && k.as === c.as)) return false;

            const tokenHit = AppConfig.indicatorTokens.some(tok => L.includes(tok));

            const qHit = /^q\d+(\.\d+)?/.test(L);

            return tokenHit || qHit;

          });



        const seen = new Set();

        const finalIndicators = [];

        for(const c of indicatorCandidates){

          if(seen.has(c.as)) continue;

          seen.add(c.as);

          finalIndicators.push({ key:c.as, raw:c.raw, as:c.as });

        }

        finalIndicators.sort((a,b)=> a.raw.localeCompare(b.raw));

        State.indicatorList = finalIndicators;



      }catch(e){

        console.error('Error building the data view:', e);

        alert('Failed to read the Parquet schema. See console for details.');

      }finally{ showOverlay(false); }

    }



    async function loadWorld(){

      if(State.geojson) return State.geojson;

      const resp = await fetch('https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson');

      State.geojson = await resp.json();



      const m = {};

      for(const f of State.geojson.features){

        const base = normalizeName(f.properties.name);

        m[base] = f.id;

        if(base === 'democratic republic of the congo'){ m['drc']=f.id; m['dr congo']=f.id; m["congo, dem. rep."]=f.id; }

        if(base === 'republic of the congo'){ m['republic of congo']=f.id; }

        if(base === 'cote d\'ivoire'){ m["cote d ivoire"]=f.id; }

        if(base === 'czechia'){ m['czech republic']=f.id; }

        if(base === 'turkey'){ m['turkiye']=f.id; m['türkiye']=f.id; }

        if(base === 'tanzania'){ m['united republic of tanzania']=f.id; }

      }

      State.name2iso = m;

      return State.geojson;

    }



    function isoForCountryName(name){

      const n = normalizeName(name);

      if(State.name2iso[n]) return State.name2iso[n];

      const alias = BTI_ALIASES[n];

      if(alias && State.name2iso[alias]) return State.name2iso[alias];

      return null;

    }



    function initMap(){

      State.map = L.map('map',{zoomControl:true}).setView([20,0],2);

      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{ attribution:'© OpenStreetMap' }).addTo(State.map);

    }



    function fillSelect(sel, arr, value='value', label='label'){ sel.innerHTML=''; arr.forEach(r=> sel.add(new Option(r[label], r[value]))); }

    function getMulti(sel){ return Array.from(sel.selectedOptions).map(o=>o.value); }



    async function populateFilters(){

      fillSelect(document.getElementById('selIndicators'), State.indicatorList.map(x=>({value:x.key, label:x.raw})));

      const r = await State.conn.query(`SELECT DISTINCT ${State.keyCols.region.as} AS v FROM bti WHERE ${State.keyCols.region.as} IS NOT NULL ORDER BY 1`);

      fillSelect(document.getElementById('selRegions'), r.toArray().map(x=>({value:x.v, label:x.v})));

      const c = await State.conn.query(`SELECT DISTINCT ${State.keyCols.country.as} AS v FROM bti WHERE ${State.keyCols.country.as} IS NOT NULL ORDER BY 1`);

      fillSelect(document.getElementById('selCountries'), c.toArray().map(x=>({value:x.v, label:x.v})));

      const y1 = document.getElementById('selY1'), y2 = document.getElementById('selY2'); y1.innerHTML=''; y2.innerHTML='';

      State.years.forEach(y=>{ y1.add(new Option(y,y)); y2.add(new Option(y,y)); });

      if(State.years.length){ y1.value = Math.min(...State.years); y2.value = Math.max(...State.years); }

    }



    function buildQuery({regions,countries,y1,y2,indicators}){

      const cols = [];

      if(State.keyCols.region)  cols.push(`${State.keyCols.region.as} AS "Region"`);

      if(State.keyCols.country) cols.push(`${State.keyCols.country.as} AS "Country"`);

      if(State.keyCols.year)    cols.push(`${yearExpr(State.keyCols.year.as)} AS "Year"`);



      for(const k of indicators){

        const found = State.indicatorList.find(x => x.key === k);

        if(found) cols.push(`${found.as} AS "${found.raw}"`);

      }



      const where = [];

      if(regions.length && State.keyCols.region)  where.push(`${State.keyCols.region.as} IN (${regions.map(v=>`'${v.replace(/'/g,"''")}'`).join(',')})`);

      if(countries.length && State.keyCols.country) where.push(`${State.keyCols.country.as} IN (${countries.map(v=>`'${v.replace(/'/g,"''")}'`).join(',')})`);

      if(State.keyCols.year && y1 && y2) where.push(`${yearExpr(State.keyCols.year.as)} BETWEEN ${asNum(y1)} AND ${asNum(y2)}`);



      return `SELECT ${cols.join(', ')} FROM bti ${where.length?'WHERE '+where.join(' AND '):''} ORDER BY "Region","Country","Year"`;

    }



    async function renderTable(){

      const indicators = getMulti(document.getElementById('selIndicators'));

      const tableWrap = document.getElementById('tableWrap');

      if(!indicators.length){

        tableWrap.innerHTML = '<p class="note" style="text-align:center;">Select one or more indicators.</p>';

        if(State.mapLayer) State.map.removeLayer(State.mapLayer); State.map.setView([20,0],2);

        return;

      }



      showOverlay(true);

      try{

        const sql = buildQuery({

          regions:getMulti(document.getElementById('selRegions')),

          countries:getMulti(document.getElementById('selCountries')),

          y1:document.getElementById('selY1').value,

          y2:document.getElementById('selY2').value,

          indicators

        });

        const rs = await State.conn.query(sql);

        const all = rs.toArray();

        const rows = all.slice(0, AppConfig.previewRows);



        if(!rows.length){

          tableWrap.innerHTML = '<p class="note" style="text-align:center;">No rows match the current filters.</p>';

          if(State.mapLayer) State.map.removeLayer(State.mapLayer); State.map.setView([20,0],2);

          return;

        }



        const cols = Object.keys(rows[0]);

        let html = '<table><thead><tr>'; cols.forEach(c=> html += `<th>${c}</th>`); html += '</tr></thead><tbody>';

        rows.forEach(r=>{ html += '<tr>'; cols.forEach(c=> html += `<td>${asStr(r[c])}</td>`); html += '</tr>'; }); html += '</tbody></table>';

        if(all.length>rows.length){ html += `<div class="foot">Showing ${rows.length} of ${all.length} rows.</div>`; }

        tableWrap.innerHTML = html;



        const endYear = document.getElementById('selY2').value;

        const metric = cols.find(c => !['Region','Country','Year'].includes(c));

        if(metric){ await renderChoropleth(all.filter(r=>String(r.Year)===String(endYear)), metric); }

      }catch(e){

        console.error('Error rendering table:', e);

        tableWrap.innerHTML = `<p class="note" style="text-align:center;color:#d9534f;">Error while fetching data. See console.</p>`;

      }finally{ showOverlay(false); }

    }



    async function renderChoropleth(dataForYear, metric){

      if(State.mapLayer) State.map.removeLayer(State.mapLayer);

      await loadWorld();



      const valueByIso = {};

      for(const row of dataForYear){

        const iso = isoForCountryName(row.Country);

        if(iso != null){

          const v = Number(row[metric]);

          if(Number.isFinite(v)) valueByIso[iso] = v;

        }

      }



      const values = Object.values(valueByIso).filter(v=>Number.isFinite(v));

      if(!values.length){ State.map.setView([20,0],2); return; }

      const min = Math.min(...values), max = Math.max(...values);

      const getColor = d => { if(!Number.isFinite(d)) return '#ccc'; const t=(d-min)/(max-min||1); if(t>0.66) return '#228B22'; if(t>0.33) return '#FFD700'; return '#DC143C'; };



      State.mapLayer = L.geoJSON(State.geojson,{

        style:f=>({weight:.5,color:'#666',fillOpacity:.7,fillColor:getColor(valueByIso[f.id])}),

        onEachFeature:(f,layer)=>{ const v=valueByIso[f.id]; layer.bindTooltip(`${f.properties.name}: ${Number.isFinite(v)?v.toFixed(2):'N/A'}`); }

      }).addTo(State.map);



      const selected = new Set(getMulti(document.getElementById('selCountries')).map(n=>isoForCountryName(n)));

      const fit = State.geojson.features.filter(f=>selected.has(f.id));

      if(fit.length){ const b=L.geoJSON({type:'FeatureCollection',features:fit}).getBounds(); if(b.isValid()) State.map.fitBounds(b,{padding:[20,20]}); }

    }



    async function exportCSV(){

      const indicators = getMulti(document.getElementById('selIndicators'));

      if(!indicators.length){ alert('Select one or more indicators to export.'); return; }

      showOverlay(true);

      try{

        const sql = buildQuery({

          regions:getMulti(document.getElementById('selRegions')),

          countries:getMulti(document.getElementById('selCountries')),

          y1:document.getElementById('selY1').value,

          y2:document.getElementById('selY2').value,

          indicators

        });

        const rs = await State.conn.query(sql);

        const rows = rs.toArray();

        if(!rows.length){ alert('No rows to export for current filters.'); return; }



        const cols = Object.keys(rows[0]);

        const esc = s => { const v = asStr(s); return /[",\n]/.test(v) ? `"${v.replace(/"/g,'""')}"` : v; };

        const csv = [cols.join(','), ...rows.map(r => cols.map(c => esc(r[c])).join(','))].join('\n');

        const blob = new Blob([csv], {type:'text/csv;charset=utf-8;'});

        const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download=`bti_export_${Date.now()}.csv`; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);

      }catch(e){ console.error('Error exporting CSV:', e); alert('Export failed. See console.'); }

      finally{ showOverlay(false); }

    }



    document.getElementById('btnTheme').addEventListener('click', ()=> document.body.classList.toggle('dark-mode'));

    document.getElementById('btnAbout').addEventListener('click', ()=> document.getElementById('aboutDlg').showModal());

    document.getElementById('btnReset').addEventListener('click', ()=>{

      ['selIndicators','selRegions','selCountries'].forEach(id=>{ const sel=document.getElementById(id); Array.from(sel.options).forEach(o=>o.selected=false); });

      if(State.years.length){ document.getElementById('selY1').value=Math.min(...State.years); document.getElementById('selY2').value=Math.max(...State.years); }

      renderTable();

    });

    document.getElementById('btnExport').addEventListener('click', exportCSV);

    ['selIndicators','selRegions','selCountries','selY1','selY2'].forEach(id=> document.getElementById(id).addEventListener('change', renderTable));



    (async function boot(){

      await initDuckDB();

      await buildView();

      await populateFilters();

      initMap();

      renderTable();

    })();

  </script>
</body>
</html>