Spaces:
Running

File size: 21,414 Bytes
3de135f
 
 
 
 
929e2a6
3de135f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
929e2a6
 
3de135f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
929e2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3de135f
 
 
 
 
 
 
 
 
 
929e2a6
3de135f
 
 
 
 
 
 
 
 
 
 
 
 
 
929e2a6
3de135f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
929e2a6
 
3de135f
 
 
 
 
 
 
 
 
 
929e2a6
 
 
3de135f
 
 
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
import { I18N, LANGS } from './i18n.js';
import { MOON_I18N } from './i18n_moons.js';
import { CRAFT_I18N, CRAFT_ORDER, CRAFT_THEMES, CRAFT_INST, CRAFT_BACKDROP } from './i18n_craft.js';
import { createCraftViewer } from './craft.js';
import { createScene, PLANET_CFG, FEATURED_MOONS, moonData } from './scene.js';
import { moonFxKeys } from './moonfx.js';

// merge moon text into the main dictionary
const deepMerge = (a, b) => { for (const k in b) { if (b[k] && typeof b[k] === 'object' && !Array.isArray(b[k]) && a[k] && typeof a[k] === 'object') deepMerge(a[k], b[k]); else a[k] = b[k]; } return a; };
for (const extra of [MOON_I18N, CRAFT_I18N]) for (const l of Object.keys(extra)) deepMerge(I18N[l], extra[l]);
import { initAuroraGallery } from './aurora2d.js';

/* ------------------------------------------------------------ language */
const params = new URLSearchParams(location.search);
function detectLang() {
  if (LANGS.includes(params.get('lang'))) return params.get('lang');
  const saved = localStorage.getItem('mop-lang');
  if (LANGS.includes(saved)) return saved;
  const nav = (navigator.language || 'en').toLowerCase();
  if (nav.startsWith('zh')) return /tw|hk|mo|hant/.test(nav) ? 'zh-Hant' : 'zh-Hans';
  return 'en';
}
let lang = detectLang();

function t(key) {
  const get = (obj) => key.split('.').reduce((o, k) => (o == null ? undefined : o[k]), obj);
  const v = get(I18N[lang]);
  return v === undefined ? (get(I18N.en) ?? key) : v;
}
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));

/* -------------------------------------------------------------- 3D scene */
const PLANETS = ['earth', 'jupiter', 'saturn', 'uranus', 'neptune'];
let scene = null;
let selection = null;   // key of the moon shown in the info panel, or null for the planet
try {
  scene = createScene($('#stage'), {
    t,
    onPlanetChange: name => { selection = null; updateInfo(name); syncTabs(name); },
    onSelect: pick => { if (pick.type === 'moon') showMoon(pick.key); else { selection = null; updateInfo(); } }
  });
  scene.setPlanet(PLANETS.includes(params.get('planet')) ? params.get('planet') : 'jupiter', { instant: true });
} catch (err) {
  console.error(err);
  $('#stage').innerHTML = '<p class="noscript">WebGL is not available in this browser, so the 3D explorer cannot run. The rest of the page still works.</p>';
}

function syncTabs(name) { $$('#planetTabs button').forEach(b => b.classList.toggle('active', b.dataset.planet === name)); }

function updateInfo(name = scene?.planet || 'jupiter') {
  const p = `planets.${name}.`;
  $('#infoName').textContent = t(p + 'name');
  $('#infoTag').textContent = t(p + 'tag');
  $('#infoDesc').textContent = t(p + 'desc');
  $('#infoFacts').innerHTML = ['field', 'tilt', 'mp', 'source', 'rot', 'aurora', 'visited']
    .map(k => `<dt>${esc(t('info.' + k))}</dt><dd>${esc(t(p + k))}</dd>`).join('');
  const moons = PLANET_CFG[name].moons;
  $('#infoMoons').innerHTML = moons.length ? `<h3>${esc(t('nav.moons'))}</h3><div class="moon-chips">${moons.map(m =>
    `<button data-moon="${m.key}"><span class="chip-globe" style="background-image:url(textures/${m.key}.jpg)"></span>${esc(t('moons.' + m.key))}</button>`).join('')}</div><p class="note">${esc(t('mn.clickHint'))}</p>` : '';
  $$('#infoMoons [data-moon]').forEach(b => b.addEventListener('click', () => flyToMoon(b.dataset.moon, false)));
}

