Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
512 lines (465 loc) · 28.9 KB
/
Copy pathapp.js
File metadata and controls
512 lines (465 loc) · 28.9 KB
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
const MAP_W = 1200;
const MAP_H = 580;
const canvas = document.getElementById('climateCanvas');
const ctx = canvas.getContext('2d');
const boundaryCanvas = document.getElementById('boundaryCanvas');
const boundaryCtx = boundaryCanvas.getContext('2d');
const mapCard = document.getElementById('mapCard');
const hoverTip = document.getElementById('hoverTip');
const selectionBox = document.getElementById('selectionBox');
const now = new Date();
const state = {
layer: 'temperature',
utcHour: now.getUTCHours() + now.getUTCMinutes() / 60,
view: { west: -180, east: 180, south: -90, north: 90 },
selected: { name: 'Tibetan Plateau', lat: 31.2, lon: 87.5 },
features: [],
landMask: null,
live: null,
selectMode: false,
illuminationOverlay: true,
infoPanelVisible: true,
range: { min: -30, max: 40 }
};
const layers = {
temperature: {
title: 'Surface temperature', kicker: 'Temperature layer', unit: '°C', fallback: [-30, 40],
name: 'Temperature', global: '14.8', description: 'Modeled global mean surface temperature',
trend: '+1.1°C', trendText: 'warming since pre-industrial levels',
gradient: 'linear-gradient(90deg,#243c78,#2f88ad,#67c0a6,#f3dc77,#f49a4d,#d94833,#7c1830)',
colors: [[25,42,91],[42,123,163],[82,183,166],[242,220,116],[240,141,67],[201,54,43],[104,22,49]]
},
humidity: {
title: 'Relative humidity', kicker: 'Humidity layer', unit: '%', fallback: [10, 100],
name: 'Relative humidity', global: '72', description: 'Modeled global mean relative humidity',
trend: 'Live', trendText: 'humidity at selected locations',
gradient: 'linear-gradient(90deg,#e9d6a2,#beb36d,#75a17a,#3e8990,#28617a,#172d56)',
colors: [[235,216,165],[184,177,105],[102,158,119],[50,132,142],[34,91,120],[20,39,77]]
},
elevation: {
title: 'Terrain elevation', kicker: 'Elevation layer', unit: 'm', fallback: [-4000, 6000],
name: 'Elevation', global: '840', description: 'Mean elevation of Earth’s land',
trend: 'Static', trendText: 'geographic reference model',
gradient: 'linear-gradient(90deg,#355d76,#8db7b1,#d0cf94,#aa9562,#74533b,#efede4)',
colors: [[48,91,118],[133,181,174],[205,204,145],[167,144,91],[111,79,55],[239,237,228]]
},
illumination: {
title: 'Incoming solar illumination', kicker: 'Illumination layer', unit: ' W/m²', fallback: [0, 1361],
name: 'Solar irradiance', global: '340', description: 'Mean incoming solar energy across Earth',
trend: 'Live model', trendText: 'based on current date and scene time',
gradient: 'linear-gradient(90deg,#071522,#143a56,#286e88,#67a9a0,#d9c76e,#fff1a2)',
colors: [[7,21,34],[17,53,79],[35,103,129],[90,160,154],[210,190,99],[255,242,169]]
}
};
const cities = [
{ name: 'Reykjavík, Iceland', lat: 64.15, lon: -21.94 },
{ name: 'New York, United States', lat: 40.71, lon: -74.01 },
{ name: 'São Paulo, Brazil', lat: -23.55, lon: -46.63 },
{ name: 'Nairobi, Kenya', lat: -1.29, lon: 36.82 },
{ name: 'Cape Town, South Africa', lat: -33.92, lon: 18.42 },
{ name: 'London, United Kingdom', lat: 51.51, lon: -0.13 },
{ name: 'Cairo, Egypt', lat: 30.04, lon: 31.24 },
{ name: 'Mumbai, India', lat: 19.08, lon: 72.88 },
{ name: 'Tibetan Plateau', lat: 31.2, lon: 87.5 },
{ name: 'Beijing, China', lat: 39.9, lon: 116.41 },
{ name: 'Tokyo, Japan', lat: 35.68, lon: 139.69 },
{ name: 'Singapore', lat: 1.35, lon: 103.82 },
{ name: 'Sydney, Australia', lat: -33.87, lon: 151.21 },
{ name: 'Antarctic Plateau', lat: -80.2, lon: 25.0 }
];
const mapLabels = [
['CANADA', 57, -107], ['UNITED STATES', 39, -100], ['BRAZIL', -11, -52],
['ARGENTINA', -38, -64], ['GREENLAND', 72, -41], ['RUSSIA', 60, 88],
['CHINA', 36, 104], ['INDIA', 22, 79], ['AUSTRALIA', -25, 134],
['SOUTH AFRICA', -30, 24], ['ALGERIA', 28, 2], ['D.R. CONGO', -3, 23]
];
function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); }
function smoothstep(a, b, value) { const t = clamp((value-a)/(b-a), 0, 1); return t*t*(3-2*t); }
function project(lat, lon) {
const { west, east, south, north } = state.view;
return { x: (lon-west)/(east-west)*MAP_W, y: (north-lat)/(north-south)*MAP_H };
}
function unproject(x, y) {
const { west, east, south, north } = state.view;
return { lon: west+(x/MAP_W)*(east-west), lat: north-(y/MAP_H)*(north-south) };
}
function screenPoint(event) {
const r = mapCard.getBoundingClientRect();
return {
sx: clamp(event.clientX-r.left, 0, r.width), sy: clamp(event.clientY-r.top, 0, r.height),
x: clamp((event.clientX-r.left)/r.width*MAP_W, 0, MAP_W),
y: clamp((event.clientY-r.top)/r.height*MAP_H, 0, MAP_H), rect: r
};
}
function gaussian(lat, lon, clat, clon, spread) {
const dlon = Math.min(Math.abs(lon-clon), 360-Math.abs(lon-clon));
const d = (lat-clat)**2 + (dlon*Math.cos(clat*Math.PI/180))**2;
return Math.exp(-d/spread);
}
function landAt(lat, lon) {
if (!state.landMask) return Math.abs(lat) > 75;
const x = clamp(Math.floor((lon+180)/360*720), 0, 719);
const y = clamp(Math.floor((90-lat)/180*360), 0, 359);
return state.landMask[(y*720+x)*4+3] > 0;
}
function elevationAt(lat, lon, land) {
if (!land) return -3400 + 700*Math.sin(lon*.06)*Math.cos(lat*.09);
let e = 180 + 360*Math.abs(Math.sin(lon*.075+lat*.04));
e += 4700*gaussian(lat,lon,31,85,230);
e += 3000*gaussian(lat,lon,-18,-70,180);
e += 2100*gaussian(lat,lon,39,-111,330);
e += 1700*gaussian(lat,lon,46,10,60);
e += 1750*gaussian(lat,lon,9,39,100);
e += 1300*gaussian(lat,lon,-29,28,95);
return Math.max(0, e);
}
function solarElevation(lat, lon, hour = state.utcHour) {
const date = new Date();
const start = Date.UTC(date.getUTCFullYear(), 0, 0);
const day = Math.floor((Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate())-start)/86400000);
const decl = -23.44*Math.cos((2*Math.PI/365)*(day+10));
const hourAngle = ((hour+lon/15)-12)*15;
const phi=lat*Math.PI/180, delta=decl*Math.PI/180, h=hourAngle*Math.PI/180;
return Math.asin(Math.sin(phi)*Math.sin(delta)+Math.cos(phi)*Math.cos(delta)*Math.cos(h))*180/Math.PI;
}
function temperatureAt(lat, lon, land) {
let value = 29-Math.pow(Math.abs(lat)/90,1.25)*64;
value += Math.sin(lon*.07+lat*.03)*2.3;
if (land) value -= Math.max(0,elevationAt(lat,lon,land))*.0058;
else value += 2.5;
const daylight = smoothstep(-8,35,solarElevation(lat,lon));
value += (daylight-.46)*(land ? 7.5 : 2.2);
return value;
}
function humidityAt(lat, lon, land) {
const a=Math.abs(lat);
let value=42+35*Math.exp(-(lat*lat)/520)+18*Math.exp(-((a-52)**2)/190)-25*Math.exp(-((a-27)**2)/90);
value += 22*gaussian(lat,lon,-5,-62,420)+20*gaussian(lat,lon,3,110,320)+15*gaussian(lat,lon,22,91,230);
value -= 22*gaussian(lat,lon,25,18,480)+18*gaussian(lat,lon,-25,134,420);
value += 7*Math.sin(lon*.09+lat*.11);
value += (0.5-smoothstep(-6,30,solarElevation(lat,lon)))*9;
if (!land) value += 9;
return clamp(value,6,100);
}
function illuminationAt(lat, lon) {
const altitude=solarElevation(lat,lon)*Math.PI/180;
return 1361*Math.max(0,Math.sin(altitude));
}
function valueAt(layer, lat, lon) {
const land=landAt(lat,lon);
if(layer==='temperature') return temperatureAt(lat,lon,land);
if(layer==='humidity') return humidityAt(lat,lon,land);
if(layer==='illumination') return illuminationAt(lat,lon);
return elevationAt(lat,lon,land);
}
function mixColor(stops, amount) {
const t=clamp(amount,0,.999), scaled=t*(stops.length-1), i=Math.floor(scaled), f=scaled-i;
return stops[i].map((v,k)=>Math.round(v+(stops[i+1][k]-v)*f));
}
function computeViewRange() {
const values=[];
for(let y=0;y<22;y++) for(let x=0;x<44;x++) {
const geo=unproject((x+.5)/44*MAP_W,(y+.5)/22*MAP_H);
values.push(valueAt(state.layer,geo.lat,geo.lon));
}
values.sort((a,b)=>a-b);
let min=values[Math.floor(values.length*.04)], max=values[Math.floor(values.length*.96)];
if(state.layer==='humidity'){min=Math.max(0,Math.floor(min/5)*5);max=Math.min(100,Math.ceil(max/5)*5);}
if(state.layer==='temperature'){min=Math.floor(min/5)*5;max=Math.ceil(max/5)*5;}
if(state.layer==='elevation'){min=Math.floor(min/500)*500;max=Math.ceil(max/500)*500;}
if(state.layer==='illumination'){min=Math.max(0,Math.floor(min/100)*100);max=Math.min(1400,Math.max(100,Math.ceil(max/100)*100));}
if(max-min<1) max=min+1;
state.range={min,max};
}
function drawMap() {
computeViewRange();
const width=420,height=203,off=document.createElement('canvas');
off.width=width; off.height=height;
const octx=off.getContext('2d'),image=octx.createImageData(width,height),config=layers[state.layer];
for(let y=0;y<height;y++) for(let x=0;x<width;x++) {
const geo=unproject((x+.5)/width*MAP_W,(y+.5)/height*MAP_H);
const value=valueAt(state.layer,geo.lat,geo.lon);
const t=(value-state.range.min)/(state.range.max-state.range.min);
const color=mixColor(config.colors,t);
const sun=solarElevation(geo.lat,geo.lon);
const useShade=state.illuminationOverlay&&state.layer!=='illumination';
const light=useShade ? .3+.7*smoothstep(-12,8,sun) : 1;
const night=1-light;
const i=(y*width+x)*4;
image.data[i]=color[0]*light+8*night;
image.data[i+1]=color[1]*light+24*night;
image.data[i+2]=color[2]*light+43*night;
image.data[i+3]=255;
}
octx.putImageData(image,0,0);
ctx.clearRect(0,0,MAP_W,MAP_H);
ctx.imageSmoothingEnabled=true;
ctx.drawImage(off,0,0,MAP_W,MAP_H);
const vignette=ctx.createRadialGradient(600,275,140,600,275,720);
vignette.addColorStop(0,'rgba(255,255,255,.015)');vignette.addColorStop(1,'rgba(5,22,30,.14)');
ctx.fillStyle=vignette;ctx.fillRect(0,0,MAP_W,MAP_H);
updateLegend();
}
function traceRing(context,ring,projection=project) {
let previous=null,started=false;
ring.forEach(([lon,lat])=>{
const p=projection(lat,lon);
if(!started||previous&&Math.abs(p.x-previous.x)>MAP_W*.55){context.moveTo(p.x,p.y);started=true;}
else context.lineTo(p.x,p.y);
previous=p;
});
}
function traceGeometry(context,geometry,projection=project) {
if(!geometry) return;
const polygons=geometry.type==='Polygon'?[geometry.coordinates]:geometry.type==='MultiPolygon'?geometry.coordinates:[];
polygons.forEach(polygon=>polygon.forEach(ring=>{traceRing(context,ring,projection);context.closePath();}));
}
function drawBoundaries() {
boundaryCtx.clearRect(0,0,MAP_W,MAP_H);
boundaryCtx.save();
boundaryCtx.strokeStyle='rgba(255,255,255,.19)';boundaryCtx.lineWidth=.7;boundaryCtx.setLineDash([2,6]);
const lonStep=(state.view.east-state.view.west)>100?30:((state.view.east-state.view.west)>30?10:5);
const latStep=(state.view.north-state.view.south)>70?30:((state.view.north-state.view.south)>25?10:5);
for(let lon=Math.ceil(state.view.west/lonStep)*lonStep;lon<state.view.east;lon+=lonStep){const p=project(0,lon);boundaryCtx.beginPath();boundaryCtx.moveTo(p.x,0);boundaryCtx.lineTo(p.x,MAP_H);boundaryCtx.stroke();}
for(let lat=Math.ceil(state.view.south/latStep)*latStep;lat<state.view.north;lat+=latStep){const p=project(lat,0);boundaryCtx.beginPath();boundaryCtx.moveTo(0,p.y);boundaryCtx.lineTo(MAP_W,p.y);boundaryCtx.stroke();}
boundaryCtx.setLineDash([]);
boundaryCtx.beginPath();state.features.forEach(f=>traceGeometry(boundaryCtx,f.geometry));
boundaryCtx.fillStyle='rgba(255,255,255,.035)';boundaryCtx.fill('evenodd');
boundaryCtx.strokeStyle='rgba(250,251,242,.78)';boundaryCtx.lineWidth=(state.view.east-state.view.west)<80?1.3:.72;boundaryCtx.stroke();
boundaryCtx.strokeStyle='rgba(7,29,36,.38)';boundaryCtx.lineWidth=.35;boundaryCtx.stroke();
boundaryCtx.font='600 8px DM Sans, sans-serif';boundaryCtx.textAlign='center';boundaryCtx.textBaseline='middle';boundaryCtx.fillStyle='rgba(255,255,255,.62)';
mapLabels.forEach(([label,lat,lon])=>{if(lon>state.view.west&&lon<state.view.east&&lat>state.view.south&&lat<state.view.north){const p=project(lat,lon);boundaryCtx.fillText(label,p.x,p.y);}});
boundaryCtx.restore();
}
function buildLandMask() {
const mask=document.createElement('canvas');mask.width=720;mask.height=360;
const mctx=mask.getContext('2d');
const globalProject=(lat,lon)=>({x:(lon+180)/360*720,y:(90-lat)/180*360});
mctx.beginPath();state.features.forEach(f=>traceGeometry(mctx,f.geometry,globalProject));
mctx.fillStyle='#fff';mctx.fill('evenodd');
state.landMask=mctx.getImageData(0,0,720,360).data;
}
async function loadGeography() {
try {
let data=window.COUNTRIES_GEOJSON;
if(!data){
const response=await fetch('data/countries.geojson');
if(!response.ok) throw new Error(`Boundary request failed: ${response.status}`);
data=await response.json();
}
state.features=data.features||[];buildLandMask();updateUI();
} catch(error) {
console.warn(error);document.getElementById('weatherStatus').textContent='Boundary file unavailable';
}
}
function formatValue(value,layer=state.layer) {
if(layer==='temperature') return `${value<0?'−':''}${Math.abs(value).toFixed(1)}`;
return Math.round(value).toLocaleString();
}
function formatLegend(value) {
const unit=layers[state.layer].unit;
return `${value<0?'−':''}${Math.abs(Math.round(value)).toLocaleString()}${unit}`;
}
function updateLegend() {
document.getElementById('legendLow').textContent=formatLegend(state.range.min);
document.getElementById('legendHigh').textContent=formatLegend(state.range.max);
}
function pointInRing(lon,lat,ring) {
let inside=false;
for(let i=0,j=ring.length-1;i<ring.length;j=i++){
const xi=ring[i][0],yi=ring[i][1],xj=ring[j][0],yj=ring[j][1];
if(((yi>lat)!==(yj>lat))&&(lon<(xj-xi)*(lat-yi)/(yj-yi)+xi))inside=!inside;
}
return inside;
}
function countryAt(lat,lon) {
for(const feature of state.features){
const g=feature.geometry;if(!g)continue;
const polygons=g.type==='Polygon'?[g.coordinates]:g.type==='MultiPolygon'?g.coordinates:[];
if(polygons.some(poly=>pointInRing(lon,lat,poly[0])&&!poly.slice(1).some(hole=>pointInRing(lon,lat,hole))))return feature.properties?.name||'Selected location';
}
return 'Ocean point';
}
function localTimeFallback(lon) {
const base=state.utcHour+lon/15;
const h=(base%24+24)%24,m=Math.round((h%1)*60)%60;
return `${String(Math.floor(h)).padStart(2,'0')}:${String(m).padStart(2,'0')} solar`;
}
function displayLocalTime() {
const el=document.getElementById('localTime');
if(state.live?.timezone){
try { el.textContent=new Intl.DateTimeFormat([], {timeZone:state.live.timezone,hour:'2-digit',minute:'2-digit',hour12:false}).format(new Date());return; } catch(_) {}
}
el.textContent=localTimeFallback(state.selected.lon);
}
function selectedDisplayValue() {
if(state.live&&state.layer==='temperature'&&Number.isFinite(state.live.temperature_2m)) return state.live.temperature_2m;
if(state.live&&state.layer==='humidity'&&Number.isFinite(state.live.relative_humidity_2m)) return state.live.relative_humidity_2m;
return valueAt(state.layer,state.selected.lat,state.selected.lon);
}
function updateSelected() {
const p=state.selected,config=layers[state.layer],value=selectedDisplayValue();
document.getElementById('locationName').textContent=p.name;
document.getElementById('locationCoords').textContent=`${Math.abs(p.lat).toFixed(2)}°${p.lat>=0?'N':'S'}, ${Math.abs(p.lon).toFixed(2)}°${p.lon>=0?'E':'W'}`;
document.getElementById('locationValue').textContent=formatValue(value);
document.getElementById('locationUnit').textContent=config.unit;
const global={temperature:14.8,humidity:72,elevation:840,illumination:340}[state.layer],delta=value-global;
const context=state.layer==='temperature'?`${delta<0?'Cooler':'Warmer'} than global mean`:state.layer==='humidity'?`${delta<0?'Drier':'More humid'} than global mean`:state.layer==='illumination'?`${delta<0?'Below':'Above'} planetary mean`:`${delta<0?'Below':'Above'} mean land height`;
document.getElementById('locationContext').textContent=context;
document.getElementById('locationDelta').textContent=`${delta>=0?'+':'−'}${formatValue(Math.abs(delta))}${state.layer==='temperature'?'°':''}`;
document.getElementById('locationCard').hidden=!state.infoPanelVisible;
displayLocalTime();
}
function updateDetailsToggle() {
const button=document.getElementById('detailsToggle');
button.classList.toggle('active',state.infoPanelVisible);
button.setAttribute('aria-pressed',String(state.infoPanelVisible));
button.querySelector('span').textContent=state.infoPanelVisible?'Details on':'Details off';
}
let weatherAbort=null;
async function fetchWeather() {
if(weatherAbort)weatherAbort.abort();
const controller=new AbortController();weatherAbort=controller;
const source=document.querySelector('.weather-source'),status=document.getElementById('weatherStatus');
source.classList.remove('error');status.textContent='Fetching Open‑Meteo…';
['liveHumidity','liveRain','liveCloud'].forEach(id=>document.getElementById(id).textContent='—');
const {lat,lon}=state.selected;
const params=new URLSearchParams({latitude:lat.toFixed(4),longitude:lon.toFixed(4),current:'temperature_2m,relative_humidity_2m,precipitation,cloud_cover,wind_speed_10m',timezone:'auto',forecast_days:'1'});
const timeout=setTimeout(()=>weatherAbort.abort(),9000);
try {
const response=await fetch(`https://api.open-meteo.com/v1/forecast?${params}`,{signal:controller.signal});
if(!response.ok)throw new Error(`HTTP ${response.status}`);
const data=await response.json();state.live={...data.current,timezone:data.timezone,timezone_abbreviation:data.timezone_abbreviation};
document.getElementById('liveHumidity').textContent=`${Math.round(state.live.relative_humidity_2m)}%`;
document.getElementById('liveRain').textContent=`${state.live.precipitation.toFixed(1)} mm`;
document.getElementById('liveCloud').textContent=`${Math.round(state.live.cloud_cover)}%`;
const stamp=state.live.time?.split('T')[1]||'now';status.textContent=`Live · Open‑Meteo · ${stamp}`;
} catch(error) {
if(controller!==weatherAbort)return;
if(error.name==='AbortError'&&controller.signal.aborted)status.textContent='Live request timed out · model shown';
else status.textContent='Offline · model shown';
source.classList.add('error');state.live=null;
} finally {clearTimeout(timeout);updateSelected();}
}
function updatePanControls() {
const longitude=document.getElementById('panLongitude'),latitude=document.getElementById('panLatitude');
const v=state.view,lonSpan=v.east-v.west,latSpan=v.north-v.south;
const centerLon=(v.west+v.east)/2,centerLat=(v.south+v.north)/2;
longitude.disabled=lonSpan>=359.9;latitude.disabled=latSpan>=179.9;
longitude.value=longitude.disabled?50:((centerLon-(-180+lonSpan/2))/(360-lonSpan))*100;
latitude.value=latitude.disabled?50:((centerLat-(-90+latSpan/2))/(180-latSpan))*100;
document.getElementById('viewportReadout').textContent=longitude.disabled&&latitude.disabled?'World view':`${Math.round(centerLat)}°, ${Math.round(centerLon)}° · ${Math.round(lonSpan)}° wide`;
}
function updateUI() {
const config=layers[state.layer];
document.querySelectorAll('.layer-button').forEach(b=>b.classList.toggle('active',b.dataset.layer===state.layer));
document.getElementById('mapTitle').textContent=config.title;document.getElementById('mapKicker').textContent=config.kicker;
document.getElementById('legendName').textContent=`${config.name} · visible range`;
document.getElementById('legendGradient').style.background=config.gradient;document.getElementById('miniScale').style.background=config.gradient;
document.getElementById('globalValue').textContent=config.global;document.getElementById('globalUnit').textContent=config.unit;
document.getElementById('globalDescription').textContent=config.description;document.getElementById('trendValue').textContent=config.trend;document.getElementById('trendText').textContent=config.trendText;
document.getElementById('snapshotYear').textContent='Model + live';
const toggle=document.getElementById('illuminationToggle');
toggle.checked=state.illuminationOverlay;toggle.disabled=state.layer==='illumination';
document.getElementById('illuminationSwitchNote').textContent=state.layer==='illumination'?'Built into this layer':state.illuminationOverlay?'Shown on this layer':'Hidden on this layer';
const hour=state.utcHour%24;document.getElementById('yearLabel').textContent=`${String(Math.floor(hour)).padStart(2,'0')}:${String(Math.round((hour%1)*60)%60).padStart(2,'0')}`;
drawMap();drawBoundaries();updateSelected();updatePanControls();updateDetailsToggle();
}
function setView(centerLon,centerLat,lonSpan,latSpan) {
lonSpan=clamp(lonSpan,4,360);latSpan=clamp(latSpan,3,180);
let west=centerLon-lonSpan/2,east=centerLon+lonSpan/2,south=centerLat-latSpan/2,north=centerLat+latSpan/2;
if(west<-180){east+=-180-west;west=-180;}if(east>180){west-=east-180;east=180;}
if(south<-90){north+=-90-south;south=-90;}if(north>90){south-=north-90;north=90;}
state.view={west,east,south,north};updateUI();
}
function zoom(factor) {
const v=state.view;setView((v.west+v.east)/2,(v.south+v.north)/2,(v.east-v.west)*factor,(v.north-v.south)*factor);
}
document.querySelectorAll('.layer-button').forEach(button=>button.addEventListener('click',()=>{state.layer=button.dataset.layer;updateUI();}));
document.getElementById('illuminationToggle').addEventListener('change',e=>{state.illuminationOverlay=e.target.checked;updateUI();});
document.getElementById('zoomIn').addEventListener('click',e=>{e.stopPropagation();zoom(.65);});
document.getElementById('zoomOut').addEventListener('click',e=>{e.stopPropagation();zoom(1.5);});
document.getElementById('resetView').addEventListener('click',e=>{e.stopPropagation();state.view={west:-180,east:180,south:-90,north:90};updateUI();});
document.getElementById('panLongitude').addEventListener('input',e=>{
const v=state.view,span=v.east-v.west,center=-180+span/2+(Number(e.target.value)/100)*(360-span);
setView(center,(v.south+v.north)/2,span,v.north-v.south);
});
document.getElementById('panLatitude').addEventListener('input',e=>{
const v=state.view,span=v.north-v.south,center=-90+span/2+(Number(e.target.value)/100)*(180-span);
setView((v.west+v.east)/2,center,v.east-v.west,span);
});
const selectButton=document.getElementById('selectRegion');
selectButton.addEventListener('click',e=>{e.stopPropagation();state.selectMode=!state.selectMode;selectButton.classList.toggle('active',state.selectMode);mapCard.classList.toggle('selecting',state.selectMode);});
let selectionStart=null;
let panStart=null;
let suppressMapClick=false;
mapCard.addEventListener('pointerdown',e=>{
if(e.target.closest('.map-controls,.location-card,.legend-panel'))return;
const p=screenPoint(e);
if(state.selectMode){selectionStart=p;selectionBox.hidden=false;selectionBox.style.left=`${p.sx}px`;selectionBox.style.top=`${p.sy}px`;selectionBox.style.width='0';selectionBox.style.height='0';mapCard.setPointerCapture(e.pointerId);return;}
const v=state.view;
if((v.east-v.west)<359.9||(v.north-v.south)<179.9){panStart={point:p,view:{...v}};mapCard.classList.add('panning');mapCard.setPointerCapture(e.pointerId);}
});
mapCard.addEventListener('pointermove',e=>{
const p=screenPoint(e);
if(selectionStart){selectionBox.style.left=`${Math.min(selectionStart.sx,p.sx)}px`;selectionBox.style.top=`${Math.min(selectionStart.sy,p.sy)}px`;selectionBox.style.width=`${Math.abs(p.sx-selectionStart.sx)}px`;selectionBox.style.height=`${Math.abs(p.sy-selectionStart.sy)}px`;return;}
if(panStart){
const v=panStart.view,lonSpan=v.east-v.west,latSpan=v.north-v.south;
const dx=p.x-panStart.point.x,dy=p.y-panStart.point.y;
setView((v.west+v.east)/2-dx/MAP_W*lonSpan,(v.south+v.north)/2+dy/MAP_H*latSpan,lonSpan,latSpan);
hoverTip.hidden=true;return;
}
if(e.target.closest?.('.location-card,.map-controls,.legend-panel'))return;
const geo=unproject(p.x,p.y),value=valueAt(state.layer,geo.lat,geo.lon);
hoverTip.hidden=false;hoverTip.style.left=`${p.sx}px`;hoverTip.style.top=`${p.sy}px`;
document.getElementById('hoverValue').textContent=`${formatValue(value)} ${layers[state.layer].unit}`;
document.getElementById('hoverCoords').textContent=`${Math.abs(geo.lat).toFixed(2)}°${geo.lat>=0?'N':'S'} · ${Math.abs(geo.lon).toFixed(2)}°${geo.lon>=0?'E':'W'} · sun ${Math.round(solarElevation(geo.lat,geo.lon))}°`;
});
mapCard.addEventListener('pointerup',e=>{
const p=screenPoint(e);
if(selectionStart){
const start=selectionStart;selectionStart=null;selectionBox.hidden=true;mapCard.releasePointerCapture(e.pointerId);
state.selectMode=false;selectButton.classList.remove('active');mapCard.classList.remove('selecting');
if(Math.abs(p.x-start.x)>25&&Math.abs(p.y-start.y)>20){const a=unproject(start.x,start.y),b=unproject(p.x,p.y);state.view={west:Math.min(a.lon,b.lon),east:Math.max(a.lon,b.lon),south:Math.min(a.lat,b.lat),north:Math.max(a.lat,b.lat)};suppressMapClick=true;updateUI();}
return;
}
if(panStart){
const moved=Math.abs(p.x-panStart.point.x)>4||Math.abs(p.y-panStart.point.y)>4;
panStart=null;mapCard.classList.remove('panning');mapCard.releasePointerCapture(e.pointerId);if(moved)suppressMapClick=true;
}
});
mapCard.addEventListener('mouseleave',()=>{if(!selectionStart&&!panStart)hoverTip.hidden=true;});
mapCard.addEventListener('click',e=>{
if(suppressMapClick){suppressMapClick=false;return;}
if(state.selectMode||e.target.closest?.('button,.location-card,.legend-panel'))return;
const p=screenPoint(e),geo=unproject(p.x,p.y);state.live=null;state.selected={name:countryAt(geo.lat,geo.lon),lat:geo.lat,lon:geo.lon};updateSelected();fetchWeather();
});
document.getElementById('closeLocation').addEventListener('click',e=>{e.stopPropagation();state.infoPanelVisible=false;updateSelected();updateDetailsToggle();});
document.getElementById('detailsToggle').addEventListener('click',()=>{state.infoPanelVisible=!state.infoPanelVisible;updateSelected();updateDetailsToggle();});
const card=document.getElementById('locationCard'),handle=document.getElementById('dragHandle');let cardDrag=null;
handle.addEventListener('pointerdown',e=>{e.stopPropagation();const cr=card.getBoundingClientRect(),mr=mapCard.getBoundingClientRect();cardDrag={dx:e.clientX-cr.left,dy:e.clientY-cr.top,map:mr};handle.setPointerCapture(e.pointerId);});
handle.addEventListener('pointermove',e=>{if(!cardDrag)return;const left=clamp(e.clientX-cardDrag.map.left-cardDrag.dx,4,cardDrag.map.width-card.offsetWidth-4),top=clamp(e.clientY-cardDrag.map.top-cardDrag.dy,4,cardDrag.map.height-card.offsetHeight-4);card.style.left=`${left}px`;card.style.top=`${top}px`;card.style.right='auto';});
handle.addEventListener('pointerup',e=>{if(cardDrag){cardDrag=null;handle.releasePointerCapture(e.pointerId);}});
const range=document.getElementById('timeRange');range.value=state.utcHour;
range.addEventListener('input',()=>{state.utcHour=Number(range.value);updateUI();});
let playing=null;
document.getElementById('playButton').addEventListener('click',()=>{
const button=document.getElementById('playButton');
if(playing){clearInterval(playing);playing=null;button.innerHTML='<svg viewBox="0 0 24 24"><path d="m8 5 11 7-11 7V5Z"/></svg>';return;}
button.innerHTML='<svg viewBox="0 0 24 24"><path d="M8 6h3v12H8zM14 6h3v12h-3z"/></svg>';
playing=setInterval(()=>{state.utcHour=(state.utcHour+.5)%24;range.value=state.utcHour;updateUI();},260);
});
document.getElementById('nowButton').addEventListener('click',()=>{const d=new Date();state.utcHour=d.getUTCHours()+d.getUTCMinutes()/60;range.value=state.utcHour;updateUI();});
document.getElementById('utcNow').textContent=`${String(now.getUTCHours()).padStart(2,'0')}:${String(now.getUTCMinutes()).padStart(2,'0')} UTC`;
const search=document.getElementById('searchInput'),results=document.getElementById('searchResults');
function showResults(){const q=search.value.trim().toLowerCase(),matches=cities.filter(c=>!q||c.name.toLowerCase().includes(q)).slice(0,5);results.innerHTML=matches.map(c=>`<button class="search-result" data-index="${cities.indexOf(c)}"><span>${c.name}</span><small>${Math.abs(c.lat).toFixed(1)}°${c.lat>=0?'N':'S'}</small></button>`).join('');results.hidden=!matches.length;}
search.addEventListener('focus',showResults);search.addEventListener('input',showResults);
results.addEventListener('click',e=>{const b=e.target.closest('.search-result');if(!b)return;state.live=null;state.selected={...cities[Number(b.dataset.index)]};search.value=state.selected.name;results.hidden=true;updateSelected();fetchWeather();});
document.addEventListener('click',e=>{if(!e.target.closest('.search-wrap'))results.hidden=true;});
document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();search.focus();}if(e.key==='Escape'){results.hidden=true;document.getElementById('aboutModal').hidden=true;state.selectMode=false;selectButton.classList.remove('active');mapCard.classList.remove('selecting');}});
const modal=document.getElementById('aboutModal');
document.getElementById('infoButton').addEventListener('click',()=>modal.hidden=false);
document.querySelector('nav a[href="#about"]').addEventListener('click',e=>{e.preventDefault();modal.hidden=false;});
document.getElementById('closeModal').addEventListener('click',()=>modal.hidden=true);
modal.addEventListener('click',e=>{if(e.target===modal)modal.hidden=true;});
updateUI();loadGeography();fetchWeather();