File size: 65,231 Bytes
bcc6edb
9500392
 
 
 
 
bcc6edb
9500392
 
 
 
 
 
bcc6edb
 
9500392
bcc6edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d35358
ad2db1a
4d35358
bcc6edb
 
9500392
 
 
 
 
 
 
 
72ba934
9500392
bcc6edb
 
 
 
9500392
 
 
 
bcc6edb
 
 
 
9500392
 
 
 
72ba934
 
 
 
 
 
4d1b995
9500392
bcc6edb
9500392
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d35358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9500392
 
 
 
 
 
 
 
 
 
bcc6edb
9500392
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc6edb
9500392
 
 
 
 
 
bcc6edb
 
 
72ba934
 
 
 
 
4d1b995
72ba934
 
 
 
 
4d1b995
72ba934
 
 
4d1b995
 
 
72ba934
 
 
bcc6edb
72ba934
 
bcc6edb
 
 
72ba934
9500392
4d35358
bcc6edb
4d35358
 
 
 
 
 
 
 
 
 
72ba934
 
4d35358
bcc6edb
 
 
 
 
9500392
 
bcc6edb
 
9500392
4d35358
9500392
4d35358
 
9500392
4d35358
72ba934
 
4d35358
72ba934
 
4d35358
 
 
 
 
 
bcc6edb
4d35358
9500392
4d35358
9500392
4d35358
 
bcc6edb
9500392
bcc6edb
9500392
bcc6edb
9500392
bcc6edb
9500392
 
bcc6edb
 
 
9500392
bcc6edb
 
 
 
 
 
 
 
 
 
 
9500392
bcc6edb
 
 
 
716dbb5
 
ad2db1a
72ba934
bcc6edb
9500392
 
716dbb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1b995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2db1a
 
 
2901af1
4d1b995
ad2db1a
 
 
4d1b995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2901af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2db1a
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1b995
ad2db1a
 
 
 
9b3c183
4d1b995
9b3c183
 
 
 
4d1b995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b3c183
 
 
ad2db1a
 
9b3c183
 
ad2db1a
9b3c183
 
4d1b995
9b3c183
 
 
 
 
2901af1
4d1b995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2901af1
 
 
 
 
 
 
 
 
ad2db1a
 
 
 
 
 
 
 
 
9b3c183
 
 
2901af1
4d1b995
 
 
 
 
 
2901af1
 
 
 
9b3c183
 
ad2db1a
9b3c183
ad2db1a
 
 
 
 
 
2901af1
 
4d1b995
 
 
 
ad2db1a
 
 
 
 
 
 
 
72ba934
2901af1
 
72ba934
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2901af1
72ba934
 
2901af1
72ba934
 
 
4d1b995
72ba934
 
 
 
2901af1
72ba934
 
 
 
 
 
2901af1
 
 
 
 
 
 
 
72ba934
2901af1
72ba934
 
 
2901af1
72ba934
 
 
 
 
4d1b995
 
 
72ba934
 
 
4d1b995
72ba934
 
 
 
4d1b995
 
 
 
 
 
 
 
 
 
 
 
 
72ba934
 
 
2901af1
72ba934
 
 
 
 
ad2db1a
72ba934
 
 
 
 
 
 
 
 
 
 
 
bcc6edb
 
 
 
 
 
 
 
 
 
4d35358
 
bcc6edb
4d35358
bcc6edb
 
 
 
4d35358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83febf6
 
 
 
 
 
 
 
 
 
 
 
 
4d35358
 
 
 
 
bcc6edb
4d35358
 
 
 
 
83febf6
 
 
 
 
 
9500392
bcc6edb
 
 
 
9500392
bcc6edb
9500392
bcc6edb
9500392
 
4d35358
 
 
 
 
 
 
 
9500392
4d35358
9500392
bcc6edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9500392
 
bcc6edb
9500392
72ba934
 
 
 
716dbb5
 
 
 
 
 
 
 
 
 
 
2901af1
 
 
 
 
 
ad2db1a
 
 
 
 
 
9b3c183
72ba934
2901af1
 
 
bcc6edb
9500392
 
 
 
bcc6edb
 
72ba934
9500392
 
72ba934
9500392
bcc6edb
4d35358
bcc6edb
72ba934
 
ad2db1a
72ba934
 
 
 
 
 
 
9500392
 
bcc6edb
 
9500392
 
 
 
 
 
 
 
 
 
4d35358
bcc6edb
716dbb5
 
 
bcc6edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9500392
 
bcc6edb
9500392
bcc6edb
 
 
9500392
bcc6edb
9500392
 
4d35358
 
 
 
 
 
 
 
 
9500392
bcc6edb
4d35358
 
 
 
 
 
 
 
 
 
 
9500392
 
4d1b995
 
 
 
 
 
 
 
 
 
9500392
ad2db1a
 
 
 
 
 
 
 
 
 
9500392
4d35358
 
bcc6edb
4d1b995
 
ad2db1a
4d35358
 
 
 
 
 
 
 
 
 
 
 
9500392
 
 
 
 
4d35358
9500392
 
bcc6edb
 
 
9500392
 
bcc6edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9500392
 
4d35358
 
 
 
 
 
 
 
 
 
 
bcc6edb
 
 
9500392
bcc6edb
9500392
bcc6edb
9500392
 
bcc6edb
 
 
 
 
 
 
 
4d35358
 
9500392
 
bcc6edb
 
 
4d35358
 
bcc6edb
9500392
4d35358
ad2db1a
9500392
bcc6edb
9500392
 
bcc6edb
9500392
 
 
 
 
ad2db1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc6edb
 
 
 
 
ad2db1a
 
bcc6edb
 
 
 
 
 
 
ad2db1a
 
 
 
 
 
 
 
 
 
 
 
bcc6edb
 
 
 
 
 
 
 
 
 
 
 
9500392
 
bcc6edb
 
4d35358
bcc6edb
 
 
 
 
9500392
 
 
 
4d1b995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9500392
4d1b995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc6edb
 
 
 
 
9500392
bcc6edb
 
9500392
4d1b995
 
 
 
 
 
 
9500392
 
 
 
bcc6edb
 
9500392
bcc6edb
 
 
 
9500392
 
bcc6edb
9500392
 
4d35358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72ba934
716dbb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2901af1
 
 
 
 
 
 
 
 
 
 
 
72ba934
 
 
 
 
 
 
 
 
 
 
 
 
4d35358
 
bcc6edb
 
 
 
 
 
 
9500392
 
 
bcc6edb
9500392
 
 
 
 
 
 
bcc6edb
ad2db1a
bcc6edb
 
 
 
72ba934
716dbb5
 
ad2db1a
9500392
bcc6edb
 
716dbb5
 
 
 
 
 
72ba934
ad2db1a
72ba934
2901af1
 
4d35358
 
 
 
 
 
 
9500392
 
 
 
bcc6edb
9500392
 
4d35358
9500392
 
 
 
 
72ba934
 
ad2db1a
9500392
4d35358
9500392
4d35358
bcc6edb
ad2db1a
 
 
 
 
 
9500392
4d35358
 
9500392
 
 
 
ad2db1a
 
 
 
 
 
 
 
 
 
 
 
9500392
 
 
 
 
716dbb5
 
ad2db1a
2901af1
bcc6edb
9500392
 
bcc6edb
4d35358
9500392
 
 
 
 
bcc6edb
 
9500392
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
/* GEO EVENTS · 全球极端事件态势 */
const DATA = 'data/';
const $ = (id) => document.getElementById(id);

const GROUP = {
  '大规模暴力': 'conflict', '武装冲突': 'conflict', '武装袭击': 'conflict',
  '军事部署': 'mil', '胁迫': 'mil', '威胁制裁': 'mil',
  '抗议骚乱': 'social', '政治施压': 'social', '减少关系': 'social',
  '外交协商': 'diplo', '外交表态': 'diplo', '调查': 'diplo', '其他': 'diplo',
  '物质合作': 'coop', '提供援助': 'coop', '让步妥协': 'coop',
  '地震': 'quake', '自然事件': 'nature',
};
const COLOR = {
  conflict: '#ff6b5a', mil: '#ff8a5a', social: '#56a8ff', diplo: '#7f93ad',
  coop: '#4ade9f', quake: '#ffb454', nature: '#d9c85c',
};
const NAME = {
  conflict: '武装冲突', mil: '军事胁迫', social: '社会动荡',
  diplo: '外交政治', coop: '合作援助', quake: '地震', nature: '自然事件',
};
const CCOLOR = { 1: '#d9a52b', 2: '#e0553f', 3: '#b98cff' };

/* 国名注记:只在球面放大到一定程度后出现 */
const LABELS = [
  ['中国', 104, 34], ['美国', -100, 39], ['俄罗斯', 96, 61], ['印度', 79, 22],
  ['巴西', -51, -11], ['澳大利亚', 134, -25], ['加拿大', -106, 57],
  ['阿尔及利亚', 2, 27], ['尼日利亚', 8, 9], ['埃及', 30, 26], ['南非', 24, -29],
  ['沙特', 45, 24], ['伊朗', 54, 32], ['土耳其', 35, 39], ['乌克兰', 31, 49],
  ['法国', 2, 46], ['德国', 10, 51], ['日本', 138, 37], ['印尼', 113, -2],
  ['阿根廷', -64, -35], ['墨西哥', -102, 24], ['哈萨克斯坦', 68, 48],
];

const state = { summary: null, events: [], news: [], cdhe: null, hours: 24, markers: [], cLabels: [],
  disasters: [], fires: { type: 'FeatureCollection', features: [] }, flights: [], rank: 'epi', feedTop: null,
  pulses: [], countries: null, feed: 'news', region: '全球' };
const domain = (u) => { try { return new URL(u).hostname.replace(/^www\./, ''); } catch (e) { return ''; } };
const fmt = (n) => (n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e4 ? (n / 1e3).toFixed(1) + 'k' : String(n));

/* ---------------- 地图 ---------------- */
const map = new maplibregl.Map({
  container: 'map',
  style: {
    version: 8,
    projection: { type: 'globe' },
    sources: {},
    layers: [{ id: 'bg', type: 'background', paint: { 'background-color': '#04070c', 'background-opacity': 0 } }],
  },
  center: [18, 20],
  zoom: 2.5,
  minZoom: 1.0,
  maxZoom: 7,
  attributionControl: false,
  dragRotate: false,
  pitchWithRotate: false,
});
window.__map = map;
map.on('error', (e) => console.error('MAPERR', e && e.error && e.error.message));
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), 'bottom-right');

function applyGlobe() {
  try {
    map.setProjection({ type: 'globe' });
    map.setSky({
      'sky-color': '#05090f',
      'sky-horizon-blend': 0.36,
      'horizon-color': '#134667',
      'horizon-fog-blend': 0.14,
      'fog-color': '#06111c',
      'fog-ground-blend': 0.42,
      'atmosphere-blend': 0.45,
    });
  } catch (e) { console.warn('globe 不可用', e); }
}