function moonName(key) { return I18N[lang].mo?.[key]?.full || t('moons.' + key); }
function moonFacts(key) {
  const m = moonData(key), host = PLANET_CFG[m.host];
  const retro = m.period < 0 ? (lang === 'en' ? ` (${t('mn.retro')})` : `(${t('mn.retro')}οΌ‰`) : '';
  const days = Math.abs(m.period).toLocaleString('en', { maximumFractionDigits: 2 }) + ' ' + t('mn.days') + retro;
  return [
    ['mn.host', t(`planets.${m.host}.name`)],
    ['mn.dia', m.dia.toLocaleString('en') + ' ' + t('mn.km')],
    ['mn.dist', fmtKm(Math.round(m.realDist * host.radiusKm / 100) * 100)],
    ['mn.period', days]
  ];
}
function showMoon(key) {
  selection = key;
  $('#infoTag').textContent = t(`mo.${key}.tag`);
  $('#infoName').textContent = moonName(key);
  $('#infoDesc').textContent = t(`mo.${key}.text`);
  $('#infoFacts').innerHTML = moonFacts(key).map(([k, v]) => `<dt>${esc(t(k))}</dt><dd>${esc(v)}</dd>`).join('');
  const fxk = moonFxKeys(key);
  $('#infoMoons').innerHTML = (fxk.length ? `<h3>${esc(t('mn.seeTitle'))}</h3><div class="fx-chips">${fxk.map(k => `<span>${esc(t('fx.' + k))}</span>`).join('')}</div>` : '') + `<div class="moon-actions"><button class="btn primary small" id="moonFly">${esc(t('mn.fly'))}</button><button class="btn ghost small" id="moonBack">${esc(t('mn.back'))}</button></div>`;
  $('#moonFly').addEventListener('click', () => scene?.focusMoon(key));
  $('#moonBack').addEventListener('click', () => { selection = null; updateInfo(); scene?.view('overview'); });
  document.body.classList.remove('touring');
}
function flyToMoon(key, scroll = true, instant = false) {
  if (!scene) return;
  const host = moonData(key).host;
  endTour();
  startExploring();
  if (scroll) $('#explore').scrollIntoView({ behavior: 'smooth' });
  if (scene.planet !== host) scene.setPlanet(host, { keepView: true });
  scene.setLayer('moons', true); syncLayerBoxes();
  scene.focusMoon(key, instant);
  showMoon(key);
}

function syncLayerBoxes() {
  if (!scene) return;
  const L = scene.getLayers();
  $$('[data-layer]').forEach(cb => { cb.checked = !!L[cb.dataset.layer]; });
}

