File size: 66,130 Bytes
96c4809
af80a89
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f7b386
96c4809
 
 
 
 
 
7f7b386
 
 
 
 
 
 
 
 
 
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f7b386
 
96c4809
 
 
 
 
 
 
 
 
 
797a0f7
7ef5dbf
 
797a0f7
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f7b386
96c4809
 
 
af80a89
 
 
96c4809
 
af80a89
 
96c4809
 
 
 
7f7b386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c56ec
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
af80a89
7ef5dbf
96c4809
af80a89
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c56ec
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c56ec
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c56ec
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af80a89
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a88bc
96c4809
 
 
 
 
f6a88bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c56ec
96c4809
 
 
 
f1c56ec
 
 
 
 
 
 
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6337791
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a88bc
 
 
 
96c4809
f6a88bc
 
 
 
 
 
 
 
 
 
 
96c4809
 
 
 
6337791
 
96c4809
 
 
 
 
 
f6a88bc
 
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6337791
96c4809
 
 
6337791
 
 
96c4809
 
 
 
 
 
6337791
96c4809
 
 
 
 
6337791
 
96c4809
 
 
6337791
 
96c4809
 
6337791
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6337791
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6337791
96c4809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2a6fba
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
<!DOCTYPE html>
<html lang="fr" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SenClim — climat &amp; prévisions du Sénégal</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
  :root, html[data-theme="light"]{
    --navy:#1c3a5e; --navy-dark:#152c48; --blue:#3b6ea5; --ink:#171d2e; --muted:#626c8c;
    --bg:#eef1f6; --panel:#ffffff; --panel-2:#f5f7fb; --line:#dbe0ec;
    --grey-band:#c7cbd6; --grey-line:#8a8f9c; --red:#c0392b; --amber:#c98a12; --teal:#1b8f7d;
  }
  html[data-theme="dark"]{
    --navy:#0f1c2e; --navy-dark:#0a1420; --blue:#5b9bd5; --ink:#eef1f6; --muted:#96a0bd;
    --bg:#10162b; --panel:#1a2138; --panel-2:#212a44; --line:#2c3552;
    --grey-band:#3a4260; --grey-line:#7c88ab; --red:#e0725a; --amber:#e0b64e; --teal:#4fc3ac;
  }
  *{box-sizing:border-box;margin:0;padding:0;}
  html,body{background:var(--bg);color:var(--ink);font-family:'Inter',sans-serif;min-height:100vh;transition:background .2s,color .2s;}
  a{color:var(--blue);}
  .wrap{max-width:1760px;margin:0 auto;padding:0 24px;}

  header.nav{background:var(--navy);color:#fff;}
  .nav-inner{max-width:1320px;margin:0 auto;padding:14px 24px;display:flex;align-items:center;gap:22px;flex-wrap:wrap;justify-content:space-between;}
  .nav-left{display:flex;align-items:center;gap:26px;flex-wrap:wrap;}
  .nav-brand{font-weight:700;font-size:17px;display:flex;align-items:center;gap:8px;}
  .nav-brand svg{width:18px;height:18px;}
  .nav-credit{display:flex;align-items:center;gap:8px;font-family:'IBM Plex Mono',monospace;font-size:12px;color:#cfe0f5;margin-left:22px;padding-left:22px;border-left:1px solid rgba(255,255,255,.15);}
  .nav-credit .dot{width:8px;height:8px;border-radius:2px;background:var(--teal);flex:none;}
  @media(max-width:820px){.nav-credit{display:none;}}
  .author-band{background:var(--navy-dark);border-top:1px solid rgba(255,255,255,.08);}
  .author-band-inner{max-width:1760px;margin:0 auto;padding:16px 24px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;}
  .author-name{color:#fff;font-weight:700;font-size:16px;}
  .author-affil{color:#9fb0cc;font-size:12.5px;font-family:'IBM Plex Mono',monospace;margin-top:2px;}
  .author-links{display:flex;gap:8px;flex-wrap:wrap;}
  .author-links a{text-decoration:none;color:#e8edf7;font-family:'IBM Plex Mono',monospace;font-size:12px;padding:8px 13px;border:1px solid rgba(255,255,255,.18);border-radius:8px;white-space:nowrap;}
  .author-links a:hover{border-color:var(--teal);color:var(--teal);}
  .nav-links{display:flex;gap:20px;flex-wrap:wrap;font-size:13.5px;}
  .nav-links button{background:none;border:none;color:#cfe0f5;font-size:13.5px;font-family:'Inter',sans-serif;cursor:pointer;padding:4px 2px;border-bottom:2px solid transparent;}
  .nav-links button.active{color:#fff;border-color:#fff;}
  .nav-links button:hover:not(:disabled){color:#fff;}
  .nav-links button:disabled{opacity:.45;cursor:default;}
  .nav-right{display:flex;gap:8px;flex-wrap:wrap;}
  .toggle-group{display:flex;gap:2px;background:rgba(255,255,255,.08);border-radius:8px;padding:2px;}
  .toggle-btn{background:none;border:none;color:#cfe0f5;font-family:'IBM Plex Mono',monospace;font-size:11.5px;font-weight:600;padding:6px 10px;border-radius:6px;cursor:pointer;}
  .toggle-btn.active{background:#fff;color:var(--navy);}

  main{padding:28px 0 60px;}
  .tab-panel{display:none;}
  .tab-panel.active{display:block;}
  .page-title{font-size:22px;font-weight:700;color:var(--navy);margin-bottom:4px;}
  html[data-theme="dark"] .page-title{color:var(--ink);}
  .page-sub{color:var(--muted);font-size:13.5px;margin-bottom:22px;max-width:700px;line-height:1.5;}

  /* ---- climate tab layout ---- */
  .layout{display:grid;grid-template-columns:300px 1fr;gap:22px;align-items:start;}
  .layout .panel{position:sticky;top:20px;}
  @media(max-width:1100px){.layout{grid-template-columns:1fr;} .layout .panel{position:static;}}
  .panel{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:20px;}
  .field{margin-bottom:16px;}
  .field label{display:block;font-size:12px;font-weight:600;color:var(--navy);margin-bottom:6px;}
  html[data-theme="dark"] .field label{color:var(--blue);}
  select{width:100%;background:var(--panel-2);color:var(--ink);border:1px solid var(--line);border-radius:7px;padding:9px 11px;font-family:'Inter',sans-serif;font-size:14px;cursor:pointer;}
  .submit-btn{width:100%;background:var(--navy);color:#fff;border:none;border-radius:7px;padding:11px;font-size:14px;font-weight:600;cursor:pointer;margin-top:6px;}
  .submit-btn:hover{background:var(--navy-dark);}
  .submit-btn:disabled{opacity:.6;cursor:default;}
  .panel-note{font-size:11.5px;color:var(--muted);margin-top:14px;line-height:1.5;border-top:1px solid var(--line);padding-top:12px;}

  .charts-col{display:flex;flex-direction:column;gap:18px;}
  .charts-full{display:flex;flex-direction:column;gap:18px;margin-top:18px;margin-left:322px;}
  @media(max-width:1100px){.charts-full{margin-left:0;}}
  .chart-card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:18px 18px 8px;}
  .chart-card-head{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:4px;flex-wrap:wrap;gap:6px;}
  .chart-card-head h3{font-size:15px;color:var(--ink);}
  .chart-card-head .meta{font-size:11.5px;color:var(--muted);font-family:'IBM Plex Mono',monospace;}
  .chart-legend-row{display:flex;gap:16px;flex-wrap:wrap;font-size:11.5px;color:var(--muted);margin:6px 0 10px;}
  .legend-sw{display:inline-block;width:11px;height:11px;border-radius:2px;margin-right:5px;vertical-align:-1px;}
  canvas{max-height:340px;}
  .stat-row{display:flex;gap:22px;flex-wrap:wrap;margin:12px 0 16px;}
  .stat .k{font-size:11px;color:var(--muted);margin-bottom:2px;}
  .stat .v{font-family:'IBM Plex Mono',monospace;font-size:18px;font-weight:600;color:var(--navy);}
  html[data-theme="dark"] .stat .v{color:var(--ink);}
  .stat .v.neg{color:var(--red);}
  .stat .v.pos{color:var(--blue);}
  .heatmap-gradient{ width:120px; height:10px; border-radius:5px; margin:0 6px; background:linear-gradient(90deg, rgb(26,33,56), rgb(52,198,183), rgb(232,179,78)); vertical-align:-2px; display:inline-block; }
  .loading,.error{font-family:'IBM Plex Mono',monospace;font-size:13px;padding:40px 10px;text-align:center;color:var(--muted);}
  .error{color:var(--red);}
  .retry-btn{margin-top:10px;background:var(--panel-2);border:1px solid var(--line);color:var(--ink);border-radius:6px;padding:6px 14px;font-size:12px;cursor:pointer;font-family:'Inter',sans-serif;}
  .retry-btn:hover{border-color:var(--blue);}

  /* ---- monthly heatmap table ---- */
  .heatmap-scroll{overflow-x:auto;max-height:420px;overflow-y:auto;border:1px solid var(--line);border-radius:8px;}
  .heatmap-table{border-collapse:collapse;font-family:'IBM Plex Mono',monospace;font-size:10.5px;width:100%;}
  .heatmap-table th,.heatmap-table td{padding:4px 7px;text-align:center;white-space:nowrap;}
  .heatmap-table thead th{color:var(--muted);font-weight:600;position:sticky;top:0;background:var(--panel);z-index:1;border-bottom:1px solid var(--line);}
  .heatmap-table tbody th{color:var(--muted);text-align:left;position:sticky;left:0;background:var(--panel);z-index:1;border-right:1px solid var(--line);}

  /* ---- accordion ("About this page") ---- */
  .accordion{background:var(--panel);border:1px solid var(--line);border-radius:10px;margin-bottom:22px;overflow:hidden;}
  .accordion-head{display:flex;align-items:center;gap:10px;padding:14px 18px;cursor:pointer;background:var(--panel-2);user-select:none;}
  .accordion-head svg{width:16px;height:16px;stroke:var(--blue);flex:none;}
  .accordion-title{font-weight:600;font-size:14px;color:var(--navy);flex:1;}
  html[data-theme="dark"] .accordion-title{color:var(--ink);}
  .accordion-chevron{transition:transform .2s;color:var(--muted);flex:none;}
  .accordion.open .accordion-chevron{transform:rotate(180deg);}
  .accordion-body{max-height:0;overflow:hidden;transition:max-height .25s ease;}
  .accordion.open .accordion-body{max-height:600px;}
  .accordion-body-inner{padding:16px 18px;font-size:13px;color:var(--muted);line-height:1.6;}

  /* ---- geolocate ---- */
  .geo-btn{width:100%;background:var(--panel-2);border:1px solid var(--line);color:var(--ink);border-radius:7px;padding:9px;font-size:13px;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:7px;margin-top:8px;}
  .geo-btn:hover{border-color:var(--blue);}
  .geo-btn svg{width:14px;height:14px;stroke:var(--blue);flex:none;}
  .geo-status{font-size:11px;color:var(--muted);margin-top:6px;min-height:14px;}

  /* ---- year stepper ---- */
  .year-stepper{display:flex;align-items:stretch;border:1px solid var(--line);border-radius:7px;overflow:hidden;background:var(--panel-2);}
  .year-stepper input{flex:1;border:none;background:transparent;color:var(--ink);font-family:'IBM Plex Mono',monospace;font-size:15px;padding:9px 11px;width:0;}
  .year-stepper input::-webkit-outer-spin-button,.year-stepper input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0;}
  .year-stepper .yr-btns{display:flex;flex-direction:column;border-left:1px solid var(--line);flex:none;}
  .year-stepper button{flex:1;background:none;border:none;color:var(--muted);cursor:pointer;padding:0 10px;display:flex;align-items:center;justify-content:center;font-size:10px;line-height:1;}
  .year-stepper button:hover{color:var(--blue);background:var(--line);}
  .year-stepper button:first-child{border-bottom:1px solid var(--line);}

  footer{text-align:center;padding:26px 24px 44px;color:var(--muted);font-family:'IBM Plex Mono',monospace;font-size:11px;border-top:1px solid var(--line);margin-top:20px;}
</style>
</head>
<body>

<header class="nav">
  <div class="nav-inner">
    <div class="nav-left">
      <div class="nav-brand">
        <svg viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/></svg>
        SenClim
      </div>
      <div class="nav-credit"><span class="dot"></span>Dr. Ibrahima Diouf — UCAD-ESP/LPAO-SF (Sénégal) · UL (Guinée)</div>
    </div>
    <div class="nav-right">
      <div class="toggle-group" id="lang-toggle">
        <button class="toggle-btn active" data-lang="fr">Français</button>
        <button class="toggle-btn" data-lang="en">Anglais</button>
        <button class="toggle-btn" data-lang="wo">Wolof</button>
      </div>
      <div class="toggle-group" id="theme-toggle">
        <button class="toggle-btn" data-theme-val="light" data-i18n="themeLight">Clair</button>
        <button class="toggle-btn active" data-theme-val="dark" data-i18n="themeDark">Sombre</button>
      </div>
    </div>
  </div>
</header>
<div class="author-band">
  <div class="author-band-inner">
    <div>
      <div class="author-name">Dr. Ibrahima Diouf</div>
      <div class="author-affil">UCAD-ESP/LPAO-SF (Sénégal) · UL (Guinée)</div>
    </div>
    <div class="author-links">
      <a href="#" target="_blank" rel="noopener">Site</a>
      <a href="#" target="_blank" rel="noopener">Hugging Face</a>
      <a href="#" target="_blank" rel="noopener">ORCID</a>
      <a href="#" target="_blank" rel="noopener">LinkedIn</a>
      <a href="#" target="_blank" rel="noopener">Google Scholar</a>
    </div>
  </div>
</div>

<main class="wrap">

  <div class="tab-panel active" id="tab-climate">
    <div class="page-title" data-i18n="climateTitle">Climat &amp; tendances — régions du Sénégal</div>
    <p class="page-sub" data-i18n="climateSub">Cumul de pluie, prévisions à 7 jours et historique mensuel pour la région sélectionnée. Données ERA5 &amp; Open-Meteo, calculées à la volée dans votre navigateur.</p>

    <div class="accordion" id="about-accordion">
      <div class="accordion-head" id="about-head">
        <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
        <span class="accordion-title" data-i18n="aboutTitle">À propos de cette page</span>
        <svg class="accordion-chevron" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
      <div class="accordion-body"><div class="accordion-body-inner" data-i18n="aboutBody">Ces graphiques montrent, pour la région et l'année choisies, le cumul de précipitations de l'année face à la climatologie des ~30 dernières années (archive ERA5, via Open-Meteo), le cumul des 30 derniers jours comparé à la normale de saison, les prévisions à 7 jours, et l'historique mensuel. La bande grise couvre le 5e au 95e percentile des années de référence. Il ne s'agit pas d'une prévision saisonnière officielle.</div></div>
    </div>

    <div class="layout">
      <div class="panel">
        <div class="field">
          <label data-i18n="fieldRegion">Région</label>
          <select id="sel-region"></select>
          <button class="geo-btn" id="btn-geolocate" type="button">
            <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/><circle cx="12" cy="12" r="6"/></svg>
            <span data-i18n="geolocateBtn">Me géolocaliser</span>
          </button>
          <div class="geo-status" id="geo-status"></div>
        </div>
        <div class="field">
          <label data-i18n="fieldYear">Année</label>
          <div class="year-stepper">
            <input type="number" id="year-input" inputmode="numeric">
            <div class="yr-btns">
              <button type="button" id="year-up" aria-label="+1"></button>
              <button type="button" id="year-down" aria-label="-1"></button>
            </div>
          </div>
        </div>
        <button class="submit-btn" id="btn-submit" data-i18n="submitBtn">Générer</button>
        <p class="panel-note" data-i18n="panelNote">La climatologie est calculée sur les ~30 dernières années disponibles dans l'archive ERA5 (hors année sélectionnée). Il ne s'agit pas d'une prévision saisonnière officielle (type SEAS5) : la zone au-delà d'aujourd'hui, si affichée, reste la plage climatologique historique.</p>
      </div>

      <div class="charts-col">
        <div class="chart-card">
          <div class="chart-card-head"><h3 id="title-cum">☔ Cumul de précipitations</h3><span class="meta" id="meta-cum"></span></div>
          <div class="chart-legend-row">
            <span><span class="legend-sw" style="background:var(--grey-band)"></span><span data-i18n="legendPercentile">5–95e percentile</span></span>
            <span><span class="legend-sw" style="background:var(--grey-line)"></span><span data-i18n="legendMedian">Médiane historique</span></span>
            <span><span class="legend-sw" style="background:var(--ink)"></span><span data-i18n="legendSelYear">Année sélectionnée</span></span>
          </div>
          <div class="stat-row" id="stats-cum"></div>
          <div id="cum-body"><div class="loading" data-i18n="climateHint">Chargement...</div></div>
        </div>

        <div class="chart-card">
          <div class="chart-card-head"><h3 id="title-30d">📅 Pluie des 30 derniers jours vs normale</h3><span class="meta" id="meta-30d"></span></div>
          <div class="chart-legend-row">
            <span><span class="legend-sw" style="background:var(--blue)"></span><span data-i18n="legendSurplus">Excédent vs normale</span></span>
            <span><span class="legend-sw" style="background:var(--amber)"></span><span data-i18n="legendDeficit">Déficit vs normale</span></span>
            <span><span class="legend-sw" style="background:var(--grey-line)"></span><span data-i18n="legendMedian">Médiane historique</span></span>
          </div>
          <div class="stat-row" id="stats-30d"></div>
          <div id="rain30-cum-body"><div class="loading"></div></div>
          <div class="chart-legend-row" style="margin-top:14px"><span data-i18n="dailyRainLabel">Pluie journalière (mm)</span></div>
          <div id="rain30-bar-body"></div>
        </div>
      </div>
    </div>

      <div class="charts-full">
        <div class="chart-card">
          <div class="chart-card-head">
            <h3 data-i18n="detailChartTitle2">🌦️ Pluie, probabilité &amp; ensoleillement — 7 jours</h3>
          </div>
          <div class="chart-legend-row">
            <span><span class="legend-sw" style="background:var(--blue)"></span><span data-i18n="legendPrecipBar">Pluie prévue (mm)</span></span>
            <span><span class="legend-sw" style="background:#f0d98a"></span><span data-i18n="legendSunshine">Ensoleillement (h)</span></span>
            <span><span class="legend-sw" style="background:var(--grey-line)"></span><span data-i18n="legendModelSpread">Écart min–max multi-modèle</span></span>
          </div>
          <div class="stat-row" id="stats-detail"></div>
          <div id="detail-chart-body"><div class="loading"></div></div>
        </div>

        <div class="chart-card">
          <div class="chart-card-head">
            <h3 data-i18n="monthlyHeatmapTitle">🗓️ Historique pluviométrique par mois</h3>
          </div>
          <div id="monthly-heatmap-legend" class="chart-legend-row"></div>
          <div id="monthly-heatmap-body"><div class="loading"></div></div>
        </div>

        <div class="chart-card">
          <div class="chart-card-head"><h3 data-i18n="monthlyNormalsTitle">📊 Normales mensuelles</h3><span class="meta" id="meta-monthly-norm"></span></div>
          <div class="chart-legend-row">
            <span><span class="legend-sw" style="background:var(--blue)"></span><span data-i18n="legendMonthlyPrecip">Cumul moyen (mm)</span></span>
            <span><span class="legend-sw" style="background:var(--amber)"></span><span data-i18n="legendRainyDays">Jours de pluie moyens</span></span>
          </div>
          <div id="monthly-normals-body"><div class="loading"></div></div>
        </div>
      </div>
  </div>

</main>

<footer><span data-i18n="footerText">Données © <a href="https://open-meteo.com" target="_blank" rel="noopener">Open-Meteo</a> — prévisions GFS/ICON &amp; archive ERA5 (CC BY 4.0). Outil indépendant, dans l'esprit de</span> <a href="https://hh.guidocioni.it/pointwx" target="_blank" rel="noopener">PointWx</a>.</footer>

<script>
/* Visible error banner — surfaces any JS failure directly on the page, no devtools needed. */
window.addEventListener('error', function(e){
  let b = document.getElementById('debug-banner');
  if(!b){
    b = document.createElement('div');
    b.id = 'debug-banner';
    b.style.cssText = 'position:sticky;top:0;z-index:99999;background:#c0392b;color:#fff;padding:10px 16px;font-family:monospace;font-size:12px;white-space:pre-wrap;';
    document.body.prepend(b);
  }
  b.textContent = 'Erreur JS : ' + e.message + '  (ligne ' + e.lineno + ')';
});
</script>
<script>
/* ============================= DATA ============================= */
const REGIONS = [
  {name:'Dakar', lat:14.7167, lon:-17.4677},
  {name:'Thiès', lat:14.7910, lon:-16.9359},
  {name:'Diourbel', lat:14.6522, lon:-16.2317},
  {name:'Fatick', lat:14.3390, lon:-16.4110},
  {name:'Kaolack', lat:14.1652, lon:-16.0726},
  {name:'Kaffrine', lat:14.1059, lon:-15.5508},
  {name:'Louga', lat:15.6173, lon:-16.2240},
  {name:'Saint-Louis', lat:16.0179, lon:-16.4896},
  {name:'Matam', lat:15.6559, lon:-13.2554},
  {name:'Tambacounda', lat:13.7707, lon:-13.6673},
  {name:'Kédougou', lat:12.5556, lon:-12.1746},
  {name:'Kolda', lat:12.8983, lon:-14.9412},
  {name:'Sédhiou', lat:12.7081, lon:-15.5569},
  {name:'Ziguinchor', lat:12.5833, lon:-16.2719}
];
const MONTHS = {
  fr:['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'],
  en:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
  wo:['Sam','Few','Mar','Awr','Me','Suw','Sul','Ut','Sàt','Okt','Now','Des']
};

/* ============================= I18N ============================= */
const I18N = {
  fr: {
    themeLight:'Clair', themeDark:'Sombre',
    aboutTitle:'À propos de cette page',
    aboutBody:"Ces graphiques montrent, pour la région et l'année choisies, le cumul de précipitations de l'année face à la climatologie des ~30 dernières années (archive ERA5, via Open-Meteo), le cumul des 30 derniers jours comparé à la normale de saison, les prévisions à 7 jours, et l'historique mensuel. La bande grise couvre le 5e au 95e percentile des années de référence. Il ne s'agit pas d'une prévision saisonnière officielle.",
    geolocateBtn:'Me géolocaliser', geoLocating:'Localisation en cours…', geoError:"Impossible d'obtenir votre position.", geoUnsupported:"La géolocalisation n'est pas disponible sur cet appareil.",
    geoFound:(name,km)=>`Région la plus proche : ${name} (~${km} km).`,
    climateTitle:"Climat &amp; tendances — régions du Sénégal",
    climateSub:"Cumul de pluie, prévisions à 7 jours et historique mensuel pour la région sélectionnée. Données ERA5 &amp; Open-Meteo, calculées à la volée dans votre navigateur.",
    fieldRegion:'Région', fieldYear:'Année',
    submitBtn:'Générer',
    panelNote:"La climatologie est calculée sur les ~30 dernières années disponibles dans l'archive ERA5 (hors année sélectionnée). Il ne s'agit pas d'une prévision saisonnière officielle (type SEAS5) : la zone au-delà d'aujourd'hui, si affichée, reste la plage climatologique historique.",
    legendPercentile:'5–95e percentile', legendMedian:'Médiane historique', legendSelYear:'Année sélectionnée',
    climateHint:"Chargement...",
    cumTitle:(r,y)=>`☔ Cumul de précipitations — ${r}, ${y}`,
    rain30Title:r=>`📅 Pluie des 30 derniers jours vs normale — ${r}`,
    legendSurplus:'Excédent vs normale', legendDeficit:'Déficit vs normale', dailyRainLabel:'Pluie journalière (mm)',
    metaRef:(r,n)=>`${r} · ERA5 · ${n} années de référence`,
    todayLabel:"AUJOURD'HUI",
    chartErr:m=>`Chart.js n'a pas pu être chargé depuis le CDN (${m}). Vérifiez la connexion réseau ou un bloqueur de script, puis rechargez la page.`,
    detailChartTitle2:'🌦️ Pluie, probabilité &amp; ensoleillement — 7 jours',
    legendPrecipBar:'Pluie prévue (mm)', legendSunshine:'Ensoleillement (h)', legendModelSpread:'Écart min–max multi-modèle',
    sunshineUnit:'h',
    loadingForecast:'Chargement des prévisions…', errorPrefix:'Erreur : ',
    rateLimitError:"Trop de requêtes envoyées à Open-Meteo en peu de temps (limite de l'API gratuite atteinte). Patientez une minute puis réessayez.",
    monthlyHeatmapTitle:'🗓️ Historique pluviométrique par mois', monthlyNormalsTitle:'📊 Normales mensuelles',
    legendMonthlyPrecip:'Cumul moyen (mm)', legendRainyDays:'Jours de pluie moyens',
    loadingClimate:"Analyse des archives ERA5…",
    footerText:'Données © <a href="https://open-meteo.com" target="_blank" rel="noopener">Open-Meteo</a> — prévisions GFS/ICON &amp; archive ERA5 (CC BY 4.0). Outil indépendant, dans l\'esprit de'
  },
  en: {
    themeLight:'Light', themeDark:'Dark',
    aboutTitle:'About this page',
    aboutBody:"For the chosen region and year, this shows cumulative rainfall for the year against the climatology of the last ~30 years (ERA5 archive, via Open-Meteo), the last 30 days' rainfall vs the seasonal normal, the 7-day forecast, and the monthly history. The grey band spans the 5th to 95th percentile of reference years. This is not an official seasonal forecast.",
    geolocateBtn:'Use my location', geoLocating:'Locating…', geoError:'Could not get your location.', geoUnsupported:'Geolocation is not available on this device.',
    geoFound:(name,km)=>`Nearest region: ${name} (~${km} km).`,
    climateTitle:"Climate &amp; trends — Senegal regions",
    climateSub:"Cumulative rainfall, 7-day forecast and monthly history for the selected region. ERA5 &amp; Open-Meteo data, computed live in your browser.",
    fieldRegion:'Region', fieldYear:'Year',
    submitBtn:'Generate',
    panelNote:"Climatology is computed over the ~30 most recent years available in the ERA5 archive (excluding the selected year). This is not an official seasonal forecast (e.g. SEAS5): any area shown beyond today remains the historical climatology range.",
    legendPercentile:'5–95th percentile', legendMedian:'Historical median', legendSelYear:'Selected year',
    climateHint:'Loading...',
    cumTitle:(r,y)=>`☔ Cumulative rainfall — ${r}, ${y}`,
    rain30Title:r=>`📅 Last 30 days rainfall vs normal — ${r}`,
    legendSurplus:'Surplus vs normal', legendDeficit:'Deficit vs normal', dailyRainLabel:'Daily rainfall (mm)',
    metaRef:(r,n)=>`${r} · ERA5 · ${n} reference years`,
    todayLabel:'TODAY',
    chartErr:m=>`Chart.js could not be loaded from the CDN (${m}). Check the network connection or a script blocker, then reload the page.`,
    detailChartTitle2:'🌦️ Rain, probability &amp; sunshine — 7 days',
    legendPrecipBar:'Forecast rain (mm)', legendSunshine:'Sunshine (h)', legendModelSpread:'Multi-model min–max spread',
    sunshineUnit:'h',
    loadingForecast:'Loading forecasts…', errorPrefix:'Error: ',
    rateLimitError:"Too many requests sent to Open-Meteo in a short time (free API limit reached). Wait a minute, then try again.",
    monthlyHeatmapTitle:'🗓️ Rainfall history by month', monthlyNormalsTitle:'📊 Monthly normals',
    legendMonthlyPrecip:'Average total (mm)', legendRainyDays:'Average rainy days',
    loadingClimate:'Analyzing ERA5 archives…',
    footerText:'Data © <a href="https://open-meteo.com" target="_blank" rel="noopener">Open-Meteo</a> — GFS/ICON forecasts &amp; ERA5 archive (CC BY 4.0). Independent tool, in the spirit of'
  },
  wo: {
    themeLight:'Sedd', themeDark:'Lëndëm',
    aboutTitle:'Ci mbir mi',
    aboutBody:"Ngir dëkk ak at bi ñu tann, wàll bii won taw mu dajale ci at bi ci wàllu tàngoor bu jaar-jaar ci ~30 at yu weesu (archive ERA5, jóge ci Open-Meteo), taw ci 30 fan yu weesu, xibaar taw ci 7 fan, ak jaar-jaar weer. Bànd bu grey bi mi ci diggante 5–95e percentile ci at yi jiitu. Du xibaar taw bu wér.",
    geolocateBtn:'Wone fu nekk', geoLocating:'Dañuy seet fu nekk…', geoError:'Mënula am fu nekk.', geoUnsupported:'Geolocation amul ci sa jumtukaay.',
    geoFound:(name,km)=>`Dëkk bu gëna jege: ${name} (~${km} km).`,
    climateTitle:"Tàngoor ak jëf — dëkk yi ci Senegaal",
    climateSub:"Taw mu dajale, xibaar taw ci 7 fan ak jaar-jaar weer ngir dëkk bi ñu tann. Xibaar ERA5 ak Open-Meteo, ñu ko xayma ci sa navigateur.",
    fieldRegion:'Dëkk', fieldYear:'At',
    submitBtn:'Def ko',
    panelNote:"Tàngoor bu jaar-jaar bi ñu koy xayma ci ~30 at yu mujj yi nekk ci archive ERA5 (bañ at bi ñu tann). Du xibaar taw bu wér (SEAS5) : palal bu ëpp tey, su feeñee, dafay tàngoor bu jaar-jaar rekk.",
    legendPercentile:'5–95e percentile', legendMedian:'Tàngoor jaar-jaar', legendSelYear:'At bi ñu tann',
    climateHint:'Dañuy yebbi...',
    cumTitle:(r,y)=>`☔ Taw mu dajale — ${r}, ${y}`,
    rain30Title:r=>`📅 Taw ci 30 fan yu weesu vs normale — ${r}`,
    legendSurplus:'Ëpp na normale', legendDeficit:'Néew na normale', dailyRainLabel:'Taw bés bu nekk (mm)',
    metaRef:(r,n)=>`${r} · ERA5 · ${n} at yu jiitu`,
    todayLabel:'TEY',
    chartErr:m=>`Mënula yónnee Chart.js (${m}). Xool sa réseau walla bloqueur script, def refresh xët bi.`,
    detailChartTitle2:'🌦️ Taw, jarul ak jant — 7 fan',
    legendPrecipBar:'Taw bi ñuy xaar (mm)', legendSunshine:'Jant (h)', legendModelSpread:'Diggante model yi',
    sunshineUnit:'h',
    loadingForecast:'Dañuy yónnee xibaar taw yi…', errorPrefix:'Njumte: ',
    rateLimitError:"Yónnee nañu ay request yu bare ci Open-Meteo ci diir bu gàtt (limite bi mat na). Xaar benn simili, jàppal.",
    monthlyHeatmapTitle:'🗓️ Jaar-jaar taw ci weer', monthlyNormalsTitle:'📊 Normales weer',
    legendMonthlyPrecip:'Cumul digg (mm)', legendRainyDays:'Bés yu taw yu digg',
    loadingClimate:'Dañuy xool archive ERA5 yi…',
    footerText:'Xibaar © <a href="https://open-meteo.com" target="_blank" rel="noopener">Open-Meteo</a> — xibaar GFS/ICON &amp; archive ERA5 (CC BY 4.0). Jumtukaay bu bokkul, ci melni'
  }
};
let currentLang = 'fr';
let currentTheme = 'dark';

/* ============================= I18N APPLY ============================= */
function applyI18n(){
  const t = I18N[currentLang];
  document.querySelectorAll('[data-i18n]').forEach(el=>{
    const key = el.getAttribute('data-i18n');
    if(typeof t[key] === 'string') el.innerHTML = t[key];
  });
  document.getElementById('lang-toggle').querySelectorAll('.toggle-btn').forEach(b=>b.classList.toggle('active', b.dataset.lang===currentLang));
  document.documentElement.lang = currentLang;
  const region = document.getElementById('sel-region').value;
  if(region) refreshClimateTitles();
}

/* ============================= THEME / LANG TOGGLES ============================= */
document.getElementById('theme-toggle').addEventListener('click', e=>{
  const btn = e.target.closest('.toggle-btn'); if(!btn) return;
  currentTheme = btn.dataset.themeVal;
  document.documentElement.setAttribute('data-theme', currentTheme);
  document.querySelectorAll('#theme-toggle .toggle-btn').forEach(b=>b.classList.toggle('active', b===btn));
  const region = document.getElementById('sel-region').value;
  if(cumChart) generate();
  if(detailChart) loadDetailChart(region);
  if(monthlyLoadedRegion) loadMonthlyClimate(region);
  if(window.parent !== window) window.parent.postMessage({type:'dashTheme', theme: currentTheme}, '*');
});
document.getElementById('lang-toggle').addEventListener('click', e=>{
  const btn = e.target.closest('.toggle-btn'); if(!btn) return;
  currentLang = btn.dataset.lang;
  applyI18n();
  if(window.parent !== window) window.parent.postMessage({type:'dashLang', lang: currentLang}, '*');
});

/* ---- respond to lang/theme commands from a hosting portal page (if embedded in an iframe) ---- */
window.addEventListener('message', ev=>{
  const msg = ev.data || {};
  if(msg.type === 'setLang' && msg.lang && I18N[msg.lang] && msg.lang !== currentLang){
    currentLang = msg.lang;
    applyI18n();
  }
  if(msg.type === 'setTheme' && msg.theme){
    // the portal supports 3 themes (navy/sky/light); this page only has light/dark — anything but "light" maps to dark
    const mapped = msg.theme === 'light' ? 'light' : 'dark';
    if(mapped !== currentTheme){
      currentTheme = mapped;
      document.documentElement.setAttribute('data-theme', currentTheme);
      document.querySelectorAll('#theme-toggle .toggle-btn').forEach(b=>b.classList.toggle('active', b.dataset.themeVal===currentTheme));
      const region = document.getElementById('sel-region').value;
      if(cumChart) generate();
      if(detailChart) loadDetailChart(region);
      if(monthlyLoadedRegion) loadMonthlyClimate(region);
    }
  }
});

/* ============================= CHART THEME COLORS ============================= */
function chartColors(){
  return currentTheme==='dark'
    ? { grid:'#2c3552', text:'#96a0bd', band:'rgba(124,136,171,0.22)', median:'#7c88ab', line:'#eef1f6', red:'rgba(224,114,90,0.5)', blue:'rgba(91,155,213,0.5)', amber:'rgba(224,182,78,0.5)' }
    : { grid:'#e6e9f0', text:'#626c8c', band:'rgba(138,143,156,0.28)', median:'#8a8f9c', line:'#171d2e', red:'rgba(192,57,43,0.45)', blue:'rgba(59,110,165,0.45)', amber:'rgba(201,138,18,0.45)' };
}

/* ============================= PERCENTILE / ARCHIVE ============================= */
function percentile(arr,p){
  const s=arr.filter(v=>v!=null&&!isNaN(v)).slice().sort((a,b)=>a-b);
  if(!s.length) return null;
  const idx=Math.min(s.length-1,Math.max(0,Math.ceil((p/100)*s.length)-1));
  return s[idx];
}
function explainFetchError(err){
  const t = I18N[currentLang];
  if(err && /HTTP 429/.test(err.message)) return t.rateLimitError;
  return t.errorPrefix + (err ? err.message : '');
}
/* Optional: paste a free Open-Meteo API key here (https://open-meteo.com/en/pricing) to get your
   own request quota instead of sharing the anonymous-IP limit with everyone on your network.
   Leave empty to use the free anonymous endpoints exactly as before — nothing else changes. */
const OPEN_METEO_API_KEY = '';
function omKeyed(url){
  if(!OPEN_METEO_API_KEY) return url;
  return url
    .replace('https://api.open-meteo.com','https://customer-api.open-meteo.com')
    .replace('https://archive-api.open-meteo.com','https://customer-archive-api.open-meteo.com')
    + '&apikey=' + OPEN_METEO_API_KEY;
}
async function fetchWithRetry(url, retries=2, delay=3000){
  url = omKeyed(url);
  for(let attempt=0; attempt<=retries; attempt++){
    const res = await fetch(url);
    if(res.status !== 429 || attempt === retries) return res;
    await new Promise(r=>setTimeout(r, delay));
    delay *= 2;
  }
}
function localCacheGet(key, maxAgeMs){
  try{
    const raw = localStorage.getItem(key);
    if(!raw) return null;
    const {ts, data} = JSON.parse(raw);
    if(Date.now() - ts > maxAgeMs) return null;
    return data;
  }catch(e){ return null; }
}
function localCacheSet(key, data){
  try{ localStorage.setItem(key, JSON.stringify({ts:Date.now(), data})); }catch(e){}
}
let archiveCache = {};
function fetchArchive(region){
  if(archiveCache[region]) return archiveCache[region];
  const cacheKey = 'sc_archive_'+region;
  const cached = localCacheGet(cacheKey, 12*3600*1000);
  if(cached){ const p = Promise.resolve(cached); archiveCache[region] = p; return p; }
  const r = REGIONS.find(x=>x.name===region);
  const now = new Date();
  const startYear = now.getFullYear()-30;
  const yesterday = new Date(now); yesterday.setDate(yesterday.getDate()-1);
  const end = yesterday.toISOString().slice(0,10);
  const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${r.lat}&longitude=${r.lon}&start_date=${startYear}-01-01&end_date=${end}&daily=precipitation_sum,temperature_2m_mean,temperature_2m_max,temperature_2m_min&timezone=auto`;
  const promise = fetchWithRetry(url).then(res=>{
    if(!res.ok) throw new Error('HTTP '+res.status);
    return res.json();
  }).then(data=> data.daily).then(daily=>{ localCacheSet(cacheKey, daily); return daily; });
  archiveCache[region] = promise;
  promise.catch(()=>{ delete archiveCache[region]; });
  return promise;
}
function organizeByYear(daily){
  const byYear = {};
  daily.time.forEach((t,i)=>{
    const d = new Date(t+'T00:00:00');
    if(d.getMonth()===1 && d.getDate()===29) return;
    const year = d.getFullYear();
    const start = new Date(year,0,1);
    let doy = Math.floor((d-start)/86400000)+1;
    if(doy>365) doy=365;
    if(!byYear[year]) byYear[year] = { precip:new Array(365).fill(null), tmean:new Array(365).fill(null), tmax:new Array(365).fill(null), tmin:new Array(365).fill(null) };
    byYear[year].precip[doy-1] = daily.precipitation_sum[i];
    byYear[year].tmean[doy-1] = daily.temperature_2m_mean[i];
    byYear[year].tmax[doy-1] = daily.temperature_2m_max[i];
    byYear[year].tmin[doy-1] = daily.temperature_2m_min[i];
  });
  Object.values(byYear).forEach(y=>{
    let acc=0, lastValid=-1;
    y.precip.forEach((v,i)=>{ if(v!=null) lastValid=i; });
    y.cumPrecip = y.precip.map((v,i)=>{ acc += (v||0); return i<=lastValid ? acc : null; });
  });
  return byYear;
}

/* ============================= CUSTOM CHART PLUGINS ============================= */
const todayLinePlugin = {
  id:'todayLine',
  afterDraw(chart, args, opts){
    if(!opts || opts.index==null) return;
    const {ctx, chartArea, scales} = chart;
    const x = scales.x.getPixelForValue(opts.index);
    if(x < chartArea.left || x > chartArea.right) return;
    ctx.save();
    ctx.strokeStyle = opts.gridColor||'#9aa1b0'; ctx.setLineDash([4,3]); ctx.lineWidth = 1;
    ctx.beginPath(); ctx.moveTo(x, chartArea.top); ctx.lineTo(x, chartArea.bottom); ctx.stroke();
    ctx.setLineDash([]);
    ctx.fillStyle = opts.textColor||'#626c8c'; ctx.font = '10px IBM Plex Mono, monospace';
    ctx.save(); ctx.translate(x-6, chartArea.top+4); ctx.rotate(-Math.PI/2); ctx.fillText(opts.label||"AUJOURD'HUI", 0, 0); ctx.restore();
    ctx.restore();
  }
};
const pointLabelPlugin = {
  id:'pointLabel',
  afterDraw(chart, args, opts){
    if(!opts || !opts.points) return;
    const {ctx, scales} = chart;
    opts.points.forEach(p=>{
      if(p.index==null || p.value==null) return;
      const x = scales.x.getPixelForValue(p.index);
      const y = scales.y.getPixelForValue(p.value);
      ctx.save();
      ctx.fillStyle = p.color || '#171d2e';
      ctx.beginPath(); ctx.arc(x,y,4,0,Math.PI*2); ctx.fill();
      ctx.font = '600 11px IBM Plex Mono, monospace';
      ctx.textAlign = p.align || 'left';
      ctx.fillText(p.label, x + (p.align==='right'?-8:8), y - 8);
      ctx.restore();
    });
  }
};
const whiskerDiamondPlugin = {
  id:'whiskerDiamond',
  afterDatasetsDraw(chart, args, opts){
    if(!opts || !opts.mins) return;
    const {ctx, scales, chartArea} = chart;
    const xScale = scales.x, yScale = scales.y;
    opts.mins.forEach((minV,i)=>{
      const maxV = opts.maxs[i], meanV = opts.means ? opts.means[i] : null;
      if(minV==null || maxV==null) return;
      const x = xScale.getPixelForValue(i);
      const yMin = Math.min(yScale.getPixelForValue(minV), chartArea.bottom);
      const yMax = Math.max(yScale.getPixelForValue(maxV), chartArea.top);
      ctx.save();
      ctx.strokeStyle = opts.color || '#8a8f9c'; ctx.lineWidth = 1.4;
      const capW = 7;
      ctx.beginPath(); ctx.moveTo(x, yMin); ctx.lineTo(x, yMax); ctx.stroke();
      ctx.beginPath(); ctx.moveTo(x-capW, yMin); ctx.lineTo(x+capW, yMin); ctx.stroke();
      if(yScale.getPixelForValue(maxV) >= chartArea.top){
        ctx.beginPath(); ctx.moveTo(x-capW, yMax); ctx.lineTo(x+capW, yMax); ctx.stroke();
      }
      if(meanV!=null){
        const yMean = Math.max(chartArea.top+4, Math.min(chartArea.bottom-4, yScale.getPixelForValue(meanV))), s=5;
        ctx.fillStyle = opts.diamondColor || '#c98a12';
        ctx.beginPath();
        ctx.moveTo(x, yMean-s); ctx.lineTo(x+s, yMean); ctx.lineTo(x, yMean+s); ctx.lineTo(x-s, yMean); ctx.closePath();
        ctx.fill();
      }
      ctx.restore();
    });
  }
};
const barLabelPlugin = {
  id:'barLabel',
  afterDatasetsDraw(chart, args, opts){
    if(!opts || !opts.items) return;
    const {ctx, scales} = chart;
    opts.items.forEach(item=>{
      const x = scales[item.xScaleId||'x'].getPixelForValue(item.index);
      const y = scales[item.yScaleId||'y'].getPixelForValue(item.y);
      ctx.save();
      ctx.fillStyle = item.color || '#171d2e';
      ctx.font = item.font || '600 11px IBM Plex Mono, monospace';
      ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
      ctx.fillText(item.text, x, y);
      ctx.restore();
    });
  }
};

/* ============================= REGION / YEAR CONTROLS ============================= */
function initSelects(){
  const regionSel = document.getElementById('sel-region');
  regionSel.innerHTML = REGIONS.map(r=>`<option value="${r.name}">${r.name}</option>`).join('');
  initYearInput();
}
function initYearInput(){
  const curYear = new Date().getFullYear();
  const input = document.getElementById('year-input');
  input.min = curYear - 9; input.max = curYear; input.step = 1; input.value = curYear;
}
function currentYearValue(){
  const input = document.getElementById('year-input');
  let v = parseInt(input.value, 10);
  const min = parseInt(input.min,10), max = parseInt(input.max,10);
  if(isNaN(v)) v = max;
  v = Math.min(max, Math.max(min, v));
  input.value = v;
  return v;
}
document.getElementById('year-up').addEventListener('click', ()=>{
  const input = document.getElementById('year-input');
  input.value = Math.min(parseInt(input.max,10), currentYearValue()+1);
  loadAll(document.getElementById('sel-region').value);
});
document.getElementById('year-down').addEventListener('click', ()=>{
  const input = document.getElementById('year-input');
  input.value = Math.max(parseInt(input.min,10), currentYearValue()-1);
  loadAll(document.getElementById('sel-region').value);
});
document.getElementById('year-input').addEventListener('change', ()=>{
  loadAll(document.getElementById('sel-region').value);
});
document.getElementById('sel-region').addEventListener('change', ()=>{
  loadAll(document.getElementById('sel-region').value);
});

/* ---- accordion ---- */
document.getElementById('about-head').addEventListener('click', ()=>{
  document.getElementById('about-accordion').classList.toggle('open');
});

/* ---- geolocation (no map, just nearest-region lookup) ---- */
function haversineKm(lat1,lon1,lat2,lon2){
  const toRad = d=>d*Math.PI/180, R=6371;
  const dLat=toRad(lat2-lat1), dLon=toRad(lon2-lon1);
  const a = Math.sin(dLat/2)**2 + Math.cos(toRad(lat1))*Math.cos(toRad(lat2))*Math.sin(dLon/2)**2;
  return 2*R*Math.asin(Math.sqrt(a));
}
document.getElementById('btn-geolocate').addEventListener('click', ()=>{
  const status = document.getElementById('geo-status');
  const t = I18N[currentLang];
  if(!navigator.geolocation){ status.textContent = t.geoUnsupported; return; }
  status.textContent = t.geoLocating;
  navigator.geolocation.getCurrentPosition(pos=>{
    const {latitude, longitude} = pos.coords;
    let best=null, bestD=Infinity;
    REGIONS.forEach(r=>{ const d=haversineKm(latitude,longitude,r.lat,r.lon); if(d<bestD){bestD=d; best=r;} });
    if(best){
      document.getElementById('sel-region').value = best.name;
      status.textContent = t.geoFound(best.name, Math.round(bestD));
      loadAll(best.name);
    }
  }, ()=>{ status.textContent = t.geoError; }, {timeout:8000});
});

let cumChart=null, lastClimateResult=null;

function buildCumulativeChart(byYear, region, selYear){
  const t = I18N[currentLang], C = chartColors();
  const pastYears = Object.keys(byYear).map(Number).filter(y=>y!==selYear).sort((a,b)=>a-b);
  const nBuckets = 73, bucketEnds = Array.from({length:nBuckets},(_,i)=>Math.min(365,(i+1)*5)-1);
  const band = bucketEnds.map(idx=>{
    const vals = pastYears.map(y=>byYear[y] && byYear[y].cumPrecip[idx]).filter(v=>v!=null);
    return {p5:percentile(vals,5), p50:percentile(vals,50), p95:percentile(vals,95)};
  });
  const selArr = byYear[selYear] ? bucketEnds.map(idx=>byYear[selYear].cumPrecip[idx] ?? null) : bucketEnds.map(()=>null);
  let lastIdx=-1; selArr.forEach((v,i)=>{ if(v!=null) lastIdx=i; });
  const isCurrentYear = selYear === new Date().getFullYear();
  const selTrimmed = isCurrentYear ? selArr.map((v,i)=> i<=lastIdx ? v : null) : selArr;
  const todayLabelIdx = isCurrentYear ? lastIdx : -1;

  document.getElementById('cum-body').innerHTML = '<canvas id="chart-cum"></canvas>';
  const ctx = document.getElementById('chart-cum').getContext('2d');
  const months = MONTHS[currentLang];
  const labels = bucketEnds.map(idx=>{ const d=new Date(selYear,0,idx+1); return d.getDate()<=5 ? months[d.getMonth()] : ''; });
  if(cumChart) cumChart.destroy();
  cumChart = new Chart(ctx,{
    type:'line',
    data:{ labels, datasets:[
      {label:'p5', data:band.map(b=>b.p5), borderWidth:0, pointRadius:0, fill:false},
      {label:t.legendPercentile, data:band.map(b=>b.p95), borderWidth:0, pointRadius:0, backgroundColor:C.band, fill:'-1'},
      {label:t.legendMedian, data:band.map(b=>b.p50), borderColor:C.median, borderDash:[4,3], borderWidth:1.3, pointRadius:0, fill:false},
      {label:String(selYear), data:selTrimmed, borderColor:C.line, backgroundColor:'rgba(59,110,165,0.08)', borderWidth:2.5, pointRadius:0, pointHoverRadius:4, fill:'origin'}
    ]},
    options:{responsive:true, maintainAspectRatio:false,
      interaction:{mode:'index', intersect:false},
      plugins:{ legend:{display:false},
        tooltip:{ filter:(item)=>item.dataset.label!=='p5', callbacks:{ label:(item)=> `${item.dataset.label}: ${item.parsed.y!=null?item.parsed.y.toFixed(0)+' mm':'—'}` } },
        todayLine: todayLabelIdx>=0 ? {index:todayLabelIdx, textColor:C.text, gridColor:C.grid, label:t.todayLabel} : null,
        pointLabel: todayLabelIdx>=0 ? {points:[{index:todayLabelIdx, value:selTrimmed[todayLabelIdx], label:(selTrimmed[todayLabelIdx]||0).toFixed(1)+' mm', color:C.line}]} : null
      },
      scales:{ x:{ticks:{color:C.text,autoSkip:false,maxRotation:0}, grid:{color:C.grid}},
               y:{ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}} } }
  });
  document.getElementById('meta-cum').textContent = t.metaRef(region, pastYears.length);
  const todayCum = todayLabelIdx>=0 ? selTrimmed[todayLabelIdx] : null;
  const normalToDate = todayLabelIdx>=0 ? band[todayLabelIdx].p50 : null;
  const anomaly = (todayCum!=null && normalToDate!=null) ? todayCum - normalToDate : null;
  const anomalyPct = (anomaly!=null && normalToDate>0) ? (anomaly/normalToDate*100) : null;
  document.getElementById('stats-cum').innerHTML = isCurrentYear ? `
    <div class="stat"><div class="k">Cumul à ce jour</div><div class="v">${todayCum!=null?todayCum.toFixed(0)+' mm':'—'}</div></div>
    <div class="stat"><div class="k">Normale à ce jour</div><div class="v">${normalToDate!=null?normalToDate.toFixed(0)+' mm':'—'}</div></div>
    <div class="stat"><div class="k">Écart vs normale</div><div class="v ${anomaly>=0?'pos':'neg'}">${anomaly!=null?(anomaly>=0?'+':'')+anomaly.toFixed(0)+' mm ('+(anomalyPct>=0?'+':'')+anomalyPct.toFixed(0)+'%)':'—'}</div></div>
  ` : '';
  return {band, selTrimmed, lastIdx, isCurrentYear};
}

function refreshClimateTitles(){
  const t = I18N[currentLang];
  const region = document.getElementById('sel-region').value;
  const selYear = currentYearValue();
  document.getElementById('title-cum').textContent = t.cumTitle(region, selYear);
  document.getElementById('title-30d').textContent = t.rain30Title(region);
}

/* ---- trailing 30-day rainfall vs normal (RFE2-style) ---- */
let rain30ChartCum=null, rain30ChartBar=null;
async function fetchRecent30(region){
  const cacheKey = 'sc_recent30_'+region;
  const cached = localCacheGet(cacheKey, 3*3600*1000);
  if(cached) return cached;
  const r = REGIONS.find(x=>x.name===region);
  const url = `https://api.open-meteo.com/v1/forecast?latitude=${r.lat}&longitude=${r.lon}&daily=precipitation_sum&timezone=auto&past_days=30&forecast_days=1`;
  const res = await fetchWithRetry(url); if(!res.ok) throw new Error('HTTP '+res.status);
  const data = await res.json();
  localCacheSet(cacheKey, data.daily);
  return data.daily;
}
function dayOfYearOf(d){ const start=new Date(d.getFullYear(),0,1); let doy=Math.floor((d-start)/86400000)+1; return doy>365?365:doy; }
function computeNormalForDates(byYear, dates, excludeYear){
  // Uses the same method as the cumulative chart: for each reference year, sum precip over the
  // matching calendar-day window, then take the MEDIAN of those yearly totals — not a day-by-day
  // average, which uses a different statistic (mean) and can silently disagree in sign with the
  // cumulative chart on skewed rainfall distributions.
  const years = Object.keys(byYear).map(Number).filter(y=>y!==excludeYear);
  const doys = dates.map(d=>dayOfYearOf(d));
  return doys.map((_, i)=>{
    const yearlyTotals = years.map(y=>{
      let total = 0;
      for(let k=0;k<=i;k++){
        const v = byYear[y].precip[doys[k]-1];
        total += (v||0);
      }
      return total;
    });
    return percentile(yearlyTotals, 50) || 0;
  });
}
async function buildRain30(region){
  const t = I18N[currentLang], C = chartColors();
  document.getElementById('rain30-cum-body').innerHTML = '<canvas id="chart-rain30-cum"></canvas>';
  document.getElementById('rain30-bar-body').innerHTML = '<canvas id="chart-rain30-bar"></canvas>';
  try{
    const [recent, archiveDaily] = await Promise.all([fetchRecent30(region), fetchArchive(region)]);
    const byYear = organizeByYear(archiveDaily);
    const times = recent.time.slice(0,-1);
    const precs = recent.precipitation_sum.slice(0,-1).map(v=>v==null?0:v);
    const dates = times.map(s=>new Date(s+'T00:00:00'));
    const normalCum = computeNormalForDates(byYear, dates, new Date().getFullYear());
    let accA=0;
    const actualCum = precs.map(v=>{ accA+=v; return accA; });
    const above = actualCum.map((v,i)=>Math.max(v, normalCum[i]));
    const below = actualCum.map((v,i)=>Math.min(v, normalCum[i]));
    const months = MONTHS[currentLang];
    const labels = dates.map(d=>d.getDate()+' '+months[d.getMonth()]);

    const ctxCum = document.getElementById('chart-rain30-cum').getContext('2d');
    if(rain30ChartCum) rain30ChartCum.destroy();
    rain30ChartCum = new Chart(ctxCum,{
      type:'line',
      data:{ labels, datasets:[
        {label:t.legendMedian, data:normalCum, borderColor:C.median, borderDash:[3,3], borderWidth:1.3, pointRadius:0, fill:false},
        {label:t.legendSurplus, data:above, borderWidth:0, pointRadius:0, backgroundColor:C.blue, fill:0},
        {label:t.legendDeficit, data:below, borderWidth:0, pointRadius:0, backgroundColor:C.amber, fill:0},
        {label:region, data:actualCum, borderColor:C.line, borderDash:[2,2], borderWidth:2, pointRadius:0, fill:false}
      ]},
      options:{responsive:true, maintainAspectRatio:false,
        interaction:{mode:'index', intersect:false},
        plugins:{legend:{display:false}, tooltip:{ callbacks:{ label:(item)=> `${item.dataset.label}: ${item.parsed.y!=null?item.parsed.y.toFixed(0)+' mm':'—'}` } }},
        scales:{ x:{ticks:{color:C.text,maxRotation:0,autoSkip:true,maxTicksLimit:8}, grid:{color:C.grid}},
                 y:{ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}} } }
    });

    const ctxBar = document.getElementById('chart-rain30-bar').getContext('2d');
    if(rain30ChartBar) rain30ChartBar.destroy();
    rain30ChartBar = new Chart(ctxBar,{
      type:'bar',
      data:{ labels, datasets:[ {label:t.dailyRainLabel, data:precs, backgroundColor:'#7fbf3f', borderRadius:3} ] },
      options:{responsive:true, maintainAspectRatio:false,
        plugins:{legend:{display:false}, tooltip:{ callbacks:{ label:(item)=> `${item.parsed.y.toFixed(1)} mm` } }},
        scales:{ x:{ticks:{color:C.text,maxRotation:0,autoSkip:true,maxTicksLimit:8}, grid:{display:false}},
                 y:{ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}} } }
    });
    document.getElementById('meta-30d').textContent = t.metaRef(region, Object.keys(byYear).filter(y=>Number(y)!==new Date().getFullYear()).length);
    const total30 = actualCum[actualCum.length-1], normal30 = normalCum[normalCum.length-1];
    const gap30 = total30 - normal30, gap30Pct = normal30>0 ? (gap30/normal30*100) : null;
    document.getElementById('stats-30d').innerHTML = `
      <div class="stat"><div class="k">Cumul 30 jours</div><div class="v">${total30.toFixed(0)} mm</div></div>
      <div class="stat"><div class="k">Normale 30 jours</div><div class="v">${normal30.toFixed(0)} mm</div></div>
      <div class="stat"><div class="k">Écart vs normale</div><div class="v ${gap30>=0?'pos':'neg'}">${gap30>=0?'+':''}${gap30.toFixed(0)} mm${gap30Pct!=null?' ('+(gap30Pct>=0?'+':'')+gap30Pct.toFixed(0)+'%)':''}</div></div>
    `;
  }catch(err){
    document.getElementById('rain30-cum-body').innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="buildRain30('${region}')">↻ Réessayer</button></div>`;
    document.getElementById('rain30-bar-body').innerHTML = '';
    document.getElementById('stats-30d').innerHTML = '';
  }
}

async function generate(){
  const t = I18N[currentLang];
  const region = document.getElementById('sel-region').value;
  const selYear = currentYearValue();
  document.getElementById('cum-body').innerHTML = `<div class="loading">${t.climateHint}</div>`;
  document.getElementById('stats-cum').innerHTML = '';
  refreshClimateTitles();
  try{
    const daily = await fetchArchive(region);
    const byYear = organizeByYear(daily);
    lastClimateResult = {byYear, region, selYear};
    buildCumulativeChart(byYear, region, selYear);
    buildRain30(region);
  }catch(err){
    document.getElementById('cum-body').innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="generate()">↻ Réessayer</button></div>`;
  }
}

function fmtValue(varKey,v){ if(v==null||isNaN(v)) return '—'; return varKey==='sum'?v.toFixed(1):Math.round(v); }

/* ---- detailed 7-day forecast chart (rain + probability + sunshine + multi-model spread) ---- */
function detailChartPalette(){
  return currentTheme==='dark'
    ? { bar:'#5b9bd5', sun:'rgba(224,182,78,0.35)', labelOnBar:'#0f1c2e', labelAbove:'#eef1f6', whisker:'#7c88ab', diamond:'#e0b64e' }
    : { bar:'#3b6ea5', sun:'rgba(240,217,138,0.7)', labelOnBar:'#ffffff', labelAbove:'#171d2e', whisker:'#8a8f9c', diamond:'#c98a12' };
}
async function fetchForecastDetailData(region){
  const cacheKey = 'sc_detail_'+region;
  const cached = localCacheGet(cacheKey, 3*3600*1000);
  if(cached) return cached;
  const r = REGIONS.find(x=>x.name===region);
  const baseUrl = `https://api.open-meteo.com/v1/forecast?latitude=${r.lat}&longitude=${r.lon}&daily=precipitation_sum,precipitation_probability_max,sunshine_duration&timezone=auto&forecast_days=7`;
  const modelsUrl = `https://api.open-meteo.com/v1/forecast?latitude=${r.lat}&longitude=${r.lon}&daily=precipitation_sum&models=icon_seamless,gfs_seamless,ecmwf_ifs025,gem_seamless&timezone=auto&forecast_days=7`;
  const baseRes = await fetchWithRetry(baseUrl);
  if(!baseRes.ok) throw new Error('HTTP '+baseRes.status);
  const base = await baseRes.json();
  const n = base.daily.time.length;
  let modelMin=null, modelMean=null, modelMax=null;
  try{
    const modelRes = await fetchWithRetry(modelsUrl);
    if(modelRes.ok){
      const modelData = await modelRes.json();
      const keys = Object.keys(modelData.daily).filter(k=>k.startsWith('precipitation_sum_'));
      if(keys.length){
        modelMin = new Array(n).fill(null); modelMean = new Array(n).fill(null); modelMax = new Array(n).fill(null);
        for(let i=0;i<n;i++){
          const vals = keys.map(k=>modelData.daily[k][i]).filter(v=>v!=null);
          if(vals.length){ modelMin[i]=Math.min(...vals); modelMax[i]=Math.max(...vals); modelMean[i]=vals.reduce((a,b)=>a+b,0)/vals.length; }
        }
      }
    }
  }catch(e){}
  const result = { daily: base.daily, modelMin, modelMean, modelMax };
  localCacheSet(cacheKey, result);
  return result;
}
let detailChart = null;
async function loadDetailChart(region){
  const t = I18N[currentLang];
  const body = document.getElementById('detail-chart-body');
  body.innerHTML = `<div class="loading">${t.loadingForecast}</div>`;
  try{
    const { daily, modelMin, modelMean, modelMax } = await fetchForecastDetailData(region);
    const P = detailChartPalette();
    const narrow = body.clientWidth > 0 && body.clientWidth < 480;
    const localeMap = {fr:'fr-FR', en:'en-US', wo:'fr-FR'};
    const labels = daily.time.map(iso=>{
      const d = new Date(iso+'T00:00:00');
      return narrow
        ? d.toLocaleDateString(localeMap[currentLang], {day:'numeric', month:'short'})
        : d.toLocaleDateString(localeMap[currentLang], {weekday:'short', day:'numeric', month:'short'});
    });
    const precip = daily.precipitation_sum.map(v=>v==null?0:v);
    const prob = daily.precipitation_probability_max;
    const sunHours = daily.sunshine_duration.map(v=>v==null?0:v/3600);
    const precipMax = Math.max(1, ...precip);
    const yMax = Math.max(10, Math.ceil((precipMax*1.6)/5)*5);
    const labelFontPx = narrow ? 9 : 11;

    const items = [];
    precip.forEach((v,i)=>{
      const tall = v >= yMax*0.15;
      items.push({ index:i, y: tall ? v*0.9 : v + yMax*0.13, xScaleId:'x', yScaleId:'y',
        text: fmtValue('prob',prob[i])+'%', color: tall ? P.labelOnBar : P.labelAbove,
        font:`600 ${labelFontPx}px IBM Plex Mono, monospace` });
    });
    sunHours.forEach((h,i)=>{
      items.push({ index:i, y: Math.max(h*0.55, 1), xScaleId:'x2', yScaleId:'y1',
        text: (narrow ? Math.round(h)+t.sunshineUnit : h.toFixed(1)+' '+t.sunshineUnit), color: P.labelAbove,
        font:`500 ${labelFontPx}px IBM Plex Mono, monospace` });
    });

    body.innerHTML = '<canvas id="chart-detail"></canvas>';
    const ctx = document.getElementById('chart-detail').getContext('2d');
    const C = chartColors();
    if(detailChart) detailChart.destroy();
    detailChart = new Chart(ctx,{
      type:'bar',
      data:{ labels, datasets:[
        { label:'Ensoleillement', data: sunHours, xAxisID:'x2', yAxisID:'y1', backgroundColor:P.sun, barPercentage:0.9, categoryPercentage:0.85, order:2 },
        { label:'Pluie prévue', data: precip, xAxisID:'x', yAxisID:'y', backgroundColor:P.bar, barPercentage:0.42, categoryPercentage:0.85, order:1, borderRadius:3 }
      ]},
      options:{responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{display:false},
          tooltip:{ callbacks:{ label:(item)=> item.dataset.label==='Pluie prévue'
            ? `Pluie: ${item.parsed.y.toFixed(1)} mm (${fmtValue('prob',prob[item.dataIndex])}% de proba)`
            : `Ensoleillement: ${item.parsed.y.toFixed(1)} h` } },
          whiskerDiamond: modelMin ? {mins:modelMin, maxs:modelMax, means:modelMean, color:P.whisker, diamondColor:P.diamond} : null,
          barLabel: {items}
        },
        scales:{
          x:{ type:'category', labels, offset:true, ticks:{color:C.text, font:{size:labelFontPx+1}}, grid:{color:C.grid} },
          x2:{ type:'category', labels, offset:true, display:false },
          y:{ position:'left', min:0, suggestedMax:yMax, ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text} },
          y1:{ position:'right', min:0, max:14, display:false }
        } }
    });
    let bestIdx=-1, bestScore=-1;
    precip.forEach((v,i)=>{ const score=v*(prob[i]||0); if(score>bestScore){ bestScore=score; bestIdx=i; } });
    const takeawayEl = document.getElementById('stats-detail');
    if(bestIdx>=0 && precip[bestIdx]>=1){
      takeawayEl.innerHTML = `<div class="stat" style="max-width:100%"><div class="k">À retenir</div><div class="v" style="font-size:14px">Jour le plus arrosé : <b>${labels[bestIdx]}</b> — ${precip[bestIdx].toFixed(1)} mm attendus (${fmtValue('prob',prob[bestIdx])}%)</div></div>`;
    } else {
      takeawayEl.innerHTML = `<div class="stat" style="max-width:100%"><div class="k">À retenir</div><div class="v" style="font-size:14px">Pas de pluie significative attendue sur les 7 prochains jours</div></div>`;
    }
  }catch(err){
    body.innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="loadDetailChart('${region}')">↻ Réessayer</button></div>`;
    document.getElementById('stats-detail').innerHTML = '';
  }
}

/* ---- monthly climate: rainfall history heatmap + normals ---- */
function mixRgb(c0,c1,t){ return [Math.round(c0[0]+(c1[0]-c0[0])*t), Math.round(c0[1]+(c1[1]-c0[1])*t), Math.round(c0[2]+(c1[2]-c0[2])*t)]; }
function contrastForRgb(rgb){ const lum=(0.299*rgb[0]+0.587*rgb[1]+0.114*rgb[2])/255; return lum>0.6?'#111318':'#ffffff'; }
function heatColor(ratio, theme){
  ratio = Math.max(0, Math.min(1, ratio));
  const stops = theme==='dark'
    ? [[0,[26,33,56]],[0.5,[59,110,165]],[1,[224,182,78]]]
    : [[0,[245,247,251]],[0.5,[91,155,213]],[1,[28,58,94]]];
  for(let i=0;i<stops.length-1;i++){ if(ratio<=stops[i+1][0]){ const t=(ratio-stops[i][0])/(stops[i+1][0]-stops[i][0]); return mixRgb(stops[i][1],stops[i+1][1],t); } }
  return stops[stops.length-1][1];
}
function organizeMonthlyStats(daily){
  const byYear = {};
  daily.time.forEach((t,i)=>{
    const d = new Date(t+'T00:00:00');
    const year = d.getFullYear(), month = d.getMonth();
    if(!byYear[year]) byYear[year] = { totals:new Array(12).fill(0), rainyDays:new Array(12).fill(0) };
    const p = daily.precipitation_sum[i]||0;
    byYear[year].totals[month] += p;
    if(p>=1) byYear[year].rainyDays[month] += 1;
  });
  return byYear;
}
function buildHeatmapTable(byYear){
  const months = MONTHS[currentLang];
  const years = Object.keys(byYear).map(Number).sort((a,b)=>a-b);
  let maxVal = 0, maxYear=null, maxMonth=null;
  years.forEach(y=> byYear[y].totals.forEach((v,m)=>{ if(v>maxVal){ maxVal=v; maxYear=y; maxMonth=m; } }));
  let html = '<div class="heatmap-scroll"><table class="heatmap-table"><thead><tr><th></th>';
  years.forEach(y=> html += `<th>${y}</th>`);
  html += '</tr></thead><tbody>';
  for(let m=0;m<12;m++){
    html += `<tr><th>${months[m]}</th>`;
    years.forEach(y=>{
      const v = byYear[y].totals[m];
      const rgb = heatColor(maxVal ? v/maxVal : 0, currentTheme);
      const bg = `rgb(${rgb.join(',')})`, fg = contrastForRgb(rgb);
      html += `<td style="background:${bg};color:${fg}" title="${months[m]} ${y} : ${v.toFixed(1)} mm">${v>=10?Math.round(v):v>0?v.toFixed(1):'0'}</td>`;
    });
    html += '</tr>';
  }
  html += '</tbody></table></div>';
  const legendEl = document.getElementById('monthly-heatmap-legend');
  if(legendEl) legendEl.innerHTML = `<span>Faible</span><span class="heatmap-gradient"></span><span>Élevé — max : ${Math.round(maxVal)} mm (${months[maxMonth]} ${maxYear})</span>`;
  return html;
}
let monthlyNormalsChart = null;
function buildMonthlyNormalsChart(byYear){
  const t = I18N[currentLang], C = chartColors();
  const years = Object.keys(byYear).map(Number);
  const avgTotals = new Array(12).fill(0), avgRainyDays = new Array(12).fill(0);
  for(let m=0;m<12;m++){
    let sumT=0,sumR=0;
    years.forEach(y=>{ sumT += byYear[y].totals[m]; sumR += byYear[y].rainyDays[m]; });
    avgTotals[m] = years.length ? sumT/years.length : 0;
    avgRainyDays[m] = years.length ? sumR/years.length : 0;
  }
  document.getElementById('monthly-normals-body').innerHTML = '<canvas id="chart-monthly-normals"></canvas>';
  const ctx = document.getElementById('chart-monthly-normals').getContext('2d');
  if(monthlyNormalsChart) monthlyNormalsChart.destroy();
  monthlyNormalsChart = new Chart(ctx,{
    data:{ labels: MONTHS[currentLang], datasets:[
      { type:'bar', label:t.legendMonthlyPrecip, data:avgTotals, backgroundColor:C.blue, yAxisID:'y', borderRadius:4 },
      { type:'line', label:t.legendRainyDays, data:avgRainyDays, borderColor:'#c98a12', backgroundColor:'#c98a12', yAxisID:'y1', pointRadius:3, pointHoverRadius:5, tension:.3 }
    ]},
    options:{responsive:true, maintainAspectRatio:false,
      interaction:{mode:'index', intersect:false},
      plugins:{legend:{display:false}, tooltip:{ callbacks:{ label:(item)=> item.datasetIndex===0 ? `${t.legendMonthlyPrecip}: ${item.parsed.y.toFixed(0)} mm` : `${t.legendRainyDays}: ${item.parsed.y.toFixed(1)}` } }},
      scales:{ x:{ticks:{color:C.text}, grid:{display:false}},
               y:{position:'left', ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}},
               y1:{position:'right', ticks:{color:C.text}, grid:{display:false}, title:{display:true,text:t.legendRainyDays,color:C.text}} } }
  });
}
let monthlyLoadedRegion = null;
async function loadMonthlyClimate(region){
  const t = I18N[currentLang];
  monthlyLoadedRegion = region;
  document.getElementById('monthly-heatmap-body').innerHTML = `<div class="loading">${t.loadingClimate}</div>`;
  document.getElementById('monthly-normals-body').innerHTML = '<div class="loading">—</div>';
  try{
    const daily = await fetchArchive(region);
    const byYear = organizeMonthlyStats(daily);
    document.getElementById('monthly-heatmap-body').innerHTML = buildHeatmapTable(byYear);
    buildMonthlyNormalsChart(byYear);
    document.getElementById('meta-monthly-norm').textContent = t.metaRef(region, Object.keys(byYear).length);
  }catch(err){
    document.getElementById('monthly-heatmap-body').innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="loadMonthlyClimate('${region}')">↻ Réessayer</button></div>`;
    document.getElementById('monthly-normals-body').innerHTML = '';
  }
}

/* ---- unified load: one region drives all 5 figures ---- */
function loadAll(region){
  generate();
  loadDetailChart(region);
  loadMonthlyClimate(region);
}
document.getElementById('btn-submit').addEventListener('click', ()=> loadAll(document.getElementById('sel-region').value));

/* ============================= BOOT ============================= */
function loadScript(src){
  return new Promise((resolve,reject)=>{
    const s = document.createElement('script');
    s.src = src; s.onload = ()=>resolve(true); s.onerror = ()=>reject(new Error(src));
    document.head.appendChild(s);
  });
}
async function ensureChartJs(){
  if(window.Chart) return true;
  const sources = ['https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.4/chart.umd.min.js','https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js'];
  for(const src of sources){ try{ await loadScript(src); if(window.Chart) return true; }catch(e){} }
  return false;
}

initSelects();
applyI18n();

(async function boot(){
  const ok = await ensureChartJs();
  if(!ok){
    const t = I18N[currentLang];
    document.getElementById('cum-body').innerHTML = `<div class="error">${t.chartErr('cdnjs / jsdelivr')}</div>`;
    return;
  }
  Chart.register(todayLinePlugin, pointLabelPlugin, whiskerDiamondPlugin, barLabelPlugin);
  loadAll(document.getElementById('sel-region').value);
})();
</script>
</body>
</html>