function graticule() {
  const f = [];
  for (let lon = -180; lon < 180; lon += 30) {
    const c = [];
    for (let lat = -85; lat <= 85; lat += 2.5) c.push([lon, lat]);
    f.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: c } });
  }
  for (let lat = -60; lat <= 60; lat += 30) {
    const c = [];
    for (let lon = -180; lon <= 180; lon += 2.5) c.push([lon, lat]);
    f.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: c } });
  }
  return { type: 'FeatureCollection', features: f };
}

const REGIONS = [
  ['全球', 18, 20, 2.5],
  ['中东', 45, 29, 3.6],
  ['欧洲', 12, 50, 3.7],
  ['东亚', 116, 32, 3.6],
  ['南亚', 78, 22, 3.8],
  ['北美', -100, 40, 3.1],
  ['非洲', 20, 2, 3.0],
  ['南美', -60, -15, 3.0],
];

/* Natural Earth 对争议地区给 FIPS=-99,这里按英文名桥接到 GDELT 的 FIPS 代码 */
const BRIDGE = {
  Israel: ['IS'],
  Palestine: ['WE', 'GZ'],
  'South Sudan': ['OD'],
  Norway: ['NO'],
  Mozambique: ['MZ'],
  'East Timor': ['TT'],
  'Guinea-Bissau': ['PU'],
  'Western Sahara': ['WI'],
  'Falkland Islands': ['FK'],
  'French Southern and Antarctic Lands': ['FS'],
};

/** 把国家级 EPI 写回国界要素,供 fill-color 直接读 */
function enrichCountries(gj) {
  const rows = (state.summary && state.summary.all_countries) || [];
  const byFips = new Map(rows.map((r) => [r.f, r]));
  state.nameOf = new Map();
  const max = Math.max(...rows.map((r) => r.epi), 1);
  let hit = 0;
  gj.features.forEach((f) => {
    const p = f.properties;
    let hits = [];
    const direct = byFips.get(p.FIPS_10) || byFips.get(p.ISO_A2);
    if (direct) hits = [direct];
    else if (BRIDGE[p.NAME_EN]) hits = BRIDGE[p.NAME_EN].map((k) => byFips.get(k)).filter(Boolean);
    if (hits.length && hits.some((r) => r.epi > 0)) {
      p.epi = hits.reduce((s, r) => s + r.epi, 0);
      p.n = hits.reduce((s, r) => s + (r.n || 0), 0);
      p.p = Math.pow(p.epi / max, 0.55);
      // 字典里没有的小国只回了两位代码,这时用国界自带的中文名
      p.cn = (hits[0].cc && hits[0].cc !== hits[0].f)
        ? hits[0].cc
        : (f.properties.NAME_ZH || f.properties.NAME);
      p.fips = hits[0].f;
      if (!state.nameOf.has(p.fips)) state.nameOf.set(p.fips, p.cn);
      hit++;
    } else {
      p.epi = 0; p.p = null; p.cn = p.NAME_ZH || p.NAME;
    }
    // 粗略中心:外环顶点均值,足够用于飞到该国
    const g = f.geometry;
    let ring = null;
    if (g.type === 'Polygon') ring = g.coordinates[0];
    else if (g.type === 'MultiPolygon') {
      ring = g.coordinates.reduce((a, b) => (b[0].length > a[0].length ? b : a))[0];
    }
    if (ring) {
      let sx = 0, sy = 0;
      ring.forEach(([x, y]) => { sx += x; sy += y; });
      p.cx = sx / ring.length; p.cy = sy / ring.length;
    }
  });
  console.log('国界匹配', hit, '/', gj.features.length);
  return gj;
}

function eventFeatures() {
  return {
    type: 'FeatureCollection',
    features: state.events.map((p) => ({
      type: 'Feature',
      geometry: { type: 'Point', coordinates: [p.lon, p.lat] },
      properties: {
        grp: GROUP[p.cat] || 'diplo', cat: p.cat, cc: p.cc,
        m: p.m || 0, t: p.t, title: p.title || '', url: p.url || '',
        src: p.src, w: p.w || 3, ts: Date.parse(p.ts) / 1000,
        r: Math.min(6.5, 1.8 + Math.sqrt(p.m || 0) * 0.36),
      },
    })),
  };
}

function cdheFeatures() {
  return {
    type: 'FeatureCollection',
    features: state.cdhe.points.map((p) => ({
      type: 'Feature',
      geometry: { type: 'Point', coordinates: [p[0], p[1]] },
      properties: { s: p[2], spi: p[3], sti: p[4] },
    })),
  };
}

function oceanSource() {
  const bands = [];
  for (let lon = -180; lon < 180; lon += 40) {
    const a = lon - 0.1, b = Math.min(180, lon + 40.1);
    bands.push({ type: 'Feature', geometry: { type: 'Polygon', coordinates: [[
      [a, -89], [b, -89], [b, 89], [a, 89], [a, -89]]] } });
  }
  return { type: 'FeatureCollection', features: bands };
}

const TILES = '/tiles/gibs/';

function addBaseRaster() {
  // 真实地表:NASA GIBS 静态影像,本地 nginx 已做 30 天缓存
  map.addSource('base-night', {
    type: 'raster', tileSize: 256, maxzoom: 6, attribution: 'NASA GIBS / VIIRS',
    tiles: [TILES + 'VIIRS_CityLights_2012/default/2012-01-01/GoogleMapsCompatible_Level8/{z}/{y}/{x}.jpg'],
  });
  map.addLayer({ id: 'base-night', type: 'raster', source: 'base-night',
    paint: { 'raster-opacity': 0.9, 'raster-brightness-max': 0.95, 'raster-contrast': 0.1, 'raster-fade-duration': 260 } });
  map.addSource('base-relief', {
    type: 'raster', tileSize: 256, maxzoom: 6, attribution: 'NASA GIBS / Blue Marble',
    tiles: [TILES + 'BlueMarble_ShadedRelief_Bathymetry/default/500m/GoogleMapsCompatible_Level8/{z}/{y}/{x}.jpeg'],
  });
  map.addLayer({ id: 'base-relief', type: 'raster', source: 'base-relief',
    paint: { 'raster-opacity': 0.96, 'raster-saturation': 0.05,
      'raster-brightness-min': 0.04, 'raster-brightness-max': 0.95,
      'raster-contrast': -0.12, 'raster-fade-duration': 180 } });
  map.setLayoutProperty('base-relief', 'visibility', 'none');
}

function addLayers() {
  addBaseRaster();
  // 极简模式下的球体:海面给一点深蓝,陆地压暗,形成"球"而不是"平面"
  map.addSource('ocean', { type: 'geojson', data: oceanSource() });
  map.addLayer({ id: 'ocean', type: 'fill', source: 'ocean',
    paint: { 'fill-color': '#081726', 'fill-opacity': 1 } });
  map.setLayoutProperty('ocean', 'visibility', 'none');

  map.addSource('countries', { type: 'geojson', data: state.countries });
  map.addLayer({ id: 'c-fill', type: 'fill', source: 'countries',
    paint: {
      'fill-color': ['case',
        ['==', ['get', 'p'], null], '#0e1a28',
        ['interpolate', ['linear'], ['get', 'p'],
          0.00, '#132030',
          0.30, '#2b3038',
          0.55, '#5e4433',
          0.78, '#a3553c',
          1.00, '#ff6b5a']],
      'fill-opacity': ['case',
        ['==', ['get', 'p'], null], 0.18,
        ['interpolate', ['linear'], ['get', 'p'], 0, 0.08, 1, 0.34]],
    } });
  // 两层描边:外层低透明度做微光,内层细线做边界
  map.addLayer({ id: 'c-glow', type: 'line', source: 'countries',
    paint: { 'line-color': '#2f6f9e', 'line-width': 2.2, 'line-opacity': 0.10, 'line-blur': 1.6 } });
  map.addLayer({ id: 'c-line', type: 'line', source: 'countries',
    paint: { 'line-color': '#29506f', 'line-width': 0.45, 'line-opacity': 0.85 } });

  map.addSource('grat', { type: 'geojson', data: graticule() });
  map.addLayer({ id: 'grat', type: 'line', source: 'grat',
    paint: { 'line-color': '#12324c', 'line-width': 0.4, 'line-opacity': 0.55 } });

  // CDHE:按三态各一层热力,格点融合成连续场
  map.addSource('cdhe', { type: 'geojson', data: cdheFeatures() });
  const heat = (id, s, ramp) => map.addLayer({
    id, type: 'heatmap', source: 'cdhe', filter: ['==', ['get', 's'], s],
    paint: {
      'heatmap-weight': 1,
      'heatmap-intensity': ['interpolate', ['linear'], ['zoom'], 1, 0.5, 3, 0.44, 6, 0.38],
      'heatmap-radius': ['interpolate', ['exponential', 1.9], ['zoom'], 1, 12, 2, 20, 3, 34, 4, 64, 5, 120, 6, 240],
      'heatmap-color': ['interpolate', ['linear'], ['heatmap-density'],
        0, 'rgba(0,0,0,0)', 0.35, ramp[0], 0.7, ramp[1], 1, ramp[2]],
      'heatmap-opacity': 0.58,
    },
  });
  heat('cdhe-h1', 1, ['rgba(217,165,43,.10)', 'rgba(217,165,43,.26)', 'rgba(236,190,80,.46)']);
  heat('cdhe-h2', 2, ['rgba(224,85,63,.10)', 'rgba(224,85,63,.26)', 'rgba(255,120,95,.46)']);
  heat('cdhe-h3', 3, ['rgba(185,140,255,.12)', 'rgba(185,140,255,.34)', 'rgba(214,180,255,.62)']);
  // 放大后补一圈细点,保留"这是格点"的信息
  map.addLayer({ id: 'cdhe-pts', type: 'circle', source: 'cdhe',
    minzoom: 2.4,
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'], 2.4, 1.2, 6, 3.2],
      'circle-color': ['match', ['get', 's'], 1, CCOLOR[1], 2, CCOLOR[2], 3, CCOLOR[3], '#888'],
      'circle-opacity': ['interpolate', ['linear'], ['zoom'], 2.4, 0, 3.6, 0.4],
      'circle-blur': 0.2,
    } });

  // 事件点
  map.addSource('events', { type: 'geojson', data: eventFeatures() });
  const paint = (c, op) => ({
    'circle-radius': ['interpolate', ['linear'], ['zoom'],
      1, ['*', ['get', 'r'], 0.8], 3, ['*', ['get', 'r'], 1.0], 6, ['*', ['get', 'r'], 1.6]],
    'circle-color': c,
    'circle-opacity': op,
    'circle-blur': 0.1,
    'circle-stroke-width': 0.45,
    'circle-stroke-color': 'rgba(230,242,255,.5)',
  });
  [
    ['ev-conflict', 'conflict', 0.85],
    ['ev-mil', 'mil', 0.8],
    ['ev-social', 'social', 0.8],
    ['ev-diplo', 'diplo', 0.4],
    ['ev-coop', 'coop', 0.45],
    ['ev-quake', 'quake', 0.9],
    ['ev-nature', 'nature', 0.8],
  ].forEach(([id, k, op]) => {
    map.addLayer({ id, type: 'circle', source: 'events',
      filter: ['==', ['get', 'grp'], k], paint: paint(COLOR[k], op) });
  });
  // 地震单独放在 nature 组之外,按类别判断
  map.setFilter('ev-quake', ['==', ['get', 'cat'], '地震']);
  map.setFilter('ev-nature', ['==', ['get', 'cat'], '自然事件']);

  addDisasters();
  addFires();
  addFlights();
  addSats();
  addLabels();
}