$$('#planetTabs button').forEach(b => b.addEventListener('click', () => { endTour(); scene?.setPlanet(b.dataset.planet); }));
$$('[data-layer]').forEach(cb => cb.addEventListener('change', () => scene?.setLayer(cb.dataset.layer, cb.checked)));
$$('[data-view]').forEach(b => b.addEventListener('click', () => scene?.view(b.dataset.view)));
$('#speed').addEventListener('input', e => scene?.setSpeed(parseFloat(e.target.value)));
/* solar wind intensity: 1 = typical; values are relative dynamic pressure */
function windLevelKey(k) { return k < 0.7 ? 'ex.windCalm' : k < 1.5 ? 'ex.windNormal' : k < 2.6 ? 'ex.windStrong' : 'ex.windStorm'; }
function setWind(k, instant = false) {
  const sl = $('#windSlider');
  k = Math.min(parseFloat(sl.max), Math.max(parseFloat(sl.min), k));
  sl.value = k;
  scene?.setWind(k, instant);
  // the stream must be visible for the slider to make sense
  if (scene && !scene.getLayers().wind) { scene.setLayer('wind', true); syncLayerBoxes(); }
  renderWind();
}
function renderWind() {
  const k = parseFloat($('#windSlider').value);
  const lvl = windLevelKey(k);
  $('#windVal').textContent = `${t(lvl)} Β· Γ—${k.toFixed(1)}`;
  $('#windVal').dataset.level = lvl.slice(7).toLowerCase();
  $('#windCard').classList.toggle('storming', k >= 2.6);
}
/* hide / show all overlay menus so the 3D view is unobstructed (button or "H" key) */
function renderUiToggle() {
  const min = document.body.classList.contains('ui-min');
  $('#uiToggleTxt').textContent = t(min ? 'ex.showUi' : 'ex.hideUi');
  $('#uiToggle').setAttribute('aria-pressed', String(min));
  $('#uiToggle').title = t(min ? 'ex.showUi' : 'ex.hideUi') + ' (H)';
}
function toggleUi(force) {
  document.body.classList.toggle('ui-min', force);
  renderUiToggle();
}
$('#uiToggle').addEventListener('click', () => toggleUi());
document.addEventListener('keydown', e => {
  if (e.key !== 'h' && e.key !== 'H') return;
  if (e.ctrlKey || e.metaKey || e.altKey || /INPUT|TEXTAREA|SELECT/.test(document.activeElement?.tagName || '')) return;
  const r = $('#explore').getBoundingClientRect();
  if (r.bottom > 0 && r.top < innerHeight) toggleUi();
});
$('#windSlider').addEventListener('input', e => setWind(parseFloat(e.target.value)));
$('#windReset').addEventListener('click', () => setWind(1));
$('#cmeBtn').addEventListener('click', () => {
  if (!scene) return;
  if (!scene.getLayers().wind) { scene.setLayer('wind', true); syncLayerBoxes(); }
  if (!scene.getLayers().mp) { scene.setLayer('mp', true); syncLayerBoxes(); }
  scene.launchCME();
});
// Typical magnetopause stand-off distance in planetary radii; it scales as (pressure)^(-1/6).
const REAL_MP = { earth: 10, jupiter: 63, saturn: 22, uranus: 18, neptune: 26 };
let meterT = 0;
function updateMeters(now) {
  requestAnimationFrame(updateMeters);
  if (!scene || now - meterT < 150) return;
  meterT = now;
  const w = scene.windInfo();
  const mp = (REAL_MP[scene.planet] || 10) * Math.pow(w.k, -1 / 6);
  $('#mpVal').textContent = t('ex.mRadii').replace('{n}', mp >= 30 ? Math.round(mp) : mp.toFixed(1));
  $('#mpBar').style.width = `${Math.min(100, 100 * Math.pow(w.k, -1 / 6) / 1.25)}%`;
  $('#auVal').textContent = `Γ—${w.boost.toFixed(1)}`;
  $('#auBar').style.width = `${Math.min(100, 100 * w.boost / 2.6)}%`;
  const card = $('#windCard');
  card.classList.toggle('cme', w.cme && w.kick === 0);
  card.classList.toggle('impact', w.kick > 0.05);
  $('#cmeBtn').disabled = w.cme;
}
requestAnimationFrame(updateMeters);

function startExploring() { document.body.classList.add('exploring'); }
$('#startBtn').addEventListener('click', startExploring);

/* ----------------------------------------------------------------- tour */
const ALL_ON = { field: true, wind: true, mp: true, aurora: true, torus: true, moons: true, labels: true };
const TOUR = [
  { planet: 'jupiter', view: 'close', layers: { field: true, wind: false, mp: false, aurora: false, torus: false, moons: false, labels: true } },
  { planet: 'jupiter', view: 'overview', layers: { field: true, wind: true, mp: false, aurora: false, torus: false, moons: false, labels: true } },
  { planet: 'jupiter', view: 'overview', layers: { field: true, wind: true, mp: true, aurora: false, torus: false, moons: false, labels: true } },
  { planet: 'jupiter', view: 'mid', moon: 'io', layers: { field: true, wind: false, mp: false, aurora: true, torus: true, moons: true, labels: true } },
  { planet: 'jupiter', view: 'aurora', layers: { ...ALL_ON, wind: false, mp: false } },
  { planet: 'uranus', view: 'overview', layers: { ...ALL_ON } }
];
let tourIdx = -1;