const DIS = [
  ['dis-flood', ['FL'], '#3fa9ff'],
  ['dis-cyclone', ['TC'], '#35e0c8'],
  ['dis-drought', ['DR'], '#d9a52b'],
  ['dis-volcano', ['VO'], '#b06ef0'],
  ['dis-wildfire', ['WF'], '#ff8a3d'],
];
const DIS_TOG = { FL: 'l-flood', TC: 'l-cyclone', DR: 'l-drought', VO: 'l-volcano', WF: 'l-wildfire' };
const ALR = ['match', ['get', 'al'], 'Red', 1.65, 'Orange', 1.3, 1];

function disasterFC() {
  return { type: 'FeatureCollection', features: (state.disasters || []).map((d) => ({
    type: 'Feature', geometry: { type: 'Point', coordinates: [d.lon, d.lat] }, properties: d })) };
}

function addDisasters() {
  map.addSource('disasters', { type: 'geojson', data: disasterFC() });
  DIS.forEach(([id, types, color]) => {
    map.addLayer({ id, type: 'circle', source: 'disasters',
      filter: ['in', ['get', 'et'], ['literal', types]],
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'],
          1, ['*', 2.4, ALR], 4, ['*', 3.9, ALR], 7, ['*', 5.8, ALR]],
        'circle-color': color,
        'circle-opacity': 0.2,
        'circle-stroke-color': ['match', ['get', 'al'], 'Red', '#ff4d4d', 'Orange', '#ffb03a', color],
        'circle-stroke-width': ['match', ['get', 'al'], 'Red', 1.8, 'Orange', 1.4, 0.9],
        'circle-stroke-opacity': 0.82,
      } });
  });
}

function addFires() {
  map.addSource('fires', { type: 'geojson', data: state.fires });
  map.addLayer({ id: 'fire-heat', type: 'heatmap', source: 'fires',
    paint: {
      'heatmap-weight': ['interpolate', ['linear'], ['get', 'f'], 0, 0.22, 40, 0.6, 200, 1],
      'heatmap-intensity': ['interpolate', ['linear'], ['zoom'], 1, 0.5, 3, 0.7, 6, 0.85],
      'heatmap-radius': ['interpolate', ['exponential', 1.6], ['zoom'], 1, 8, 2, 11, 3, 15, 5, 22, 7, 32],
      'heatmap-color': ['interpolate', ['linear'], ['heatmap-density'],
        0, 'rgba(0,0,0,0)', 0.3, 'rgba(255,130,60,.16)', 0.65, 'rgba(255,110,50,.4)',
        1, 'rgba(255,205,130,.7)'],
      'heatmap-opacity': 0.8,
    } });
  map.addLayer({ id: 'fire-pt', type: 'circle', source: 'fires', minzoom: 2.6,
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'], 2.6, 0.9, 6, 2.2],
      'circle-color': '#ffc078', 'circle-opacity': 0.55, 'circle-blur': 0.3,
    } });
}

const AIRLINE = {
  CCA: '中国国航', CES: '东方航空', CSN: '南方航空', CHH: '海南航空', CXA: '厦门航空',
  CSC: '四川航空', CSZ: '深圳航空', CQH: '春秋航空', CUA: '中国联航', CYZ: '顺丰航空',
  CAL: '中华航空', EVA: '长荣航空', CPA: '国泰航空', HKE: '香港快运', CRK: '香港航空',
  JAL: '日本航空', ANA: '全日空', APJ: '乐桃航空', KAL: '大韩航空', AAR: '韩亚航空',
  SIA: '新加坡航空', SLK: '酷航', MAS: '马来西亚航空', AXM: '亚洲航空', GIA: '印尼鹰航',
  LNI: '狮航', CEB: '宿务太平洋', PAL: '菲律宾航空', THA: '泰国国际', AIQ: '泰亚航',
  VNL: '越捷', HVN: '越南航空', AIC: '印度航空', IGO: '靛蓝航空', VTI: '印度快运',
  UAE: '阿联酋航空', ETD: '阿提哈德', QTR: '卡塔尔航空', SVA: '沙特航空', KAC: '科威特航空',
  THY: '土耳其航空', MSR: '埃及航空', ETH: '埃塞俄比亚航空', KQA: '肯尼亚航空',
  SAA: '南非航空', RAM: '摩洛哥皇家', RWD: '卢旺达航空',
  BAW: '英国航空', EZY: '易捷航空', VIR: '维珍航空', AFR: '法国航空', TVF: '泛航法国',
  DLH: '汉莎航空', EWG: '欧洲之翼', SWR: '瑞士航空', AUA: '奥地利航空', KLM: '荷兰皇家',
  TRA: '泛航荷兰', IBE: '西班牙航空', VLG: '伏林航空', AEA: '欧罗巴航空', TAP: '葡萄牙航空',
  ITY: 'ITA 航空', SAS: '北欧航空', NAX: '挪威航空', RYR: '瑞安航空', EIN: '爱尔兰航空',
  WZZ: '维兹航空', LOT: '波兰航空', CSA: '捷克航空', AEE: '爱琴海航空', ELL: '波罗的海航空',
  QFA: '澳洲航空', JST: '捷星航空', ANZ: '新西兰航空', VOZ: '维珍澳洲',
  ACA: '加拿大航空', WJA: '西捷航空', UAL: '美联航', DAL: '达美航空', AAL: '美国航空',
  SWA: '西南航空', JBU: '捷蓝航空', ASA: '阿拉斯加航空', FFT: '边疆航空', NKS: '精神航空',
  HAL: '夏威夷航空', AMX: '墨西哥航空', AVA: '哥伦比亚航空', LAN: '智利航空',
  GLO: '戈尔航空', AZU: '蓝色巴西', TAM: '巴西天马', ARG: '阿根廷航空',
};
function airlineOf(cs) {
  return AIRLINE[(cs || '').slice(0, 3)] || '';
}

const FL = { rows: [], mil: [], trails: {}, t0: 0, timer: null, sel: null };

function initFlights(data) {
  FL.rows = data.flights || [];
  FL.mil = data.mil || [];
  FL.trails = data.trails || {};
  FL.t0 = data.generated || Date.now() / 1000;
}

/* 球面正算:从 (lat,lon) 沿方位角 brg 前进 dist 米 */
function dest(lat, lon, brg, dist) {
  const R = 6371000, d = dist / R, b = (brg * Math.PI) / 180;
  const p1 = (lat * Math.PI) / 180, l1 = (lon * Math.PI) / 180;
  const p2 = Math.asin(Math.sin(p1) * Math.cos(d) + Math.cos(p1) * Math.sin(d) * Math.cos(b));
  const l2 = l1 + Math.atan2(Math.sin(b) * Math.sin(d) * Math.cos(p1),
    Math.cos(d) - Math.sin(p1) * Math.sin(p2));
  let lo = (l2 * 180) / Math.PI;
  if (lo > 180) lo -= 360;
  if (lo < -180) lo += 360;
  return [lo, (p2 * 180) / Math.PI];
}

/* 已飞航迹:用后端的真实历史点 */
function trailFC() {
  const now = Date.now() / 1000;
  const dt = Math.min(Math.max(now - FL.t0, 0), 1800);
  const feats = [];
  Object.entries(FL.trails).forEach(([hexid, pts]) => {
    if (!pts || !pts.length) return;
    const r = FL.rows.find((x) => x[7] === hexid);
    if (!r) return;
    const pos = flightPos(r);
    if (pts.length >= 2) {
      feats.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: pts.map((p) => [p[0], p[1]]) },
        properties: { h: hexid } });
    } else if (r[3] > 30) {
      // 历史还没攒够 2 点:按航向反推 20 分钟,先给出航迹尾
      const back = dest(pos[1], pos[0], (r[4] + 180) % 360, r[3] * 20 * 60);
      feats.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: [back, pos] },
        properties: { h: hexid } });
    }
  });
  return { type: 'FeatureCollection', features: feats };
}

/* 预测线:从当前位置沿航向按速度外推 45 分钟 */
function forecastFC() {
  const now = Date.now() / 1000;
  const dt = Math.min(Math.max(now - FL.t0, 0), 1800);
  const feats = [];
  if (!FL.sel) return { type: 'FeatureCollection', features: feats };
  // 只给选中的飞机画前向外推线,否则满屏虚线
  for (let i = 0; i < FL.rows.length; i += 1) {
    const r = FL.rows[i];
    if (r[7] !== FL.sel || !r[3]) continue;
    const rad = (r[4] * Math.PI) / 180;
    const lat = r[1] + (r[3] * Math.cos(rad) * dt) / 111320;
    const cosLat = Math.cos((lat * Math.PI) / 180) || 0.01;
    let lon = r[0] + (r[3] * Math.sin(rad) * dt) / (111320 * cosLat);
    if (lon > 180) lon -= 360;
    if (lon < -180) lon += 360;
    const ahead = dest(lat, lon, r[4], r[3] * 60 * 18);
    feats.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: [[lon, lat], ahead] },
      properties: { h: r[7] } });
  }
  return { type: 'FeatureCollection', features: feats };
}

function milFC() {
  const now = Date.now() / 1000;
  const dt = Math.min(Math.max(now - FL.t0, 0), 1800);
  return { type: 'FeatureCollection', features: FL.mil.map((r) => {
    const rad = (r[4] * Math.PI) / 180;
    const lat = r[1] + (r[3] * Math.cos(rad) * dt) / 111320;
    const cosLat = Math.cos((lat * Math.PI) / 180) || 0.01;
    let lon = r[0] + (r[3] * Math.sin(rad) * dt) / (111320 * cosLat);
    if (lon > 180) lon -= 360;
    if (lon < -180) lon += 360;
    return { type: 'Feature', geometry: { type: 'Point', coordinates: [lon, lat] },
      properties: { c: r[5], t: r[6], a: r[2], h: r[7] } };
  }) };
}

/* 两次拉取之间用速度与航向做推算,让目标真的在动而不是每 20 分钟跳一次 */
function flightFC() {
  const now = Date.now() / 1000;
  const dt = Math.min(Math.max(now - FL.t0, 0), 1800);
  const feats = new Array(FL.rows.length);
  for (let i = 0; i < FL.rows.length; i++) {
    const r = FL.rows[i];
    const rad = (r[4] * Math.PI) / 180;
    const lat = r[1] + (r[3] * Math.cos(rad) * dt) / 111320;
    const cosLat = Math.cos((lat * Math.PI) / 180) || 0.01;
    let lon = r[0] + (r[3] * Math.sin(rad) * dt) / (111320 * cosLat);
    if (lon > 180) lon -= 360;
    if (lon < -180) lon += 360;
    feats[i] = { type: 'Feature', geometry: { type: 'Point', coordinates: [lon, lat] },
      properties: { c: r[5], o: r[6], a: r[2], v: r[3], q: r[7], t: r[4], s: i % 3 === 0 ? 1 : 0, i, h: r[7] } };
  }
  return { type: 'FeatureCollection', features: feats };
}

function planeIcon() {
  const size = 40;
  const cv = document.createElement('canvas');
  cv.width = cv.height = size;
  const g = cv.getContext('2d');
  g.translate(size / 2, size / 2);
  // 机身 + 后掠翼 + 平尾,机头朝上(-y)
  g.beginPath();
  g.moveTo(0, -16);
  g.quadraticCurveTo(1.9, -13.5, 2.1, -6);
  g.lineTo(2.1, -2.6);
  g.lineTo(15, 3.4);
  g.lineTo(15, 5.4);
  g.lineTo(2.1, 1.6);
  g.lineTo(1.9, 6.8);
  g.lineTo(6.2, 10.2);
  g.lineTo(6.2, 11.6);
  g.lineTo(0, 10.2);
  g.lineTo(-6.2, 11.6);
  g.lineTo(-6.2, 10.2);
  g.lineTo(-1.9, 6.8);
  g.lineTo(-2.1, 1.6);
  g.lineTo(-15, 5.4);
  g.lineTo(-15, 3.4);
  g.lineTo(-2.1, -2.6);
  g.lineTo(-2.1, -6);
  g.quadraticCurveTo(-1.9, -13.5, 0, -16);
  g.closePath();
  g.fillStyle = '#e8f6ff';
  g.fill();
  g.lineWidth = 1.6;
  g.strokeStyle = 'rgba(6,16,26,.85)';
  g.stroke();
  return g.getImageData(0, 0, size, size);
}

function addFlights() {
  map.addSource('flights', { type: 'geojson', data: flightFC() });
  try { map.addImage('plane-icon', planeIcon(), { pixelRatio: 2 }); } catch (e) { /* 忽略重复 */ }
  map.addLayer({ id: 'fl-air', type: 'symbol', source: 'flights',
    filter: ['!', ['in', ['get', 'q'], ['literal', ['7700', '7600', '7500']]]],
    layout: {
      'icon-image': 'plane-icon',
      'icon-size': ['interpolate', ['linear'], ['zoom'], 1, 0.26, 3, 0.4, 5, 0.58, 7, 0.72],
      'icon-rotate': ['get', 't'],
      'icon-rotation-alignment': 'map',
      'icon-allow-overlap': true,
      'icon-ignore-placement': true,
    },
    paint: { 'icon-opacity': ['interpolate', ['linear'], ['zoom'], 1, 0.38, 3, 0.5, 5, 0.62, 7, 0.72] } });
  map.addSource('trails', { type: 'geojson', data: trailFC() });
  map.addLayer({ id: 'tr-line', type: 'line', source: 'trails',
    paint: {
      'line-color': '#7fd0f5', 'line-width': 0.65, 'line-opacity': 0.26,
      'line-blur': 0.2,
    } });
  map.addSource('forecast', { type: 'geojson', data: forecastFC() });
  map.addLayer({ id: 'fc-line', type: 'line', source: 'forecast',
    paint: {
      'line-color': '#7fd0f5', 'line-width': 0.65, 'line-opacity': 0.15,
      'line-dasharray': [1.6, 2.2],
    } });

  map.addSource('sel', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
  map.addLayer({ id: 'sel-ring', type: 'circle', source: 'sel',
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'], 1, 13, 5, 22, 8, 30],
      'circle-color': 'rgba(0,0,0,0)',
      'circle-stroke-width': 1.2,
      'circle-stroke-color': 'rgba(90,210,255,.85)',
      'circle-stroke-opacity': 0.9,
    } });
  map.addLayer({ id: 'sel-ring2', type: 'circle', source: 'sel',
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'], 1, 7, 5, 12, 8, 16],
      'circle-color': 'rgba(0,0,0,0)',
      'circle-stroke-width': 0.7,
      'circle-stroke-color': 'rgba(90,210,255,.45)',
      'circle-stroke-opacity': 0.8,
    } });

  map.addSource('mil', { type: 'geojson', data: milFC() });
  map.addLayer({ id: 'mil-pt', type: 'circle', source: 'mil',
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'], 1, 2.6, 4, 4, 7, 6],
      'circle-color': 'rgba(255,140,60,.14)',
      'circle-stroke-width': 1.1,
      'circle-stroke-color': '#ff9c4a',
      'circle-stroke-opacity': 0.9,
    } });
  map.addLayer({ id: 'fl-em', type: 'circle', source: 'flights',
    filter: ['in', ['get', 'q'], ['literal', ['7700', '7600', '7500']]],
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'], 1, 3, 5, 6],
      'circle-color': '#ff5040', 'circle-opacity': 0.9,
      'circle-stroke-width': 1, 'circle-stroke-color': 'rgba(255,179,168,.8)',
    } });
}

function setFlightFilter() {
  if (!map.getLayer('fl-air')) return;
  const base = ['!', ['in', ['get', 'q'], ['literal', ['7700', '7600', '7500']]]];
  const z = map.getZoom();
  ['tr-line', 'fc-line'].forEach((id) => {
    if (map.getLayer(id)) {
      map.setLayoutProperty(id, 'visibility',
        (z > 2.6 && document.getElementById('l-flights').checked) ? 'visible' : 'none');
    }
  });
  // 分级采样:全球看分布,区域看密度,近景看全部
  if (z < 2.8) map.setFilter('fl-air', ['all', base, ['==', ['get', 's'], 1]]);
  else if (z < 4.6) map.setFilter('fl-air', ['all', base, ['<', ['%', ['get', 'i'], 2], 1]]);
  else map.setFilter('fl-air', base);
}

function startFlights() {
  map.on('zoomend', setFlightFilter);
  const tick = () => {
    const src = map.getSource('flights');
    if (!src) return;
    if (!document.getElementById('l-flights').checked) return;
    const fc = flightFC();
    src.setData(fc);
    const msrc = map.getSource('mil');
    if (msrc) msrc.setData(milFC());
    const tsrc = map.getSource('trails');
    if (tsrc) tsrc.setData(trailFC());
    const fsrc = map.getSource('forecast');
    if (fsrc) fsrc.setData(forecastFC());
    window.__flt = { n: (window.__flt ? window.__flt.n : 0) + 1,
      p: fc.features.length ? fc.features[0].geometry.coordinates : null };
  };
  tick();
  if (FL.timer) clearInterval(FL.timer);
  FL.timer = setInterval(tick, 2500);
}

const SAT = { items: [], timer: null };
const SATC = { stations: '#eaf4ff', 'gps-ops': '#ffd166', weather: '#6fd3ff',
  starlink: '#b9e6ff', visual: '#ffd9a8', science: '#a9ffd0' };

function initSats(data) {
  SAT.items = (data.satellites || []).map((s) => {
    try { return { n: s.n, g: s.g, rec: satellite.twoline2satrec(s.l1, s.l2) }; }
    catch (e) { return null; }
  }).filter(Boolean);
}

function satFC() {
  const now = new Date();
  const gmst = satellite.gstime(now);
  const feats = [];
  SAT.items.forEach((s) => {
    const pv = satellite.propagate(s.rec, now);
    if (!pv || !pv.position) return;
    const g = satellite.eciToGeodetic(pv.position, gmst);
    const lon = satellite.degreesLong(g.longitude);
    const lat = satellite.degreesLat(g.latitude);
    if (!isFinite(lon) || !isFinite(lat)) return;
    feats.push({ type: 'Feature', geometry: { type: 'Point', coordinates: [lon, lat] },
      properties: { n: s.n, g: s.g, h: Math.round(g.height) } });
  });
  return { type: 'FeatureCollection', features: feats };
}

function satFilter() {
  if (!document.getElementById('l-sat').checked) return ['==', ['get', 'g'], '__off'];
  const on = ['stations', 'visual', 'science'];
  if (document.getElementById('l-sat-gps').checked) on.push('gps-ops');
  if (document.getElementById('l-sat-wx').checked) on.push('weather');
  if (document.getElementById('l-sat-sx').checked) on.push('starlink');
  return ['in', ['get', 'g'], ['literal', on]];
}

const ISSK = ['case', ['==', ['get', 'n'], 'ISS (ZARYA)'], 1.9, ['==', ['get', 'n'], 'CSS (TIANHE)'], 1.9, 1];

function addSats() {
  map.addSource('sats', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
  map.addLayer({ id: 'sat-glow', type: 'circle', source: 'sats',
    filter: ['!=', ['get', 'g'], 'starlink'],
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'],
        1, ['*', 4, ISSK], 4, ['*', 9, ISSK], 7, ['*', 15, ISSK]],
      'circle-color': ['match', ['get', 'g'], 'stations', SATC.stations, 'gps-ops', SATC['gps-ops'], 'weather', SATC.weather, '#9fb6cc'],
      'circle-opacity': 0.14, 'circle-blur': 1.1,
    } });
  map.addLayer({ id: 'sat-starlink', type: 'circle', source: 'sats',
    filter: ['==', ['get', 'g'], 'starlink'],
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'], 1, 0.72, 4, 1.05, 7, 1.5],
      'circle-color': SATC.starlink,
      // 星链是星座结构,低缩放看带、放大后让位给态势
      'circle-opacity': ['interpolate', ['linear'], ['zoom'], 1, 0.20, 2.6, 0.18, 3.4, 0.08, 4.2, 0],
    } });
  map.addLayer({ id: 'sat-dot', type: 'circle', source: 'sats',
    filter: ['!=', ['get', 'g'], 'starlink'],
    paint: {
      'circle-radius': ['interpolate', ['linear'], ['zoom'],
        1, ['*', 1.3, ISSK], 4, ['*', 2.4, ISSK], 7, ['*', 3.6, ISSK]],
      'circle-color': ['match', ['get', 'g'], 'stations', SATC.stations, 'gps-ops', SATC['gps-ops'], 'weather', SATC.weather, 'visual', SATC.visual, 'science', SATC.science, '#9fb6cc'],
      'circle-opacity': 0.95,
      'circle-stroke-width': 0.5, 'circle-stroke-color': 'rgba(255,255,255,.55)',
    } });
}