function showStep(i) {
  if (!scene) return;
  tourIdx = Math.max(0, Math.min(TOUR.length - 1, i));
  const s = TOUR[tourIdx];
  startExploring();
  document.body.classList.add('touring');
  if (scene.planet !== s.planet) scene.setPlanet(s.planet, { keepView: true });
  scene.setLayers(s.layers);
  scene.view(s.view);
  if (s.moon) scene.focusMoon(s.moon);
  syncLayerBoxes();
  $('#tour').hidden = false;
  renderTourText();
}
function renderTourText() {
  if (tourIdx < 0) return;
  const step = t('how.steps')[tourIdx];
  $('#tourStep').textContent = t('ex.stepFmt').replace('{i}', tourIdx + 1).replace('{n}', TOUR.length);
  $('#tourTitle').textContent = step.title;
  $('#tourText').textContent = step.text;
  $('#tourPrev').disabled = tourIdx === 0;
  $('#tourNext').disabled = tourIdx === TOUR.length - 1;
}
function endTour() {
  if (tourIdx < 0) return;
  tourIdx = -1;
  $('#tour').hidden = true;
  document.body.classList.remove('touring');
  scene?.setLayers(ALL_ON);
  syncLayerBoxes();
}
$('#tourBtn').addEventListener('click', () => showStep(0));
$('#tourPrev').addEventListener('click', () => showStep(tourIdx - 1));
$('#tourNext').addEventListener('click', () => showStep(tourIdx + 1));
$('#tourExit').addEventListener('click', endTour);

/* ------------------------------------------------------ dynamic sections */
const STEP_ICONS = ['🧲', 'β˜€οΈ', '🌊', 'πŸŒ‹', '🌌', 'πŸŒ€'];
function renderSteps() {
  $('#stepsGrid').innerHTML = t('how.steps').map((s, i) => `
    <article class="step-card">
      <div class="step-num">${STEP_ICONS[i]}<span>${i + 1}</span></div>
      <h3>${esc(s.title)}</h3>
      <p>${esc(s.text)}</p>
      <button class="btn ghost small" data-step="${i}">${esc(t('how.see'))} β†’</button>
    </article>`).join('');
  $$('#stepsGrid [data-step]').forEach(b => b.addEventListener('click', () => {
    $('#explore').scrollIntoView({ behavior: 'smooth' });
    showStep(parseInt(b.dataset.step, 10));
  }));
}