const SAT_TAGS = [['ISS (ZARYA)', 'ISS'], ['CSS (TIANHE)', '天宫']];
const TAG_MK = {};

function startSats() {
  const tick = () => {
    const on = document.getElementById('l-sat').checked;
    Object.values(TAG_MK).forEach((m) => { m.getElement().style.display = on ? '' : 'none'; });
    const src = map.getSource('sats');
    if (!src || !on) return;
    const fc = satFC();
    src.setData(fc);
    SAT_TAGS.forEach(([id, tag]) => {
      const f = fc.features.find((x) => x.properties.n === id);
      if (!TAG_MK[id]) {
        if (!f) return;
        const el = document.createElement('div');
        el.className = 'satiss';
        el.textContent = tag;
        TAG_MK[id] = new maplibregl.Marker({ element: el, anchor: 'left', offset: [7, 0] })
          .setLngLat(f.geometry.coordinates).addTo(map);
      }
      if (f) { TAG_MK[id].setLngLat(f.geometry.coordinates); TAG_MK[id].getElement().style.display = ''; }
      else TAG_MK[id].getElement().style.display = 'none';
    });
  };
  tick();
  if (SAT.timer) clearInterval(SAT.timer);
  SAT.timer = setInterval(tick, 2000);
}

function applyBasemode(m) {
  const night = m === 'night', relief = m === 'relief';
  if (map.getLayer('base-night')) map.setLayoutProperty('base-night', 'visibility', night ? 'visible' : 'none');
  // 真彩底图有轨道缝隙,垫一层晕渲,缝里露地表而不是黑洞
  if (map.getLayer('base-relief')) map.setLayoutProperty('base-relief', 'visibility', relief ? 'visible' : 'none');
  if (map.getLayer('ocean')) map.setLayoutProperty('ocean', 'visibility', m === 'plain' ? 'visible' : 'none');
  if (map.getLayer('c-fill')) {
    map.setPaintProperty('c-fill', 'fill-opacity', m === 'plain'
      ? ['case', ['==', ['get', 'p'], null], 0.95,
          ['interpolate', ['linear'], ['get', 'p'], 0, 0.34, 1, 0.66]]
      : ['case', ['==', ['get', 'p'], null], 0.05,
          ['interpolate', ['linear'], ['get', 'p'], 0, 0, 0.4, 0.02, 0.68, 0.14, 1, 0.30]]);
  }
  document.querySelectorAll('#basemode .chip').forEach((c) => c.classList.toggle('on', c.dataset.m === m));
}

function addLabels() {
  LABELS.forEach(([name, lon, lat]) => {
    const el = document.createElement('div');
    el.className = 'cty';
    el.textContent = name;
    const mk = new maplibregl.Marker({ element: el, anchor: 'center' })
      .setLngLat([lon, lat]).addTo(map);
    state.markers.push(mk);
  });
  const style = document.createElement('style');
  style.textContent = `.cty{display:none}.cty.on{display:block}.cty2{display:none}.cty2.on{display:block}
    .cty{font-size:9px;letter-spacing:.16em;color:rgba(150,185,220,.42);
    text-shadow:0 0 6px rgba(4,7,12,.9);pointer-events:none;white-space:nowrap;
    font-family:-apple-system,"PingFang SC",sans-serif}`;
  document.head.appendChild(style);
  updateLabelOpacity();
}

function applyPadding() {
  const w = window.innerWidth;
  if (w < 1180) { map.setPadding({ left: 0, right: 0, top: 60, bottom: 10 }); return; }
  map.setPadding({ left: 286, right: 396, top: 68, bottom: 26 });
}

function bindRegions() {
  $('regions').innerHTML = REGIONS.map(([n]) =>
    `<div class="reg${n === state.region ? ' on' : ''}" data-n="${n}">${n}</div>`).join('');
  document.querySelectorAll('.reg').forEach((el) => {
    el.addEventListener('click', () => {
      const r = REGIONS.find((x) => x[0] === el.dataset.n);
      state.region = r[0];
      document.querySelectorAll('.reg').forEach((x) => x.classList.toggle('on', x === el));
      spinning = false;
      map.flyTo({ center: [r[1], r[2]], zoom: r[3], duration: 1700, essential: true });
    });
  });
  $('ramp-max').textContent = (state.summary.all_countries[0].epi / 1000).toFixed(1) + 'k';
}

/** 最新、最重的事件打脉冲环,让画面有"正在发生"的动感 */
function refreshPulses() {
  state.pulses.forEach((m) => m.remove());
  state.pulses = [];
  const cut = Date.now() / 1000 - state.hours * 3600;
  const list = state.events
    .filter((p) => Date.parse(p.ts) / 1000 >= cut)
    .slice()
    .sort((a, b) => (b.w || 0) - (a.w || 0))
    .slice(0, 14);
  list.forEach((p) => {
    const k = GROUP[p.cat] || 'diplo';
    const el = document.createElement('div');
    el.className = 'pmark';
    el.style.setProperty('--c', COLOR[k]);
    el.innerHTML = '<i></i>';
    state.pulses.push(new maplibregl.Marker({ element: el }).setLngLat([p.lon, p.lat]).addTo(map));
  });
}

/** 国家尺度注记:按国界质心生成,放大到国家层级才显示 */
function addCountryLabels() {
  state.cLabels.forEach((m) => m.remove());
  state.cLabels = [];
  const style = document.createElement('style');
  style.textContent = `.cty2{font-size:10px;letter-spacing:.1em;color:rgba(178,205,232,.62);
    text-shadow:0 0 7px rgba(4,7,12,.95);pointer-events:none;white-space:nowrap;
    font-family:-apple-system,"PingFang SC",sans-serif}`;
  document.head.appendChild(style);
  const seen = new Set();
  state.countries.features.forEach((f) => {
    const p = f.properties;
    if (!p.fips || p.cx == null) return;
    const nm = p.cn || p.NAME;
    if (seen.has(nm)) return;
    seen.add(nm);
    const el = document.createElement('div');
    el.className = 'cty2';
    el.textContent = p.cn || p.NAME;
    // 粗略面积:经度跨度 × cos(纬度) × 纬度跨度,用来滤掉小国标签
    let span = 0;
    try {
      const c = f.geometry.coordinates;
      const rings = f.geometry.type === 'Polygon' ? c : c.flat();
      let x0 = 180, x1 = -180, y0 = 90, y1 = -90;
      rings.forEach((r) => r.forEach(([x, y]) => {
        if (x < x0) x0 = x; if (x > x1) x1 = x;
        if (y < y0) y0 = y; if (y > y1) y1 = y;
      }));
      span = (x1 - x0) * Math.cos((Math.max(Math.abs(y0), Math.abs(y1)) * Math.PI) / 180) * (y1 - y0);
    } catch (e) { span = 0; }
    el.dataset.span = span.toFixed(1);
    state.cLabels.push(new maplibregl.Marker({ element: el, anchor: 'center' })
      .setLngLat([p.cx, p.cy]).addTo(map));
  });
}

function updateLabelOpacity() {
  const on = $('l-label').checked;
  const z = map.getZoom();
  const coarse = on && z > 2.05 && z <= 3.3;
  const fine = on && z > 3.3;
  state.markers.forEach((m) => m.getElement().classList.toggle('on', coarse));
  (state.cLabels || []).forEach((m) => {
    const el = m.getElement();
    const span = Number(el.dataset.span || 0);
    const big = z > 4.4 || span > (z > 3.9 ? 5 : 16);
    el.classList.toggle('on', fine && big);
  });
}

/* ---------------- 过滤 ---------------- */
const timeCond = () => ['>=', ['get', 'ts'], Date.now() / 1000 - state.hours * 3600];

function refreshFilters() {
  // 气候层
  const cd = [];
  if ($('l-cdhe').checked) cd.push(3);
  if ($('l-dry').checked) cd.push(1);
  if ($('l-hot').checked) cd.push(2);
  // 每层只显示自己的状态;状态未开启时给一个不可能条件
  const stateLayer = { 1: 'cdhe-h1', 2: 'cdhe-h2', 3: 'cdhe-h3' };
  Object.entries(stateLayer).forEach(([k, id]) => {
    if (!map.getLayer(id)) return;
    map.setFilter(id, cd.includes(Number(k))
      ? ['==', ['get', 's'], Number(k)]
      : ['==', ['get', 's'], -1]);
  });
  const cf = cd.length ? ['in', ['get', 's'], ['literal', cd]] : ['==', ['get', 's'], -1];
  if (map.getLayer('cdhe-pts')) map.setFilter('cdhe-pts', cf);

  // 事件层
  const on = [];
  if ($('l-viol').checked) on.push('conflict');
  if ($('l-mil').checked) on.push('mil');
  if ($('l-protest').checked) on.push('social');
  if ($('l-diplo').checked) on.push('diplo');
  if ($('l-coop').checked) on.push('coop');
  const base = ['all', timeCond(), ['in', ['get', 'grp'], ['literal', on]]];
  ['ev-conflict', 'ev-mil', 'ev-social', 'ev-diplo', 'ev-coop']
    .forEach((id) => map.setFilter(id, base));

  const q = $('l-quake').checked ? ['all', timeCond(), ['==', ['get', 'cat'], '地震']]
    : ['==', ['get', 'cat'], '__none'];
  const n = $('l-nature').checked ? ['all', timeCond(), ['==', ['get', 'cat'], '自然事件']]
    : ['==', ['get', 'cat'], '__none'];
  map.setFilter('ev-quake', q);
  map.setFilter('ev-nature', n);

  map.setLayoutProperty('c-line', 'visibility', $('l-border').checked ? 'visible' : 'none');
  map.setLayoutProperty('c-glow', 'visibility', $('l-border').checked ? 'visible' : 'none');
  map.setLayoutProperty('grat', 'visibility', $('l-grat').checked ? 'visible' : 'none');
  if (map.getLayer('c-fill')) {
    map.setLayoutProperty('c-fill', 'visibility',
      document.getElementById('l-epi').checked ? 'visible' : 'none');
  }
  DIS.forEach(([id, types]) => {
    const on = types.some((t) => {
      const el = document.getElementById(DIS_TOG[t]);
      return el && el.checked;
    });
    map.setFilter(id, on ? ['in', ['get', 'et'], ['literal', types]] : ['==', ['get', 'et'], '__off']);
  });
  ['fire-heat', 'fire-pt'].forEach((id) => {
    if (map.getLayer(id)) map.setLayoutProperty(id, 'visibility',
      document.getElementById('l-fires').checked ? 'visible' : 'none');
  });
  ['mil-pt'].forEach((id) => {
    if (map.getLayer(id)) {
      map.setLayoutProperty(id, 'visibility',
        document.getElementById('l-mil').checked ? 'visible' : 'none');
    }
  });
  ['fl-air', 'fl-em'].forEach((id) => {
    if (map.getLayer(id)) {
      map.setLayoutProperty(id, 'visibility',
        document.getElementById('l-flights').checked ? 'visible' : 'none');
    }
  });
  setFlightFilter();
  const sf = satFilter();
  if (map.getLayer('sat-glow')) map.setFilter('sat-glow', sf);
  if (map.getLayer('sat-dot')) map.setFilter('sat-dot', ['all', sf, ['!=', ['get', 'g'], 'starlink']]);
  if (map.getLayer('sat-starlink')) map.setFilter('sat-starlink', ['all', sf, ['==', ['get', 'g'], 'starlink']]);
  updateLabelOpacity();
  renderFeed();
}

function bindToggles() {
  document.querySelectorAll('.left input[type=checkbox]').forEach((el) =>
    el.addEventListener('change', refreshFilters));
  document.querySelectorAll('#chips .chip').forEach((c) =>
    c.addEventListener('click', () => {
      state.hours = Number(c.dataset.h);
      document.querySelectorAll('#chips .chip').forEach((x) => x.classList.toggle('on', x === c));
      refreshFilters();
      renderFeed();
      refreshPulses();
    }));
  document.querySelectorAll('#basemode .chip').forEach((c) =>
    c.addEventListener('click', () => applyBasemode(c.dataset.m)));
  document.querySelectorAll('#basetog .chip, #distog .chip, #movetog .chip').forEach((c) =>
    c.addEventListener('click', () => {
      const box = document.getElementById(c.dataset.for);
      if (!box) return;
      box.checked = !box.checked;
      c.classList.toggle('on', box.checked);
      refreshFilters();
    }));
}

/* ---------------- 面板 ---------------- */
function renderTop() {
  const s = state.summary;
  const total = s.series.reduce((a, b) => a + b.n, 0);
  const epi = s.series.reduce((a, b) => a + b.epi, 0);
  const cty = (s.frames[0] && s.frames[0].c) || s.countries;
  const cd = state.cdhe;
  const comp = cd.points.filter((p) => p[2] === 3).length;
  const frac = (comp / (cd.land || 3435)) * 100;

  $('h-events').textContent = total.toLocaleString();
  $('h-countries').textContent = cty;
  $('h-news').textContent = (state.news || []).length;
  $('h-cdhe').innerHTML = frac.toFixed(1) + '<em>%</em>';
  const fEl = $('h-fire'), dEl = $('h-dis');
  if (fEl) fEl.textContent = (state.fires.features || []).length.toLocaleString();
  if (dEl) dEl.textContent = (state.disasters || []).length;
  $('h-gen').textContent = s.generated.slice(11, 16) + 'Z';

  $('k-epi').textContent = fmt(Math.round(epi));
  $('k-total').textContent = total.toLocaleString() + ' 条';

  // 15 分钟变化
  const f = s.frames;
  if (f.length > 1) {
    const d = f[0].epi - f[1].epi;
    const pc = f[1].epi ? (d / f[1].epi) * 100 : 0;
    const cls = d >= 0 ? 'up' : 'dn';
    $('k-trend').innerHTML =
      `<b class="${cls}">${d >= 0 ? '+' : ''}${Math.round(d)}</b>较上一帧`;
  }
  $('k-frames').textContent = f.length + ' 帧';

  // 左栏计数
  const g = { conflict: 0, mil: 0, social: 0, diplo: 0, coop: 0, quake: 0, nature: 0 };
  s.categories.forEach((c) => { const k = GROUP[c.cat]; if (g[k] != null) g[k] += c.n; });
  $('n-viol').textContent = fmt(g.conflict + g.mil);
  $('n-soc').textContent = fmt(g.social + g.diplo + g.coop);
  $('n-quake').textContent = g.quake + g.nature;
  $('n-cdhe').textContent = comp;
  $('cdhe-month').textContent = `${cd.year}-${String(cd.month).padStart(2, '0')}`;
}

const BUCKETS = [
  ['冲突袭击', 'conflict', ['大规模暴力', '武装冲突', '武装袭击']],
  ['军事胁迫', 'mil', ['军事部署', '胁迫', '威胁制裁']],
  ['社会动荡', 'social', ['抗议骚乱', '政治施压', '减少关系']],
  ['外交政治', 'diplo', ['外交协商', '外交表态', '调查', '其他']],
  ['合作援助', 'coop', ['物质合作', '提供援助', '让步妥协']],
  ['灾害', 'quake', ['地震', '自然事件']],
];

function renderBars() {
  const cats = state.summary.categories;
  const byCat = new Map(cats.map((c) => [c.cat, c.n]));
  const rows = BUCKETS.map(([nm, k, list]) => ({
    nm, k, n: list.reduce((a, c) => a + (byCat.get(c) || 0), 0),
  })).filter((r) => r.n > 0).sort((x, y) => y.n - x.n);
  const max = Math.max(...rows.map((r) => r.n), 1);
  const sum = rows.reduce((a, r) => a + r.n, 0);

  $('bars').innerHTML = rows.map((r) =>
    `<div class="bar"><span class="nm">${r.nm}</span>
      <span class="tr"><span class="fl" style="width:${(r.n / max) * 100}%;background:${COLOR[r.k]}"></span></span>
      <span class="v">${((r.n / sum) * 100).toFixed(0)}%</span></div>`).join('');
}

/* 压力色阶:低=蓝 中=黄 高=红,和地图的 choropleth 同一套语义 */
function rampColor(t) {
  const stops = [[63, 169, 255], [255, 209, 102], [255, 90, 74]];
  const x = Math.max(0, Math.min(0.999, t));
  const i = x < 0.5 ? 0 : 1;
  const f = (x - i * 0.5) / 0.5;
  const c = stops[i].map((v, k) => Math.round(v + (stops[i + 1][k] - v) * f));
  return `rgb(${c[0]},${c[1]},${c[2]})`;
}

function renderRank() {
  const key = state.rank || 'epi';
  const list = (state.summary.all_countries || [])
    .slice().sort((a, b) => (b[key] || 0) - (a[key] || 0)).slice(0, 14);
  const max = Math.max(1, list[0] ? list[0][key] : 1);
  const note = document.getElementById('rnote');
  if (note) {
    note.textContent = key === 'cepi'
      ? '冲突 = 武装袭击 + 大规模暴力 + 军事部署(24h)'
      : 'EPI = Σ 类别权重 × 事件数(24h)';
  }
  $('rank').innerHTML = list.map((c, i) => `
    <div class="rk" data-f="${c.f}" title="飞到 ${c.cc}">
      <span class="i">${String(i + 1).padStart(2, '0')}</span>
      <span class="nm">${c.cc}</span>
      <span class="tr"><span class="fl" style="width:${((c[key] || 0) / max) * 100}%;
        background:${rampColor((c[key] || 0) / max)}"></span></span>
      <span class="v">${Math.round(c[key] || 0).toLocaleString()}</span></div>`).join('');

  document.querySelectorAll('.rk').forEach((el) => {
    el.addEventListener('click', () => {
      const f = el.dataset.f;
      const feat = state.countries.features.find((x) => x.properties.fips === f);
      if (!feat) return;
      const { cx, cy } = feat.properties;
      if (cx == null) return;
      spinning = false;
      map.flyTo({ center: [cx, cy], zoom: 3.9, duration: 1500, essential: true });
    });
  });
}

function renderSpark() {
  const cv = $('spark');
  const dpr = window.devicePixelRatio || 1;
  const w = cv.clientWidth || 340, h = 46;
  cv.width = w * dpr; cv.height = h * dpr;
  const ctx = cv.getContext('2d');
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.clearRect(0, 0, w, h);

  const fr = state.summary.frames.slice().reverse();
  if (!fr.length) return;
  const vals = fr.map((f) => f.n);
  const max = Math.max(...vals), min = Math.min(...vals);
  const pad = 4, top = 12, bot = h - 3;
  const n = vals.length;

  // 网格
  ctx.strokeStyle = 'rgba(126,163,201,.10)';
  ctx.lineWidth = 1;
  for (let i = 0; i <= 2; i++) {
    const y = top + ((bot - top) / 2) * i;
    ctx.beginPath(); ctx.moveTo(0, y + .5); ctx.lineTo(w, y + .5); ctx.stroke();
  }

  // 面积
  const X = (i) => pad + (i * (w - pad * 2)) / Math.max(1, n - 1);
  const Y = (v) => bot - ((v - min) / Math.max(1, max - min)) * (bot - top);
  const grad = ctx.createLinearGradient(0, top, 0, bot);
  grad.addColorStop(0, 'rgba(90,210,255,.42)');
  grad.addColorStop(1, 'rgba(90,210,255,.02)');
  ctx.beginPath();
  ctx.moveTo(X(0), bot);
  vals.forEach((v, i) => ctx.lineTo(X(i), Y(v)));
  ctx.lineTo(X(n - 1), bot);
  ctx.closePath();
  ctx.fillStyle = grad;
  ctx.fill();

  // 折线
  ctx.beginPath();
  vals.forEach((v, i) => (i ? ctx.lineTo(X(i), Y(v)) : ctx.moveTo(X(i), Y(v))));
  ctx.strokeStyle = 'rgba(90,210,255,.9)';
  ctx.lineWidth = 1.2;
  ctx.stroke();

  // 末点
  ctx.beginPath();
  ctx.arc(X(n - 1), Y(vals[n - 1]), 2.2, 0, Math.PI * 2);
  ctx.fillStyle = '#e9f6ff'; ctx.fill();
  ctx.strokeStyle = 'rgba(90,210,255,.8)'; ctx.lineWidth = 1; ctx.stroke();

  // 标注
  ctx.font = '9px ui-monospace,Menlo,monospace';
  ctx.fillStyle = 'rgba(95,113,137,.9)';
  ctx.fillText('峰值 ' + max.toLocaleString(), 2, 9);
}

const ccName = (s) => (s && s.length <= 3 && state.nameOf && state.nameOf.has(s))
  ? state.nameOf.get(s) : s;

const loc = (s) => {
  if (!s) return '—';
  const parts = s.split(',').map((x) => x.trim()).filter(Boolean);
  const out = [];
  parts.forEach((p) => { if (!out.includes(p)) out.push(p); });
  return out.join(' · ');
};