const SIZES = [
  { key: 'earth', km: 64000, color: '#4fa3ff' },
  { key: 'jupiter', km: 4500000, color: '#e0b27a' },
  { key: 'saturn', km: 1300000, color: '#e8d08f' },
  { key: 'uranus', km: 460000, color: '#8fe3ea' },
  { key: 'neptune', km: 600000, color: '#5d7fff' },
  { key: 'sun', km: 1392000, color: '#ffcc55' }
];
function fmtKm(km) {
  if (lang === 'en') return km >= 1e6 ? `${(km / 1e6).toLocaleString('en', { maximumFractionDigits: 2 })} million km` : `${km.toLocaleString('en')} km`;
  const wan = lang === 'zh-Hans' ? 'δΈ‡' : '萬';
  return km >= 1e4 ? `${(km / 1e4).toLocaleString('en', { maximumFractionDigits: 1 })} ${wan}ε…¬ι‡Œ` : `${km.toLocaleString('en')} ε…¬ι‡Œ`;
}
function renderBars() {
  const max = Math.max(...SIZES.map(s => s.km));
  $('#bars').innerHTML = SIZES.map(s => {
    const name = s.key === 'sun' ? t('cmp.sun') : t(`planets.${s.key}.name`);
    const w = Math.max(0.6, (s.km / max) * 100);
    return `<div class="bar-row${s.key === 'sun' ? ' sun' : ''}">
      <span class="bar-name">${esc(name)}</span>
      <div class="bar-track"><div class="bar" style="--w:${w}%;--c:${s.color}"></div></div>
      <span class="bar-val">${esc(fmtKm(s.km))}</span>
    </div>`;
  }).join('');
  const io = new IntersectionObserver(es => es.forEach(e => e.isIntersecting && e.target.classList.add('grow')), { threshold: 0.3 });
  io.observe($('#bars'));
}
function renderTable() {
  const cols = ['field', 'tilt', 'mp', 'rot', 'source'];
  $('#cmpTable').innerHTML = `<thead><tr><th>${esc(t('cmp.planet'))}</th>${cols.map(c => `<th>${esc(t('info.' + c))}</th>`).join('')}</tr></thead>
    <tbody>${PLANETS.map(p => `<tr><th>${esc(t(`planets.${p}.name`))}</th>${cols.map(c => `<td>${esc(t(`planets.${p}.${c}`))}</td>`).join('')}</tr>`).join('')}</tbody>`;
}
function renderMoons() {
  $('#moonGrid').innerHTML = FEATURED_MOONS.map(k => `
    <article class="moon-card">
      <div class="globe" style="background-image:url(textures/${k}.jpg)"></div>
      <div class="moon-body">
        <p class="tag">${esc(t(`planets.${moonData(k).host}.name`))} Β· ${esc(t(`mo.${k}.tag`))}</p>
        <h3>${esc(moonName(k))}</h3>
        <p>${esc(t(`mo.${k}.text`))}</p>
        <dl class="moon-facts">${moonFacts(k).slice(1).map(([a, v]) => `<div><dt>${esc(t(a))}</dt><dd>${esc(v)}</dd></div>`).join('')}</dl>
        <button class="btn ghost small" data-fly="${k}">${esc(t('mn.fly'))} β†’</button>
      </div>
    </article>`).join('');
  $$('#moonGrid [data-fly]').forEach(b => b.addEventListener('click', () => flyToMoon(b.dataset.fly)));
}
/* ------------------------------------------------------------ spacecraft */
const craft = { key: 'juno', theme: 0, inst: null, viewer: null };
const pad2 = n => String(n).padStart(2, '0');
function craftMatches(key) { return !craft.theme || CRAFT_THEMES[key].includes(craft.theme); }
function renderThemes() {
  const themes = t('themes');
  $('#themeChips').innerHTML = `<button data-theme="0" class="${craft.theme ? '' : 'active'}">${esc(t('sc.all'))}</button>` +
    themes.map((th, i) => `<button data-theme="${i + 1}" class="${craft.theme === i + 1 ? 'active' : ''}"><b>${pad2(i + 1)}</b> ${esc(th.title)}</button>`).join('');
  $('#themeDesc').textContent = craft.theme ? themes[craft.theme - 1].text : '';
  $$('#themeChips [data-theme]').forEach(b => b.addEventListener('click', () => setTheme(+b.dataset.theme)));
}
function setTheme(n) {
  craft.theme = n;
  renderThemes();
  if (!craftMatches(craft.key)) showCraft(CRAFT_ORDER.find(craftMatches));
  else renderPicker();
}
function renderPicker() {
  $('#craftPicker').innerHTML = CRAFT_ORDER.map(k => `
    <button data-craft="${k}" class="${k === craft.key ? 'active' : ''} ${craftMatches(k) ? '' : 'dim'}">
      <span class="cp-name">${esc(t(`crafts.${k}.name`))}</span><span class="cp-years">${esc(t(`crafts.${k}.years`))}</span>
    </button>`).join('');
  $$('#craftPicker [data-craft]').forEach(b => b.addEventListener('click', () => showCraft(b.dataset.craft)));
}
function renderCraftInfo() {
  const k = craft.key, c = `crafts.${k}.`;
  const insts = CRAFT_INST[k];
  $('#craftInfo').innerHTML = `
    <p class="tag">${esc(t(c + 'agency'))}</p>
    <h3 class="craft-name">${esc(t(c + 'name'))}</h3>
    <p>${esc(t(c + 'desc'))}</p>
    <dl class="craft-facts">
      <div><dt>${esc(t('sc.years'))}</dt><dd>${esc(t(c + 'years'))}</dd></div>
      <div><dt>${esc(t('sc.target'))}</dt><dd>${esc(t(c + 'target'))}</dd></div>
      <div><dt>${esc(t('sc.status'))}</dt><dd>${esc(t(c + 'status'))}</dd></div>
    </dl>
    <h4>${esc(t('sc.mopThemes'))}</h4>
    <div class="theme-badges">${CRAFT_THEMES[k].map(n => `<button data-theme="${n}">${pad2(n)} Β· ${esc(t('themes')[n - 1].title)}</button>`).join('')}</div>
    <h4>${esc(t('sc.instruments'))}</h4>
    <ol class="inst-list">${insts.map((id, i) => {
      const on = craft.inst === id;
      return `<li class="${on ? 'open' : ''}"><button data-inst="${id}"><span class="num">${i + 1}</span>${esc(t(c + 'inst.' + id + '.name'))}</button>${on ? `<p>${esc(t(c + 'inst.' + id + '.text'))}</p>` : ''}</li>`;
    }).join('')}</ol>
    <h4>${esc(t('sc.saw'))}</h4>
    <ul class="saw-list">${t(c + 'saw').map(s => `<li>${esc(s)}</li>`).join('')}</ul>`;
  $$('#craftInfo [data-inst]').forEach(b => b.addEventListener('click', () => pickInst(b.dataset.inst === craft.inst ? null : b.dataset.inst)));
  $$('#craftInfo [data-theme]').forEach(b => b.addEventListener('click', () => setTheme(+b.dataset.theme)));
}
function pickInst(id) {
  craft.inst = id;
  craft.viewer?.select(id);
  renderCraftInfo();
}
function showCraft(key) {
  craft.key = key; craft.inst = null;
  renderPicker(); renderCraftInfo();
  craft.viewer?.show(key, CRAFT_INST[key]);
}
try {
  craft.viewer = createCraftViewer($('#craftStage'), { onPick: id => pickInst(id), backdrop: k => CRAFT_BACKDROP[k] });
  craft.viewer.show(craft.key, CRAFT_INST[craft.key]);
} catch (err) { console.error(err); }