const NCAT = { 冲突: '#ff6b5a', 灾害: '#ffb454', 气候: '#b98cff', 外交: '#7f93ad',
  社会: '#56a8ff', 经济: '#d9c85c', 其他: '#5f7189' };

function renderFeed() {
  if (state.feed === 'news') return renderNews();
  const cut = Date.now() / 1000 - state.hours * 3600;
  const seen = new Set();
  const list = state.events
    .filter((p) => Date.parse(p.ts) / 1000 >= cut)
    .filter((p) => {
      const k = (p.title || '') + '|' + (p.cc || '');
      if (seen.has(k)) return false;
      seen.add(k); return true;
    })
    .slice(0, 70);
  state.feedList = list;

  const note = `<div class="fnote">GDELT 导出表不含新闻标题,此视图为地理编码的地点 · 点开可看原文</div>`;
  $('feed').innerHTML = note + (list.map((p, i) => {
    const k = GROUP[p.cat] || 'diplo';
    const d = domain(p.url);
    const tm = new Date(p.ts);
    const hh = String(tm.getHours()).padStart(2, '0') + ':' + String(tm.getMinutes()).padStart(2, '0');
    return `<div class="ev" data-i="${i}" style="--c:${COLOR[k]}">
      <div class="m1"><span class="c">${NAME[k]}</span><span>${ccName(p.cc)}</span><span class="t">${hh}</span></div>
      <div class="tt">${loc(p.title)}</div>
      <div class="m2">${p.m} 提及 · 语气 ${p.t != null ? Number(p.t).toFixed(1) : '—'} · ${d || 'GDELT'}</div>
    </div>`;
  }).join('')) || '<div style="color:#3d4c60;padding:16px 2px;font-size:11px">该时间窗内无可展示事件</div>';
  feedStamp();

  document.querySelectorAll('#feed .ev').forEach((el) => {
    el.addEventListener('click', () => {
      const p = list[Number(el.dataset.i)];
      map.flyTo({ center: [p.lon, p.lat], zoom: 3.9, duration: 1300 });
      showPopup(p);
    });
  });
}

function agoText(ts) {
  const m = Math.max(0, Math.round((Date.now() / 1000 - ts) / 60));
  if (m < 1) return '刚刚';
  return m < 60 ? m + ' 分钟前' : Math.round(m / 60) + ' 小时前';
}

function feedStamp() {
  const el = document.getElementById('feed-upd');
  if (!el) return;
  const d = new Date();
  el.textContent = String(d.getHours()).padStart(2, '0') + ':' +
    String(d.getMinutes()).padStart(2, '0') + ' 更新';
}

function markNew(topKey) {
  const first = document.querySelector('#feed .ev');
  if (!first) return;
  if (state.feedTop && topKey && topKey !== state.feedTop) {
    first.classList.add('new');
    setTimeout(() => first.classList.remove('new'), 1200);
  }
  if (topKey) state.feedTop = topKey;
}

function renderNews() {
  const list = (state.news || []).slice(0, 80);
  $('feed').innerHTML = list.map((n) => {
    const c = NCAT[n.cat] || NCAT['其他'];
    return `<div class="ev" data-u="${encodeURIComponent(n.u)}" style="--c:${c}">
      <div class="m1"><span class="c">${n.cat}</span><span>${n.src}</span>
        <span class="t" data-rel="1" data-ts="${n.ts}">${agoText(n.ts)}</span></div>
      <div class="tt">${n.t}</div>
    </div>`;
  }).join('') || '<div style="color:#3d4c60;padding:16px 2px;font-size:11px">暂无要闻</div>';

  document.querySelectorAll('#feed .ev').forEach((el) => {
    el.addEventListener('click', () => window.open(decodeURIComponent(el.dataset.u), '_blank', 'noopener'));
  });
  feedStamp();
  markNew('n:' + (list[0] ? list[0].t : ''));
}

function bindRankTabs() {
  document.querySelectorAll('#rankTabs b').forEach((b) => {
    b.addEventListener('click', () => {
      state.rank = b.dataset.v;
      document.querySelectorAll('#rankTabs b').forEach((x) => x.classList.toggle('on', x === b));
      renderRank();
    });
  });
}

function bindFeedTabs() {
  document.querySelectorAll('#feedTabs b').forEach((b) => {
    b.addEventListener('click', () => {
      state.feed = b.dataset.v;
      document.querySelectorAll('#feedTabs b').forEach((x) => x.classList.toggle('on', x === b));
      renderFeed();
    });
  });
}

function showPopup(p) {
  const k = GROUP[p.cat] || 'diplo';
  const c = COLOR[k];
  const html = `<div class="pop" style="--c:${c}">
    <div><b>${p.cat}</b> · ${ccName(p.cc)}</div>
    <div class="k"><span>提及 <b>${p.m}</b></span><span>语气 <b>${p.t != null ? Number(p.t).toFixed(2) : '—'}</b></span></div>
    ${p.title ? `<div class="ti">${p.title}</div>` : ''}
    ${p.url ? `<div style="margin-top:5px"><a href="${p.url}" target="_blank" rel="noopener">${domain(p.url)}</a></div>` : ''}
  </div>`;
  new maplibregl.Popup({ closeButton: false, maxWidth: '290px', offset: 10 })
    .setLngLat([p.lon, p.lat]).setHTML(html).addTo(map);
}

/* ---------------- 交互 ---------------- */
function flightPos(r) {
  const now = Date.now() / 1000;
  const dt = Math.min(Math.max(now - FL.t0, 0), 1800);
  const rad = (r[4] * Math.PI) / 180;
  const lat = r[1] + (r[3] * Math.cos(rad) * dt) / 111320;
  const cosLat = Math.cos((lat * Math.PI) / 180) || 0.01;
  let lon = r[0] + (r[3] * Math.sin(rad) * dt) / (111320 * cosLat);
  if (lon > 180) lon -= 360;
  if (lon < -180) lon += 360;
  return [lon, lat];
}

/* 选中一架飞机:卡片 + 跟随 */
let FOLLOW = null;
function selectFlight(hexid) {
  const r = FL.rows.find((x) => x[7] === hexid);
  if (!r) return;
  FL.sel = hexid;
  const card = document.getElementById('flcard');
  card.classList.add('on');
  document.getElementById('fc-cs').textContent = r[5] || hexid.toUpperCase();
  document.getElementById('fc-ty').textContent = airlineOf(r[5]) || r[6] || '';
  document.getElementById('fc-alt').textContent = Math.round(r[2]) + ' m';
  document.getElementById('fc-spd').textContent = Math.round(r[3] * 3.6) + ' km/h';
  document.getElementById('fc-hdg').textContent = Math.round(r[4]) + '°';
  document.getElementById('fc-hex').textContent = hexid.toUpperCase();
  const p = flightPos(r);
  if (map.getSource('sel')) {
    map.getSource('sel').setData({ type: 'FeatureCollection', features: [
      { type: 'Feature', geometry: { type: 'Point', coordinates: p }, properties: {} }] });
  }
  map.easeTo({ center: p, zoom: Math.max(map.getZoom(), 4.2), duration: 900 });
  FOLLOW = hexid;
  const fsrc = map.getSource('forecast');
  if (fsrc) fsrc.setData(forecastFC());
  spinning = false;
}

function clearFlight() {
  FL.sel = null; FOLLOW = null;
  document.getElementById('flcard').classList.remove('on');
  if (map.getSource('sel')) {
    map.getSource('sel').setData({ type: 'FeatureCollection', features: [] });
  }
  const fsrc = map.getSource('forecast');
  if (fsrc) fsrc.setData({ type: 'FeatureCollection', features: [] });
}

function bindMap() {
  map.on('click', 'fl-air', (e) => {
    const f = e.features && e.features[0];
    if (f) selectFlight(f.properties.h || f.properties.c);
  });
  document.getElementById('fc-x').addEventListener('click', clearFlight);
  setInterval(() => {
    if (!FOLLOW) return;
    const r = FL.rows.find((x) => x[7] === FOLLOW);
    if (!r) { clearFlight(); return; }
    const p = flightPos(r);
    document.getElementById('fc-alt').textContent = Math.round(r[2]) + ' m';
    document.getElementById('fc-spd').textContent = Math.round(r[3] * 3.6) + ' km/h';
    document.getElementById('fc-hdg').textContent = Math.round(r[4]) + '°';
    map.jumpTo({ center: p });
    if (map.getSource('sel')) {
      map.getSource('sel').setData({ type: 'FeatureCollection', features: [
        { type: 'Feature', geometry: { type: 'Point', coordinates: p }, properties: {} }] });
    }
  }, 2500);

  ['ev-conflict', 'ev-mil', 'ev-social', 'ev-diplo', 'ev-coop', 'ev-quake', 'ev-nature']
    .forEach((id) => {
      map.on('click', id, (e) => {
        const f = e.features[0];
        showPopup({ lon: f.geometry.coordinates[0], lat: f.geometry.coordinates[1], ...f.properties });
      });
      map.on('mouseenter', id, () => { map.getCanvas().style.cursor = 'pointer'; });
      map.on('mouseleave', id, () => { map.getCanvas().style.cursor = ''; });
    });
  map.on('mouseenter', 'fl-air', () => { map.getCanvas().style.cursor = 'pointer'; });
  map.on('mouseleave', 'fl-air', () => { map.getCanvas().style.cursor = ''; });
  map.on('click', (e) => {
    const hits = map.queryRenderedFeatures(e.point, { layers: ['fl-air', 'mil-pt'] });
    if (!hits.length) clearFlight();
  });
  window.addEventListener('keydown', (e) => { if (e.key === 'Escape') clearFlight(); });
  map.on('click', 'cdhe-pts', (e) => {
    const f = e.features[0];
    const s = f.properties.s;
    const nm = s === 3 ? '干热复合' : s === 2 ? '仅热' : '仅干';
    const c = CCOLOR[s] || '#888';
    new maplibregl.Popup({ closeButton: false, offset: 8 })
      .setLngLat(f.geometry.coordinates)
      .setHTML(`<div class="pop" style="--c:${c}"><div><b>${nm}</b></div>
        <div class="k"><span>SPI <b>${f.properties.spi}</b></span><span>STI <b>${f.properties.sti}</b></span></div>
        <div class="m2" style="color:#5f7189;font-size:10px;margin-top:4px;font-family:ui-monospace">
        ${state.cdhe.year}-${String(state.cdhe.month).padStart(2, '0')}</div></div>`)
      .addTo(map);
  });
  map.on('move', updateLabelOpacity);
}

function bindHover() {
  const cpop = new maplibregl.Popup({ closeButton: false, closeOnClick: false, offset: 9, maxWidth: '230px' });
  const epop = new maplibregl.Popup({ closeButton: false, closeOnClick: false, offset: 10, maxWidth: '260px' });
  let last = null;

  map.on('mousemove', 'c-fill', (e) => {
    const f = e.features && e.features[0];
    if (!f) return;
    if (last !== f.properties.FIPS_10) {
      last = f.properties.FIPS_10;
      const p = f.properties;
      const epi = p.epi ? Math.round(p.epi).toLocaleString() : '—';
      cpop.setLngLat(e.lngLat).setHTML(
        `<div class="pop" style="--c:#5ad2ff"><div><b>${p.cn || p.NAME}</b></div>
         <div class="k"><span>EPI <b>${epi}</b></span><span>事件 <b>${(p.n || 0).toLocaleString()}</b></span></div></div>`
      ).addTo(map);
    } else {
      cpop.setLngLat(e.lngLat);
    }
  });
  map.on('mouseout', 'c-fill', () => { last = null; cpop.remove(); });

  const ids = ['ev-conflict', 'ev-mil', 'ev-social', 'ev-diplo', 'ev-coop', 'ev-quake', 'ev-nature'];
  ids.forEach((id) => {
    map.on('mousemove', id, (e) => {
      const f = e.features && e.features[0];
      if (!f) return;
      const p = f.properties;
      const k = GROUP[p.cat] || 'diplo';
      cpop.remove();
      epop.setLngLat(e.lngLat).setHTML(
        `<div class="pop" style="--c:${COLOR[k]}"><div><b>${p.cat}</b> · ${ccName(p.cc)}</div>
         <div class="k"><span>提及 <b>${p.m}</b></span><span>语气 <b>${p.t != null ? Number(p.t).toFixed(1) : '—'}</b></span></div></div>`
      ).addTo(map);
    });
    map.on('mouseleave', id, () => epop.remove());
  });

  map.on('mousemove', 'cdhe-pts', (e) => {
    const f = e.features && e.features[0];
    if (!f) return;
    const s = f.properties.s;
    const nm = s === 3 ? '干热复合' : s === 2 ? '仅热' : '仅干';
    cpop.remove();
    epop.setLngLat(e.lngLat).setHTML(
      `<div class="pop" style="--c:${CCOLOR[s] || '#888'}"><div><b>${nm}</b></div>
       <div class="k"><span>SPI <b>${f.properties.spi}</b></span><span>STI <b>${f.properties.sti}</b></span></div></div>`
    ).addTo(map);
  });
  map.on('mouseleave', 'cdhe-pts', () => epop.remove());

  const dpop = new maplibregl.Popup({ closeButton: false, closeOnClick: false, offset: 9, maxWidth: '250px' });
  const AL_CN = { Red: '红色', Orange: '橙色', Green: '绿色' };
  const DCOL = { FL: '#3fa9ff', TC: '#35e0c8', DR: '#d9a52b', VO: '#b06ef0', WF: '#ff8a3d' };
  DIS.forEach(([id]) => {
    map.on('mousemove', id, (e) => {
      const f = e.features && e.features[0];
      if (!f) return;
      const p = f.properties;
      dpop.setLngLat(e.lngLat).setHTML(
        `<div class="pop" style="--c:${DCOL[p.et] || '#9fb6cc'}"><div><b>${p.cn}</b> · ${AL_CN[p.al] || p.al}预警</div>
         <div class="k"><span>${p.co || '—'}</span><span>等级 <b>${p.sc || 0}</b></span></div></div>`
      ).addTo(map);
    });
    map.on('mouseleave', id, () => dpop.remove());
  });

  map.on('mousemove', 'fire-pt', (e) => {
    const f = e.features && e.features[0];
    if (!f) return;
    dpop.setLngLat(e.lngLat).setHTML(
      `<div class="pop" style="--c:#ffb454"><div><b>火点</b> · MODIS 24h</div>
       <div class="k"><span>FRP <b>${Number(f.properties.f).toFixed(1)}</b> MW</span><span>簇 <b>${f.properties.n}</b> 点</span></div></div>`
    ).addTo(map);
  });
  map.on('mouseleave', 'fire-pt', () => dpop.remove());

  const mpop = new maplibregl.Popup({ closeButton: false, closeOnClick: false, offset: 10, maxWidth: '230px' });
  map.on('mousemove', 'mil-pt', (e) => {
    const f = e.features && e.features[0];
    if (!f) return;
    const p = f.properties;
    mpop.setLngLat(e.lngLat).setHTML(
      `<div class="pop" style="--c:#ff9c4a"><div><b>${p.c || '军机'}</b> · ${p.t || '—'}</div>
       <div class="k"><span>高度 <b>${Math.round(p.a / 30.48) * 100} ft</b></span><span>应答 <b>${p.h}</b></span></div></div>`
    ).addTo(map);
  });
  map.on('mouseleave', 'mil-pt', () => mpop.remove());

  const spop = new maplibregl.Popup({ closeButton: false, closeOnClick: false, offset: 8, maxWidth: '220px' });
  map.on('mousemove', 'sat-dot', (e) => {
    const f = e.features && e.features[0];
    if (!f) return;
    const p = f.properties;
    const nm = p.g === 'stations' ? '空间站/载人' : p.g === 'gps-ops' ? '导航星座' : '气象卫星';
    cpop.remove(); epop.remove();
    spop.setLngLat(e.lngLat).setHTML(
      `<div class="pop" style="--c:${SATC[p.g] || '#9fb6cc'}"><div><b>${p.n}</b></div>
       <div class="k"><span>${nm}</span><span>高度 <b>${p.h} km</b></span></div></div>`
    ).addTo(map);
  });
  map.on('mouseleave', 'sat-dot', () => spop.remove());
}

function clock() {
  const d = new Date();
  const p = (n) => String(n).padStart(2, '0');
  $('h-clock').textContent = `${p(d.getUTCHours())}:${p(d.getUTCMinutes())} UTC`;
}

/* 缓慢自转,交互即停 */
let spinning = true;
function spin() {
  if (!spinning) return;
  map.setBearing((map.getBearing() + 0.018) % 360);
  requestAnimationFrame(spin);
}
['mousedown', 'wheel', 'touchstart', 'dragstart'].forEach((ev) =>
  map.on(ev, () => { spinning = false; }));

/* ---------------- 启动 ---------------- */
async function loadAll() {
  const t = Date.now();
  const [sum, ev, cd, hl, satd, dis, fir, flt] = await Promise.all([
    fetch(DATA + 'summary.json?t=' + t).then((r) => r.json()),
    fetch(DATA + 'events.json?t=' + t).then((r) => r.json()),
    fetch(DATA + 'cdhe.json?t=' + t).then((r) => r.json()),
    fetch(DATA + 'headlines.json?t=' + t).then((r) => r.json()).catch(() => ({ items: [] })),
    fetch(DATA + 'satellites.json?t=' + t).then((r) => r.json()).catch(() => ({ satellites: [] })),
    fetch(DATA + 'disasters.json?t=' + t).then((r) => r.json()).catch(() => ({ events: [] })),
    fetch(DATA + 'fires.json?t=' + t).then((r) => r.json()).catch(() => ({ points: [] })),
    fetch(DATA + 'flights.json?t=' + t).then((r) => r.json()).catch(() => ({ flights: [] })),
  ]);
  state.summary = sum; state.events = ev.points; state.cdhe = cd;
  state.news = hl.items || [];
  state.disasters = (dis && dis.events) || [];
  state.fires = { type: 'FeatureCollection', features: ((fir && fir.points) || []).map((p) => ({
    type: 'Feature', geometry: { type: 'Point', coordinates: [p[0], p[1]] },
    properties: { f: p[2], n: p[3] } })) };
  const disEl = document.getElementById('n-dis');
  if (disEl) disEl.textContent = state.disasters.length + ' / ' + state.fires.features.length;
  if (satd && satd.satellites) initSats(satd);
  if (flt && flt.flights) initFlights(flt);
  const satEl = document.getElementById('n-sat');
  if (satEl) satEl.textContent = (SAT.items.length / 1000).toFixed(1) + 'k 星 / ' +
    (FL.rows.length / 1000).toFixed(1) + 'k 机';
  window.__state = state;
  if (!state.countries) {
    const gj = await fetch(DATA + 'countries.geojson').then((r) => r.json());
    state.countries = enrichCountries(gj);
  } else {
    state.countries = enrichCountries(state.countries);
  }
}

async function boot() {
  await loadAll();
  $('chips').innerHTML = [[3, '3H'], [12, '12H'], [24, '24H']]
    .map(([h, t]) => `<span class="chip${h === 24 ? ' on' : ''}" data-h="${h}">${t}</span>`).join('');

  renderTop(); renderBars(); renderRank(); renderSpark(); renderFeed(); bindRegions();
  clock(); setInterval(clock, 1000);

  const init = () => {
    applyGlobe();
    addLayers();
    applyBasemode(document.querySelector('#basemode .chip.on').dataset.m || 'relief');
    startSats();
    startFlights();
    bindToggles();
    addCountryLabels();
    bindMap();
    bindHover();
    bindFeedTabs();
    bindRankTabs();
    setInterval(() => {
      document.querySelectorAll('#feed .t[data-rel]').forEach((el) => {
        el.textContent = agoText(Number(el.dataset.ts));
      });
    }, 20000);
    refreshFilters();
    refreshPulses();
    applyPadding();
    requestAnimationFrame(spin);
  };
  if (map.isStyleLoaded()) init(); else map.once('load', init);

  // 要闻单独快轮询:2 分钟一次,有新条目就滑入
  setInterval(async () => {
    try {
      const r = await fetch(DATA + 'headlines.json?t=' + Date.now());
      const j = await r.json();
      if (j && j.items && j.items.length) {
        state.news = j.items;
        if (state.feed === 'news') renderNews();
      }
    } catch (e) { /* 静默 */ }
  }, 120000);

  setInterval(async () => {
    try {
      await loadAll();
      if (map.getSource('events')) map.getSource('events').setData(eventFeatures());
      if (map.getSource('cdhe')) map.getSource('cdhe').setData(cdheFeatures());
      if (map.getSource('disasters')) map.getSource('disasters').setData(disasterFC());
      if (map.getSource('fires')) map.getSource('fires').setData(state.fires);
      if (map.getSource('flights')) map.getSource('flights').setData(flightFC());
      if (map.getSource('mil')) map.getSource('mil').setData(milFC());
      renderTop(); renderRank(); renderSpark(); refreshFilters();
    } catch (e) { console.warn('刷新失败', e); }
  }, 300000);

  window.addEventListener('resize', () => { renderSpark(); applyPadding(); });
}

boot().catch((e) => {
  console.error(e);
  document.body.insertAdjacentHTML('beforeend',
    `<div style="position:absolute;inset:0;display:grid;place-items:center;color:#ff6b5a;
     font:12px ui-monospace;z-index:99">数据加载失败:${e.message}</div>`);
});