function renderWhy() {
  $('#whyGrid').innerHTML = t('why.cards').map(c => `
    <article class="why-card"><div class="why-icon">${c.icon}</div><h3>${esc(c.title)}</h3><p>${esc(c.text)}</p></article>`).join('');
}
function renderTimeline() {
  $('#timeline').innerHTML = t('ms.items').map(m => `
    <li><span class="tl-year">${esc(m.year)}</span><div class="tl-body"><h3>${esc(m.name)}</h3><p>${esc(m.text)}</p></div></li>`).join('');
}

/* ----------------------------------------------------------------- quiz */
let answers = {};
function renderQuiz() {
  const items = t('qz.items');
  $('#quizBox').innerHTML = items.map((q, qi) => {
    const done = answers[qi] !== undefined;
    return `<div class="q${done ? ' done' : ''}">
      <p class="q-text"><span>${qi + 1}.</span> ${esc(q.q)}</p>
      <div class="q-opts">${q.options.map((o, oi) => {
        let cls = '';
        if (done) { if (oi === q.answer) cls = 'right'; else if (oi === answers[qi]) cls = 'wrong'; }
        return `<button class="${cls}" data-q="${qi}" data-o="${oi}" ${done ? 'disabled' : ''}>${esc(o)}</button>`;
      }).join('')}</div>
      ${done ? `<p class="q-explain"><strong>${esc(answers[qi] === q.answer ? t('qz.correct') : t('qz.wrong'))}</strong> ${esc(q.explain)}</p>` : ''}
    </div>`;
  }).join('');
  const score = Object.entries(answers).filter(([qi, o]) => items[qi].answer === o).length;
  $('#quizScore').textContent = `${t('qz.score')}: ${score} / ${items.length}`;
  $$('#quizBox button[data-q]').forEach(b => b.addEventListener('click', () => {
    answers[+b.dataset.q] = +b.dataset.o;
    renderQuiz();
  }));
}
$('#quizReset').addEventListener('click', () => { answers = {}; renderQuiz(); });

/* ------------------------------------------------------------ apply lang */
function applyLang(l) {
  lang = l;
  localStorage.setItem('mop-lang', l);
  document.documentElement.lang = l;
  document.title = t('meta.title');
  $$('[data-i18n]').forEach(el => { el.textContent = t(el.dataset.i18n); });
  $$('.lang button').forEach(b => b.classList.toggle('active', b.dataset.lang === l));
  renderSteps(); renderMoons(); renderThemes(); renderPicker(); renderCraftInfo(); renderBars(); renderTable(); renderWhy(); renderTimeline(); renderQuiz();
  if (scene) { selection ? showMoon(selection) : updateInfo(); scene.refreshLabels(); }
  renderTourText();
  renderWind();
  renderUiToggle();
}
$$('.lang button').forEach(b => b.addEventListener('click', () => applyLang(b.dataset.lang)));

$('#menuBtn').addEventListener('click', () => document.body.classList.toggle('menu-open'));
$$('#nav a').forEach(a => a.addEventListener('click', () => document.body.classList.remove('menu-open')));

applyLang(lang);
initAuroraGallery();
if (params.has('explore')) startExploring();
if (params.get('view')) scene?.view(params.get('view'), true);
if (params.has('wind')) setWind(parseFloat(params.get('wind')) || 1, true);
if (params.has('clean')) toggleUi(true);
if (params.has('cme')) scene?.launchCME(parseFloat(params.get('cme')) || 0);
if (params.has('tour')) showStep(parseInt(params.get('tour'), 10) || 0);
if (CRAFT_ORDER.includes(params.get('craft'))) showCraft(params.get('craft'));
if (params.get('moon') && moonData(params.get('moon'))) flyToMoon(params.get('moon'), false, true);