idiouf commited on
Commit
96c4809
·
verified ·
1 Parent(s): 362deec

Upload index.html

Browse files
Files changed (1) hide show
  1. index.html +1036 -18
index.html CHANGED
@@ -1,19 +1,1037 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
+ <!DOCTYPE html>
2
+ <html lang="fr" data-theme="light">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>SenClim climat &amp; prévisions du Sénégal</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <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">
9
+ <style>
10
+ :root, html[data-theme="light"]{
11
+ --navy:#1c3a5e; --navy-dark:#152c48; --blue:#3b6ea5; --ink:#171d2e; --muted:#626c8c;
12
+ --bg:#eef1f6; --panel:#ffffff; --panel-2:#f5f7fb; --line:#dbe0ec;
13
+ --grey-band:#c7cbd6; --grey-line:#8a8f9c; --red:#c0392b; --amber:#c98a12; --teal:#1b8f7d;
14
+ }
15
+ html[data-theme="dark"]{
16
+ --navy:#0f1c2e; --navy-dark:#0a1420; --blue:#5b9bd5; --ink:#eef1f6; --muted:#96a0bd;
17
+ --bg:#10162b; --panel:#1a2138; --panel-2:#212a44; --line:#2c3552;
18
+ --grey-band:#3a4260; --grey-line:#7c88ab; --red:#e0725a; --amber:#e0b64e; --teal:#4fc3ac;
19
+ }
20
+ *{box-sizing:border-box;margin:0;padding:0;}
21
+ html,body{background:var(--bg);color:var(--ink);font-family:'Inter',sans-serif;min-height:100vh;transition:background .2s,color .2s;}
22
+ a{color:var(--blue);}
23
+ .wrap{max-width:1320px;margin:0 auto;padding:0 24px;}
24
+
25
+ header.nav{background:var(--navy);color:#fff;}
26
+ .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;}
27
+ .nav-left{display:flex;align-items:center;gap:26px;flex-wrap:wrap;}
28
+ .nav-brand{font-weight:700;font-size:17px;display:flex;align-items:center;gap:8px;}
29
+ .nav-brand svg{width:18px;height:18px;}
30
+ .nav-links{display:flex;gap:20px;flex-wrap:wrap;font-size:13.5px;}
31
+ .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;}
32
+ .nav-links button.active{color:#fff;border-color:#fff;}
33
+ .nav-links button:hover:not(:disabled){color:#fff;}
34
+ .nav-links button:disabled{opacity:.45;cursor:default;}
35
+ .nav-right{display:flex;gap:8px;flex-wrap:wrap;}
36
+ .toggle-group{display:flex;gap:2px;background:rgba(255,255,255,.08);border-radius:8px;padding:2px;}
37
+ .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;}
38
+ .toggle-btn.active{background:#fff;color:var(--navy);}
39
+
40
+ main{padding:28px 0 60px;}
41
+ .tab-panel{display:none;}
42
+ .tab-panel.active{display:block;}
43
+ .page-title{font-size:22px;font-weight:700;color:var(--navy);margin-bottom:4px;}
44
+ html[data-theme="dark"] .page-title{color:var(--ink);}
45
+ .page-sub{color:var(--muted);font-size:13.5px;margin-bottom:22px;max-width:700px;line-height:1.5;}
46
+
47
+ /* ---- climate tab layout ---- */
48
+ .layout{display:grid;grid-template-columns:300px 1fr;gap:22px;align-items:start;}
49
+ @media(max-width:900px){.layout{grid-template-columns:1fr;}}
50
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:20px;}
51
+ .field{margin-bottom:16px;}
52
+ .field label{display:block;font-size:12px;font-weight:600;color:var(--navy);margin-bottom:6px;}
53
+ html[data-theme="dark"] .field label{color:var(--blue);}
54
+ 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;}
55
+ .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;}
56
+ .submit-btn:hover{background:var(--navy-dark);}
57
+ .submit-btn:disabled{opacity:.6;cursor:default;}
58
+ .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;}
59
+
60
+ .charts-col{display:flex;flex-direction:column;gap:18px;}
61
+ .chart-card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:18px 18px 8px;}
62
+ .chart-card-head{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:4px;flex-wrap:wrap;gap:6px;}
63
+ .chart-card-head h3{font-size:15px;color:var(--ink);}
64
+ .chart-card-head .meta{font-size:11.5px;color:var(--muted);font-family:'IBM Plex Mono',monospace;}
65
+ .chart-legend-row{display:flex;gap:16px;flex-wrap:wrap;font-size:11.5px;color:var(--muted);margin:6px 0 10px;}
66
+ .legend-sw{display:inline-block;width:11px;height:11px;border-radius:2px;margin-right:5px;vertical-align:-1px;}
67
+ canvas{max-height:340px;}
68
+ .stat-row{display:flex;gap:22px;flex-wrap:wrap;margin:12px 0 16px;}
69
+ .stat .k{font-size:11px;color:var(--muted);margin-bottom:2px;}
70
+ .stat .v{font-family:'IBM Plex Mono',monospace;font-size:18px;font-weight:600;color:var(--navy);}
71
+ html[data-theme="dark"] .stat .v{color:var(--ink);}
72
+ .stat .v.neg{color:var(--red);}
73
+ .stat .v.pos{color:var(--blue);}
74
+ .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; }
75
+ .loading,.error{font-family:'IBM Plex Mono',monospace;font-size:13px;padding:40px 10px;text-align:center;color:var(--muted);}
76
+ .error{color:var(--red);}
77
+ .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;}
78
+ .retry-btn:hover{border-color:var(--blue);}
79
+
80
+ /* ---- monthly heatmap table ---- */
81
+ .heatmap-scroll{overflow-x:auto;max-height:420px;overflow-y:auto;border:1px solid var(--line);border-radius:8px;}
82
+ .heatmap-table{border-collapse:collapse;font-family:'IBM Plex Mono',monospace;font-size:10.5px;width:100%;}
83
+ .heatmap-table th,.heatmap-table td{padding:4px 7px;text-align:center;white-space:nowrap;}
84
+ .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);}
85
+ .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);}
86
+
87
+ /* ---- accordion ("About this page") ---- */
88
+ .accordion{background:var(--panel);border:1px solid var(--line);border-radius:10px;margin-bottom:22px;overflow:hidden;}
89
+ .accordion-head{display:flex;align-items:center;gap:10px;padding:14px 18px;cursor:pointer;background:var(--panel-2);user-select:none;}
90
+ .accordion-head svg{width:16px;height:16px;stroke:var(--blue);flex:none;}
91
+ .accordion-title{font-weight:600;font-size:14px;color:var(--navy);flex:1;}
92
+ html[data-theme="dark"] .accordion-title{color:var(--ink);}
93
+ .accordion-chevron{transition:transform .2s;color:var(--muted);flex:none;}
94
+ .accordion.open .accordion-chevron{transform:rotate(180deg);}
95
+ .accordion-body{max-height:0;overflow:hidden;transition:max-height .25s ease;}
96
+ .accordion.open .accordion-body{max-height:600px;}
97
+ .accordion-body-inner{padding:16px 18px;font-size:13px;color:var(--muted);line-height:1.6;}
98
+
99
+ /* ---- geolocate ---- */
100
+ .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;}
101
+ .geo-btn:hover{border-color:var(--blue);}
102
+ .geo-btn svg{width:14px;height:14px;stroke:var(--blue);flex:none;}
103
+ .geo-status{font-size:11px;color:var(--muted);margin-top:6px;min-height:14px;}
104
+
105
+ /* ---- year stepper ---- */
106
+ .year-stepper{display:flex;align-items:stretch;border:1px solid var(--line);border-radius:7px;overflow:hidden;background:var(--panel-2);}
107
+ .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;}
108
+ .year-stepper input::-webkit-outer-spin-button,.year-stepper input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0;}
109
+ .year-stepper .yr-btns{display:flex;flex-direction:column;border-left:1px solid var(--line);flex:none;}
110
+ .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;}
111
+ .year-stepper button:hover{color:var(--blue);background:var(--line);}
112
+ .year-stepper button:first-child{border-bottom:1px solid var(--line);}
113
+
114
+ 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;}
115
+ </style>
116
+ </head>
117
+ <body>
118
+
119
+ <header class="nav">
120
+ <div class="nav-inner">
121
+ <div class="nav-left">
122
+ <div class="nav-brand">
123
+ <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>
124
+ SenClim
125
+ </div>
126
+ </div>
127
+ <div class="nav-right">
128
+ <div class="toggle-group" id="lang-toggle">
129
+ <button class="toggle-btn active" data-lang="fr">FR</button>
130
+ <button class="toggle-btn" data-lang="en">EN</button>
131
+ <button class="toggle-btn" data-lang="wo">WO</button>
132
+ </div>
133
+ <div class="toggle-group" id="theme-toggle">
134
+ <button class="toggle-btn active" data-theme-val="light" data-i18n="themeLight">Clair</button>
135
+ <button class="toggle-btn" data-theme-val="dark" data-i18n="themeDark">Sombre</button>
136
+ </div>
137
+ </div>
138
+ </div>
139
+ </header>
140
+
141
+ <main class="wrap">
142
+
143
+ <div class="tab-panel active" id="tab-climate">
144
+ <div class="page-title" data-i18n="climateTitle">Climat &amp; tendances — régions du Sénégal</div>
145
+ <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>
146
+
147
+ <div class="accordion" id="about-accordion">
148
+ <div class="accordion-head" id="about-head">
149
+ <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>
150
+ <span class="accordion-title" data-i18n="aboutTitle">À propos de cette page</span>
151
+ <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>
152
+ </div>
153
+ <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>
154
+ </div>
155
+
156
+ <div class="layout">
157
+ <div class="panel">
158
+ <div class="field">
159
+ <label data-i18n="fieldRegion">Région</label>
160
+ <select id="sel-region"></select>
161
+ <button class="geo-btn" id="btn-geolocate" type="button">
162
+ <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>
163
+ <span data-i18n="geolocateBtn">Me géolocaliser</span>
164
+ </button>
165
+ <div class="geo-status" id="geo-status"></div>
166
+ </div>
167
+ <div class="field">
168
+ <label data-i18n="fieldYear">Année</label>
169
+ <div class="year-stepper">
170
+ <input type="number" id="year-input" inputmode="numeric">
171
+ <div class="yr-btns">
172
+ <button type="button" id="year-up" aria-label="+1">▲</button>
173
+ <button type="button" id="year-down" aria-label="-1">▼</button>
174
+ </div>
175
+ </div>
176
+ </div>
177
+ <button class="submit-btn" id="btn-submit" data-i18n="submitBtn">Générer</button>
178
+ <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>
179
+ </div>
180
+
181
+ <div class="charts-col">
182
+ <div class="chart-card">
183
+ <div class="chart-card-head"><h3 id="title-cum">☔ Cumul de précipitations</h3><span class="meta" id="meta-cum">—</span></div>
184
+ <div class="chart-legend-row">
185
+ <span><span class="legend-sw" style="background:var(--grey-band)"></span><span data-i18n="legendPercentile">5–95e percentile</span></span>
186
+ <span><span class="legend-sw" style="background:var(--grey-line)"></span><span data-i18n="legendMedian">Médiane historique</span></span>
187
+ <span><span class="legend-sw" style="background:var(--ink)"></span><span data-i18n="legendSelYear">Année sélectionnée</span></span>
188
+ </div>
189
+ <div class="stat-row" id="stats-cum"></div>
190
+ <div id="cum-body"><div class="loading" data-i18n="climateHint">Sélectionnez une région et cliquez sur « Générer ».</div></div>
191
+ </div>
192
+
193
+ <div class="chart-card">
194
+ <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>
195
+ <div class="chart-legend-row">
196
+ <span><span class="legend-sw" style="background:var(--blue)"></span><span data-i18n="legendSurplus">Excédent vs normale</span></span>
197
+ <span><span class="legend-sw" style="background:var(--amber)"></span><span data-i18n="legendDeficit">Déficit vs normale</span></span>
198
+ <span><span class="legend-sw" style="background:var(--grey-line)"></span><span data-i18n="legendMedian">Médiane historique</span></span>
199
+ </div>
200
+ <div class="stat-row" id="stats-30d"></div>
201
+ <div id="rain30-cum-body"><div class="loading">—</div></div>
202
+ <div class="chart-legend-row" style="margin-top:14px"><span data-i18n="dailyRainLabel">Pluie journalière (mm)</span></div>
203
+ <div id="rain30-bar-body"></div>
204
+ </div>
205
+
206
+ <div class="chart-card">
207
+ <div class="chart-card-head">
208
+ <h3 data-i18n="detailChartTitle2">🌦️ Pluie, probabilité &amp; ensoleillement — 7 jours</h3>
209
+ </div>
210
+ <div class="chart-legend-row">
211
+ <span><span class="legend-sw" style="background:var(--blue)"></span><span data-i18n="legendPrecipBar">Pluie prévue (mm)</span></span>
212
+ <span><span class="legend-sw" style="background:#f0d98a"></span><span data-i18n="legendSunshine">Ensoleillement (h)</span></span>
213
+ <span><span class="legend-sw" style="background:var(--grey-line)"></span><span data-i18n="legendModelSpread">Écart min–max multi-modèle</span></span>
214
+ </div>
215
+ <div class="stat-row" id="stats-detail"></div>
216
+ <div id="detail-chart-body"><div class="loading">—</div></div>
217
+ </div>
218
+
219
+ <div class="chart-card">
220
+ <div class="chart-card-head">
221
+ <h3 data-i18n="monthlyHeatmapTitle">🗓️ Historique pluviométrique par mois</h3>
222
+ </div>
223
+ <div id="monthly-heatmap-legend" class="chart-legend-row"></div>
224
+ <div id="monthly-heatmap-body"><div class="loading">—</div></div>
225
+ </div>
226
+
227
+ <div class="chart-card">
228
+ <div class="chart-card-head"><h3 data-i18n="monthlyNormalsTitle">📊 Normales mensuelles</h3><span class="meta" id="meta-monthly-norm">—</span></div>
229
+ <div class="chart-legend-row">
230
+ <span><span class="legend-sw" style="background:var(--blue)"></span><span data-i18n="legendMonthlyPrecip">Cumul moyen (mm)</span></span>
231
+ <span><span class="legend-sw" style="background:var(--amber)"></span><span data-i18n="legendRainyDays">Jours de pluie moyens</span></span>
232
+ </div>
233
+ <div id="monthly-normals-body"><div class="loading">—</div></div>
234
+ </div>
235
+ </div>
236
+ </div>
237
+ </div>
238
+
239
+ </main>
240
+
241
+ <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>
242
+
243
+ <script>
244
+ /* Visible error banner — surfaces any JS failure directly on the page, no devtools needed. */
245
+ window.addEventListener('error', function(e){
246
+ let b = document.getElementById('debug-banner');
247
+ if(!b){
248
+ b = document.createElement('div');
249
+ b.id = 'debug-banner';
250
+ 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;';
251
+ document.body.prepend(b);
252
+ }
253
+ b.textContent = 'Erreur JS : ' + e.message + ' (ligne ' + e.lineno + ')';
254
+ });
255
+ </script>
256
+ <script>
257
+ /* ============================= DATA ============================= */
258
+ const REGIONS = [
259
+ {name:'Dakar', lat:14.7167, lon:-17.4677},
260
+ {name:'Thiès', lat:14.7910, lon:-16.9359},
261
+ {name:'Diourbel', lat:14.6522, lon:-16.2317},
262
+ {name:'Fatick', lat:14.3390, lon:-16.4110},
263
+ {name:'Kaolack', lat:14.1652, lon:-16.0726},
264
+ {name:'Kaffrine', lat:14.1059, lon:-15.5508},
265
+ {name:'Louga', lat:15.6173, lon:-16.2240},
266
+ {name:'Saint-Louis', lat:16.0179, lon:-16.4896},
267
+ {name:'Matam', lat:15.6559, lon:-13.2554},
268
+ {name:'Tambacounda', lat:13.7707, lon:-13.6673},
269
+ {name:'Kédougou', lat:12.5556, lon:-12.1746},
270
+ {name:'Kolda', lat:12.8983, lon:-14.9412},
271
+ {name:'Sédhiou', lat:12.7081, lon:-15.5569},
272
+ {name:'Ziguinchor', lat:12.5833, lon:-16.2719}
273
+ ];
274
+ const MONTHS = {
275
+ fr:['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'],
276
+ en:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
277
+ wo:['Sam','Few','Mar','Awr','Me','Suw','Sul','Ut','Sàt','Okt','Now','Des']
278
+ };
279
+
280
+ /* ============================= I18N ============================= */
281
+ const I18N = {
282
+ fr: {
283
+ themeLight:'Clair', themeDark:'Sombre',
284
+ aboutTitle:'À propos de cette page',
285
+ 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.",
286
+ 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.",
287
+ geoFound:(name,km)=>`Région la plus proche : ${name} (~${km} km).`,
288
+ climateTitle:"Climat &amp; tendances — régions du Sénégal",
289
+ 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.",
290
+ fieldRegion:'Région', fieldYear:'Année',
291
+ submitBtn:'Générer',
292
+ 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.",
293
+ legendPercentile:'5–95e percentile', legendMedian:'Médiane historique', legendSelYear:'Année sélectionnée',
294
+ climateHint:"Sélectionnez une région et cliquez sur « Générer ».",
295
+ cumTitle:(r,y)=>`☔ Cumul de précipitations — ${r}, ${y}`,
296
+ rain30Title:r=>`📅 Pluie des 30 derniers jours vs normale — ${r}`,
297
+ legendSurplus:'Excédent vs normale', legendDeficit:'Déficit vs normale', dailyRainLabel:'Pluie journalière (mm)',
298
+ metaRef:(r,n)=>`${r} · ERA5 · ${n} années de référence`,
299
+ todayLabel:"AUJOURD'HUI",
300
+ 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.`,
301
+ detailChartTitle2:'🌦️ Pluie, probabilité &amp; ensoleillement — 7 jours',
302
+ legendPrecipBar:'Pluie prévue (mm)', legendSunshine:'Ensoleillement (h)', legendModelSpread:'Écart min–max multi-modèle',
303
+ sunshineUnit:'h',
304
+ loadingForecast:'Chargement des prévisions…', errorPrefix:'Erreur : ',
305
+ 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.",
306
+ monthlyHeatmapTitle:'🗓️ Historique pluviométrique par mois', monthlyNormalsTitle:'📊 Normales mensuelles',
307
+ legendMonthlyPrecip:'Cumul moyen (mm)', legendRainyDays:'Jours de pluie moyens',
308
+ loadingClimate:"Analyse des archives ERA5…",
309
+ 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'
310
+ },
311
+ en: {
312
+ themeLight:'Light', themeDark:'Dark',
313
+ aboutTitle:'About this page',
314
+ 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.",
315
+ geolocateBtn:'Use my location', geoLocating:'Locating…', geoError:'Could not get your location.', geoUnsupported:'Geolocation is not available on this device.',
316
+ geoFound:(name,km)=>`Nearest region: ${name} (~${km} km).`,
317
+ climateTitle:"Climate &amp; trends — Senegal regions",
318
+ climateSub:"Cumulative rainfall, 7-day forecast and monthly history for the selected region. ERA5 &amp; Open-Meteo data, computed live in your browser.",
319
+ fieldRegion:'Region', fieldYear:'Year',
320
+ submitBtn:'Generate',
321
+ 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.",
322
+ legendPercentile:'5–95th percentile', legendMedian:'Historical median', legendSelYear:'Selected year',
323
+ climateHint:'Select a region and click "Generate".',
324
+ cumTitle:(r,y)=>`☔ Cumulative rainfall — ${r}, ${y}`,
325
+ rain30Title:r=>`📅 Last 30 days rainfall vs normal — ${r}`,
326
+ legendSurplus:'Surplus vs normal', legendDeficit:'Deficit vs normal', dailyRainLabel:'Daily rainfall (mm)',
327
+ metaRef:(r,n)=>`${r} · ERA5 · ${n} reference years`,
328
+ todayLabel:'TODAY',
329
+ chartErr:m=>`Chart.js could not be loaded from the CDN (${m}). Check the network connection or a script blocker, then reload the page.`,
330
+ detailChartTitle2:'🌦️ Rain, probability &amp; sunshine — 7 days',
331
+ legendPrecipBar:'Forecast rain (mm)', legendSunshine:'Sunshine (h)', legendModelSpread:'Multi-model min–max spread',
332
+ sunshineUnit:'h',
333
+ loadingForecast:'Loading forecasts…', errorPrefix:'Error: ',
334
+ rateLimitError:"Too many requests sent to Open-Meteo in a short time (free API limit reached). Wait a minute, then try again.",
335
+ monthlyHeatmapTitle:'🗓️ Rainfall history by month', monthlyNormalsTitle:'📊 Monthly normals',
336
+ legendMonthlyPrecip:'Average total (mm)', legendRainyDays:'Average rainy days',
337
+ loadingClimate:'Analyzing ERA5 archives…',
338
+ 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'
339
+ },
340
+ wo: {
341
+ themeLight:'Sedd', themeDark:'Lëndëm',
342
+ aboutTitle:'Ci mbir mi',
343
+ 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.",
344
+ geolocateBtn:'Wone fu nekk', geoLocating:'Dañuy seet fu nekk…', geoError:'Mënula am fu nekk.', geoUnsupported:'Geolocation amul ci sa jumtukaay.',
345
+ geoFound:(name,km)=>`Dëkk bu gëna jege: ${name} (~${km} km).`,
346
+ climateTitle:"Tàngoor ak jëf — dëkk yi ci Senegaal",
347
+ 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.",
348
+ fieldRegion:'Dëkk', fieldYear:'At',
349
+ submitBtn:'Def ko',
350
+ 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.",
351
+ legendPercentile:'5–95e percentile', legendMedian:'Tàngoor jaar-jaar', legendSelYear:'At bi ñu tann',
352
+ climateHint:'Tann dëkk te dàq ci « Def ko ».',
353
+ cumTitle:(r,y)=>`☔ Taw mu dajale — ${r}, ${y}`,
354
+ rain30Title:r=>`📅 Taw ci 30 fan yu weesu vs normale — ${r}`,
355
+ legendSurplus:'Ëpp na normale', legendDeficit:'Néew na normale', dailyRainLabel:'Taw bés bu nekk (mm)',
356
+ metaRef:(r,n)=>`${r} · ERA5 · ${n} at yu jiitu`,
357
+ todayLabel:'TEY',
358
+ chartErr:m=>`Mënula yónnee Chart.js (${m}). Xool sa réseau walla bloqueur script, def refresh xët bi.`,
359
+ detailChartTitle2:'🌦️ Taw, jarul ak jant — 7 fan',
360
+ legendPrecipBar:'Taw bi ñuy xaar (mm)', legendSunshine:'Jant (h)', legendModelSpread:'Diggante model yi',
361
+ sunshineUnit:'h',
362
+ loadingForecast:'Dañuy yónnee xibaar taw yi…', errorPrefix:'Njumte: ',
363
+ 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.",
364
+ monthlyHeatmapTitle:'🗓️ Jaar-jaar taw ci weer', monthlyNormalsTitle:'📊 Normales weer',
365
+ legendMonthlyPrecip:'Cumul digg (mm)', legendRainyDays:'Bés yu taw yu digg',
366
+ loadingClimate:'Dañuy xool archive ERA5 yi…',
367
+ 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'
368
+ }
369
+ };
370
+ let currentLang = 'fr';
371
+ let currentTheme = 'light';
372
+
373
+ /* ============================= I18N APPLY ============================= */
374
+ function applyI18n(){
375
+ const t = I18N[currentLang];
376
+ document.querySelectorAll('[data-i18n]').forEach(el=>{
377
+ const key = el.getAttribute('data-i18n');
378
+ if(typeof t[key] === 'string') el.innerHTML = t[key];
379
+ });
380
+ document.getElementById('lang-toggle').querySelectorAll('.toggle-btn').forEach(b=>b.classList.toggle('active', b.dataset.lang===currentLang));
381
+ document.documentElement.lang = currentLang;
382
+ const region = document.getElementById('sel-region').value;
383
+ if(region) refreshClimateTitles();
384
+ }
385
+
386
+ /* ============================= THEME / LANG TOGGLES ============================= */
387
+ document.getElementById('theme-toggle').addEventListener('click', e=>{
388
+ const btn = e.target.closest('.toggle-btn'); if(!btn) return;
389
+ currentTheme = btn.dataset.themeVal;
390
+ document.documentElement.setAttribute('data-theme', currentTheme);
391
+ document.querySelectorAll('#theme-toggle .toggle-btn').forEach(b=>b.classList.toggle('active', b===btn));
392
+ const region = document.getElementById('sel-region').value;
393
+ if(cumChart) generate();
394
+ if(detailChart) loadDetailChart(region);
395
+ if(monthlyLoadedRegion) loadMonthlyClimate(region);
396
+ });
397
+ document.getElementById('lang-toggle').addEventListener('click', e=>{
398
+ const btn = e.target.closest('.toggle-btn'); if(!btn) return;
399
+ currentLang = btn.dataset.lang;
400
+ applyI18n();
401
+ });
402
+
403
+ /* ============================= CHART THEME COLORS ============================= */
404
+ function chartColors(){
405
+ return currentTheme==='dark'
406
+ ? { 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)' }
407
+ : { 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)' };
408
+ }
409
+
410
+ /* ============================= PERCENTILE / ARCHIVE ============================= */
411
+ function percentile(arr,p){
412
+ const s=arr.filter(v=>v!=null&&!isNaN(v)).slice().sort((a,b)=>a-b);
413
+ if(!s.length) return null;
414
+ const idx=Math.min(s.length-1,Math.max(0,Math.ceil((p/100)*s.length)-1));
415
+ return s[idx];
416
+ }
417
+ function explainFetchError(err){
418
+ const t = I18N[currentLang];
419
+ if(err && /HTTP 429/.test(err.message)) return t.rateLimitError;
420
+ return t.errorPrefix + (err ? err.message : '');
421
+ }
422
+ /* Optional: paste a free Open-Meteo API key here (https://open-meteo.com/en/pricing) to get your
423
+ own request quota instead of sharing the anonymous-IP limit with everyone on your network.
424
+ Leave empty to use the free anonymous endpoints exactly as before — nothing else changes. */
425
+ const OPEN_METEO_API_KEY = '';
426
+ function omKeyed(url){
427
+ if(!OPEN_METEO_API_KEY) return url;
428
+ return url
429
+ .replace('https://api.open-meteo.com','https://customer-api.open-meteo.com')
430
+ .replace('https://archive-api.open-meteo.com','https://customer-archive-api.open-meteo.com')
431
+ + '&apikey=' + OPEN_METEO_API_KEY;
432
+ }
433
+ async function fetchWithRetry(url, retries=2, delay=3000){
434
+ url = omKeyed(url);
435
+ for(let attempt=0; attempt<=retries; attempt++){
436
+ const res = await fetch(url);
437
+ if(res.status !== 429 || attempt === retries) return res;
438
+ await new Promise(r=>setTimeout(r, delay));
439
+ delay *= 2;
440
+ }
441
+ }
442
+ function localCacheGet(key, maxAgeMs){
443
+ try{
444
+ const raw = localStorage.getItem(key);
445
+ if(!raw) return null;
446
+ const {ts, data} = JSON.parse(raw);
447
+ if(Date.now() - ts > maxAgeMs) return null;
448
+ return data;
449
+ }catch(e){ return null; }
450
+ }
451
+ function localCacheSet(key, data){
452
+ try{ localStorage.setItem(key, JSON.stringify({ts:Date.now(), data})); }catch(e){}
453
+ }
454
+ let archiveCache = {};
455
+ function fetchArchive(region){
456
+ if(archiveCache[region]) return archiveCache[region];
457
+ const cacheKey = 'sc_archive_'+region;
458
+ const cached = localCacheGet(cacheKey, 12*3600*1000);
459
+ if(cached){ const p = Promise.resolve(cached); archiveCache[region] = p; return p; }
460
+ const r = REGIONS.find(x=>x.name===region);
461
+ const now = new Date();
462
+ const startYear = now.getFullYear()-30;
463
+ const yesterday = new Date(now); yesterday.setDate(yesterday.getDate()-1);
464
+ const end = yesterday.toISOString().slice(0,10);
465
+ 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`;
466
+ const promise = fetchWithRetry(url).then(res=>{
467
+ if(!res.ok) throw new Error('HTTP '+res.status);
468
+ return res.json();
469
+ }).then(data=> data.daily).then(daily=>{ localCacheSet(cacheKey, daily); return daily; });
470
+ archiveCache[region] = promise;
471
+ promise.catch(()=>{ delete archiveCache[region]; });
472
+ return promise;
473
+ }
474
+ function organizeByYear(daily){
475
+ const byYear = {};
476
+ daily.time.forEach((t,i)=>{
477
+ const d = new Date(t+'T00:00:00');
478
+ if(d.getMonth()===1 && d.getDate()===29) return;
479
+ const year = d.getFullYear();
480
+ const start = new Date(year,0,1);
481
+ let doy = Math.floor((d-start)/86400000)+1;
482
+ if(doy>365) doy=365;
483
+ 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) };
484
+ byYear[year].precip[doy-1] = daily.precipitation_sum[i];
485
+ byYear[year].tmean[doy-1] = daily.temperature_2m_mean[i];
486
+ byYear[year].tmax[doy-1] = daily.temperature_2m_max[i];
487
+ byYear[year].tmin[doy-1] = daily.temperature_2m_min[i];
488
+ });
489
+ Object.values(byYear).forEach(y=>{
490
+ let acc=0, lastValid=-1;
491
+ y.precip.forEach((v,i)=>{ if(v!=null) lastValid=i; });
492
+ y.cumPrecip = y.precip.map((v,i)=>{ acc += (v||0); return i<=lastValid ? acc : null; });
493
+ });
494
+ return byYear;
495
+ }
496
+
497
+ /* ============================= CUSTOM CHART PLUGINS ============================= */
498
+ const todayLinePlugin = {
499
+ id:'todayLine',
500
+ afterDraw(chart, args, opts){
501
+ if(!opts || opts.index==null) return;
502
+ const {ctx, chartArea, scales} = chart;
503
+ const x = scales.x.getPixelForValue(opts.index);
504
+ if(x < chartArea.left || x > chartArea.right) return;
505
+ ctx.save();
506
+ ctx.strokeStyle = opts.gridColor||'#9aa1b0'; ctx.setLineDash([4,3]); ctx.lineWidth = 1;
507
+ ctx.beginPath(); ctx.moveTo(x, chartArea.top); ctx.lineTo(x, chartArea.bottom); ctx.stroke();
508
+ ctx.setLineDash([]);
509
+ ctx.fillStyle = opts.textColor||'#626c8c'; ctx.font = '10px IBM Plex Mono, monospace';
510
+ ctx.save(); ctx.translate(x-6, chartArea.top+4); ctx.rotate(-Math.PI/2); ctx.fillText(opts.label||"AUJOURD'HUI", 0, 0); ctx.restore();
511
+ ctx.restore();
512
+ }
513
+ };
514
+ const pointLabelPlugin = {
515
+ id:'pointLabel',
516
+ afterDraw(chart, args, opts){
517
+ if(!opts || !opts.points) return;
518
+ const {ctx, scales} = chart;
519
+ opts.points.forEach(p=>{
520
+ if(p.index==null || p.value==null) return;
521
+ const x = scales.x.getPixelForValue(p.index);
522
+ const y = scales.y.getPixelForValue(p.value);
523
+ ctx.save();
524
+ ctx.fillStyle = p.color || '#171d2e';
525
+ ctx.beginPath(); ctx.arc(x,y,4,0,Math.PI*2); ctx.fill();
526
+ ctx.font = '600 11px IBM Plex Mono, monospace';
527
+ ctx.textAlign = p.align || 'left';
528
+ ctx.fillText(p.label, x + (p.align==='right'?-8:8), y - 8);
529
+ ctx.restore();
530
+ });
531
+ }
532
+ };
533
+ const whiskerDiamondPlugin = {
534
+ id:'whiskerDiamond',
535
+ afterDatasetsDraw(chart, args, opts){
536
+ if(!opts || !opts.mins) return;
537
+ const {ctx, scales, chartArea} = chart;
538
+ const xScale = scales.x, yScale = scales.y;
539
+ opts.mins.forEach((minV,i)=>{
540
+ const maxV = opts.maxs[i], meanV = opts.means ? opts.means[i] : null;
541
+ if(minV==null || maxV==null) return;
542
+ const x = xScale.getPixelForValue(i);
543
+ const yMin = Math.min(yScale.getPixelForValue(minV), chartArea.bottom);
544
+ const yMax = Math.max(yScale.getPixelForValue(maxV), chartArea.top);
545
+ ctx.save();
546
+ ctx.strokeStyle = opts.color || '#8a8f9c'; ctx.lineWidth = 1.4;
547
+ const capW = 7;
548
+ ctx.beginPath(); ctx.moveTo(x, yMin); ctx.lineTo(x, yMax); ctx.stroke();
549
+ ctx.beginPath(); ctx.moveTo(x-capW, yMin); ctx.lineTo(x+capW, yMin); ctx.stroke();
550
+ if(yScale.getPixelForValue(maxV) >= chartArea.top){
551
+ ctx.beginPath(); ctx.moveTo(x-capW, yMax); ctx.lineTo(x+capW, yMax); ctx.stroke();
552
+ }
553
+ if(meanV!=null){
554
+ const yMean = Math.max(chartArea.top+4, Math.min(chartArea.bottom-4, yScale.getPixelForValue(meanV))), s=5;
555
+ ctx.fillStyle = opts.diamondColor || '#c98a12';
556
+ ctx.beginPath();
557
+ ctx.moveTo(x, yMean-s); ctx.lineTo(x+s, yMean); ctx.lineTo(x, yMean+s); ctx.lineTo(x-s, yMean); ctx.closePath();
558
+ ctx.fill();
559
+ }
560
+ ctx.restore();
561
+ });
562
+ }
563
+ };
564
+ const barLabelPlugin = {
565
+ id:'barLabel',
566
+ afterDatasetsDraw(chart, args, opts){
567
+ if(!opts || !opts.items) return;
568
+ const {ctx, scales} = chart;
569
+ opts.items.forEach(item=>{
570
+ const x = scales[item.xScaleId||'x'].getPixelForValue(item.index);
571
+ const y = scales[item.yScaleId||'y'].getPixelForValue(item.y);
572
+ ctx.save();
573
+ ctx.fillStyle = item.color || '#171d2e';
574
+ ctx.font = item.font || '600 11px IBM Plex Mono, monospace';
575
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
576
+ ctx.fillText(item.text, x, y);
577
+ ctx.restore();
578
+ });
579
+ }
580
+ };
581
+
582
+ /* ============================= REGION / YEAR CONTROLS ============================= */
583
+ function initSelects(){
584
+ const regionSel = document.getElementById('sel-region');
585
+ regionSel.innerHTML = REGIONS.map(r=>`<option value="${r.name}">${r.name}</option>`).join('');
586
+ initYearInput();
587
+ }
588
+ function initYearInput(){
589
+ const curYear = new Date().getFullYear();
590
+ const input = document.getElementById('year-input');
591
+ input.min = curYear - 9; input.max = curYear; input.step = 1; input.value = curYear;
592
+ }
593
+ function currentYearValue(){
594
+ const input = document.getElementById('year-input');
595
+ let v = parseInt(input.value, 10);
596
+ const min = parseInt(input.min,10), max = parseInt(input.max,10);
597
+ if(isNaN(v)) v = max;
598
+ v = Math.min(max, Math.max(min, v));
599
+ input.value = v;
600
+ return v;
601
+ }
602
+ document.getElementById('year-up').addEventListener('click', ()=>{
603
+ const input = document.getElementById('year-input');
604
+ input.value = Math.min(parseInt(input.max,10), currentYearValue()+1);
605
+ });
606
+ document.getElementById('year-down').addEventListener('click', ()=>{
607
+ const input = document.getElementById('year-input');
608
+ input.value = Math.max(parseInt(input.min,10), currentYearValue()-1);
609
+ });
610
+
611
+ /* ---- accordion ---- */
612
+ document.getElementById('about-head').addEventListener('click', ()=>{
613
+ document.getElementById('about-accordion').classList.toggle('open');
614
+ });
615
+
616
+ /* ---- geolocation (no map, just nearest-region lookup) ---- */
617
+ function haversineKm(lat1,lon1,lat2,lon2){
618
+ const toRad = d=>d*Math.PI/180, R=6371;
619
+ const dLat=toRad(lat2-lat1), dLon=toRad(lon2-lon1);
620
+ const a = Math.sin(dLat/2)**2 + Math.cos(toRad(lat1))*Math.cos(toRad(lat2))*Math.sin(dLon/2)**2;
621
+ return 2*R*Math.asin(Math.sqrt(a));
622
+ }
623
+ document.getElementById('btn-geolocate').addEventListener('click', ()=>{
624
+ const status = document.getElementById('geo-status');
625
+ const t = I18N[currentLang];
626
+ if(!navigator.geolocation){ status.textContent = t.geoUnsupported; return; }
627
+ status.textContent = t.geoLocating;
628
+ navigator.geolocation.getCurrentPosition(pos=>{
629
+ const {latitude, longitude} = pos.coords;
630
+ let best=null, bestD=Infinity;
631
+ REGIONS.forEach(r=>{ const d=haversineKm(latitude,longitude,r.lat,r.lon); if(d<bestD){bestD=d; best=r;} });
632
+ if(best){
633
+ document.getElementById('sel-region').value = best.name;
634
+ status.textContent = t.geoFound(best.name, Math.round(bestD));
635
+ loadAll(best.name);
636
+ }
637
+ }, ()=>{ status.textContent = t.geoError; }, {timeout:8000});
638
+ });
639
+
640
+ let cumChart=null, lastClimateResult=null;
641
+
642
+ function buildCumulativeChart(byYear, region, selYear){
643
+ const t = I18N[currentLang], C = chartColors();
644
+ const pastYears = Object.keys(byYear).map(Number).filter(y=>y!==selYear).sort((a,b)=>a-b);
645
+ const nBuckets = 73, bucketEnds = Array.from({length:nBuckets},(_,i)=>Math.min(365,(i+1)*5)-1);
646
+ const band = bucketEnds.map(idx=>{
647
+ const vals = pastYears.map(y=>byYear[y] && byYear[y].cumPrecip[idx]).filter(v=>v!=null);
648
+ return {p5:percentile(vals,5), p50:percentile(vals,50), p95:percentile(vals,95)};
649
+ });
650
+ const selArr = byYear[selYear] ? bucketEnds.map(idx=>byYear[selYear].cumPrecip[idx] ?? null) : bucketEnds.map(()=>null);
651
+ let lastIdx=-1; selArr.forEach((v,i)=>{ if(v!=null) lastIdx=i; });
652
+ const isCurrentYear = selYear === new Date().getFullYear();
653
+ const selTrimmed = isCurrentYear ? selArr.map((v,i)=> i<=lastIdx ? v : null) : selArr;
654
+ const todayLabelIdx = isCurrentYear ? lastIdx : -1;
655
+
656
+ document.getElementById('cum-body').innerHTML = '<canvas id="chart-cum"></canvas>';
657
+ const ctx = document.getElementById('chart-cum').getContext('2d');
658
+ const months = MONTHS[currentLang];
659
+ const labels = bucketEnds.map(idx=>{ const d=new Date(selYear,0,idx+1); return d.getDate()<=5 ? months[d.getMonth()] : ''; });
660
+ if(cumChart) cumChart.destroy();
661
+ cumChart = new Chart(ctx,{
662
+ type:'line',
663
+ data:{ labels, datasets:[
664
+ {label:'p5', data:band.map(b=>b.p5), borderWidth:0, pointRadius:0, fill:false},
665
+ {label:t.legendPercentile, data:band.map(b=>b.p95), borderWidth:0, pointRadius:0, backgroundColor:C.band, fill:'-1'},
666
+ {label:t.legendMedian, data:band.map(b=>b.p50), borderColor:C.median, borderDash:[4,3], borderWidth:1.3, pointRadius:0, fill:false},
667
+ {label:String(selYear), data:selTrimmed, borderColor:C.line, backgroundColor:'rgba(59,110,165,0.08)', borderWidth:2.5, pointRadius:0, pointHoverRadius:4, fill:'origin'}
668
+ ]},
669
+ options:{responsive:true, maintainAspectRatio:false,
670
+ interaction:{mode:'index', intersect:false},
671
+ plugins:{ legend:{display:false},
672
+ tooltip:{ filter:(item)=>item.dataset.label!=='p5', callbacks:{ label:(item)=> `${item.dataset.label}: ${item.parsed.y!=null?item.parsed.y.toFixed(0)+' mm':'—'}` } },
673
+ todayLine: todayLabelIdx>=0 ? {index:todayLabelIdx, textColor:C.text, gridColor:C.grid, label:t.todayLabel} : null,
674
+ pointLabel: todayLabelIdx>=0 ? {points:[{index:todayLabelIdx, value:selTrimmed[todayLabelIdx], label:(selTrimmed[todayLabelIdx]||0).toFixed(1)+' mm', color:C.line}]} : null
675
+ },
676
+ scales:{ x:{ticks:{color:C.text,autoSkip:false,maxRotation:0}, grid:{color:C.grid}},
677
+ y:{ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}} } }
678
+ });
679
+ document.getElementById('meta-cum').textContent = t.metaRef(region, pastYears.length);
680
+ const todayCum = todayLabelIdx>=0 ? selTrimmed[todayLabelIdx] : null;
681
+ const normalToDate = todayLabelIdx>=0 ? band[todayLabelIdx].p50 : null;
682
+ const anomaly = (todayCum!=null && normalToDate!=null) ? todayCum - normalToDate : null;
683
+ const anomalyPct = (anomaly!=null && normalToDate>0) ? (anomaly/normalToDate*100) : null;
684
+ document.getElementById('stats-cum').innerHTML = isCurrentYear ? `
685
+ <div class="stat"><div class="k">Cumul à ce jour</div><div class="v">${todayCum!=null?todayCum.toFixed(0)+' mm':'—'}</div></div>
686
+ <div class="stat"><div class="k">Normale à ce jour</div><div class="v">${normalToDate!=null?normalToDate.toFixed(0)+' mm':'—'}</div></div>
687
+ <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>
688
+ ` : '';
689
+ return {band, selTrimmed, lastIdx, isCurrentYear};
690
+ }
691
+
692
+ function refreshClimateTitles(){
693
+ const t = I18N[currentLang];
694
+ const region = document.getElementById('sel-region').value;
695
+ const selYear = currentYearValue();
696
+ document.getElementById('title-cum').textContent = t.cumTitle(region, selYear);
697
+ document.getElementById('title-30d').textContent = t.rain30Title(region);
698
+ }
699
+
700
+ /* ---- trailing 30-day rainfall vs normal (RFE2-style) ---- */
701
+ let rain30ChartCum=null, rain30ChartBar=null;
702
+ async function fetchRecent30(region){
703
+ const cacheKey = 'sc_recent30_'+region;
704
+ const cached = localCacheGet(cacheKey, 3*3600*1000);
705
+ if(cached) return cached;
706
+ const r = REGIONS.find(x=>x.name===region);
707
+ 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`;
708
+ const res = await fetchWithRetry(url); if(!res.ok) throw new Error('HTTP '+res.status);
709
+ const data = await res.json();
710
+ localCacheSet(cacheKey, data.daily);
711
+ return data.daily;
712
+ }
713
+ function dayOfYearOf(d){ const start=new Date(d.getFullYear(),0,1); let doy=Math.floor((d-start)/86400000)+1; return doy>365?365:doy; }
714
+ function computeNormalForDates(byYear, dates, excludeYear){
715
+ const years = Object.keys(byYear).map(Number).filter(y=>y!==excludeYear);
716
+ return dates.map(d=>{
717
+ const doy = dayOfYearOf(d);
718
+ const vals = years.map(y=>byYear[y].precip[doy-1]).filter(v=>v!=null);
719
+ return vals.length ? vals.reduce((a,b)=>a+b,0)/vals.length : 0;
720
+ });
721
+ }
722
+ async function buildRain30(region){
723
+ const t = I18N[currentLang], C = chartColors();
724
+ document.getElementById('rain30-cum-body').innerHTML = '<canvas id="chart-rain30-cum"></canvas>';
725
+ document.getElementById('rain30-bar-body').innerHTML = '<canvas id="chart-rain30-bar"></canvas>';
726
+ try{
727
+ const [recent, archiveDaily] = await Promise.all([fetchRecent30(region), fetchArchive(region)]);
728
+ const byYear = organizeByYear(archiveDaily);
729
+ const times = recent.time.slice(0,-1);
730
+ const precs = recent.precipitation_sum.slice(0,-1).map(v=>v==null?0:v);
731
+ const dates = times.map(s=>new Date(s+'T00:00:00'));
732
+ const normalsDaily = computeNormalForDates(byYear, dates, new Date().getFullYear());
733
+ let accA=0, accN=0;
734
+ const actualCum = precs.map(v=>{ accA+=v; return accA; });
735
+ const normalCum = normalsDaily.map(v=>{ accN+=v; return accN; });
736
+ const above = actualCum.map((v,i)=>Math.max(v, normalCum[i]));
737
+ const below = actualCum.map((v,i)=>Math.min(v, normalCum[i]));
738
+ const months = MONTHS[currentLang];
739
+ const labels = dates.map(d=>d.getDate()+' '+months[d.getMonth()]);
740
+
741
+ const ctxCum = document.getElementById('chart-rain30-cum').getContext('2d');
742
+ if(rain30ChartCum) rain30ChartCum.destroy();
743
+ rain30ChartCum = new Chart(ctxCum,{
744
+ type:'line',
745
+ data:{ labels, datasets:[
746
+ {label:t.legendMedian, data:normalCum, borderColor:C.median, borderDash:[3,3], borderWidth:1.3, pointRadius:0, fill:false},
747
+ {label:t.legendSurplus, data:above, borderWidth:0, pointRadius:0, backgroundColor:C.blue, fill:0},
748
+ {label:t.legendDeficit, data:below, borderWidth:0, pointRadius:0, backgroundColor:C.amber, fill:0},
749
+ {label:region, data:actualCum, borderColor:C.line, borderDash:[2,2], borderWidth:2, pointRadius:0, fill:false}
750
+ ]},
751
+ options:{responsive:true, maintainAspectRatio:false,
752
+ interaction:{mode:'index', intersect:false},
753
+ plugins:{legend:{display:false}, tooltip:{ callbacks:{ label:(item)=> `${item.dataset.label}: ${item.parsed.y!=null?item.parsed.y.toFixed(0)+' mm':'—'}` } }},
754
+ scales:{ x:{ticks:{color:C.text,maxRotation:0,autoSkip:true,maxTicksLimit:8}, grid:{color:C.grid}},
755
+ y:{ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}} } }
756
+ });
757
+
758
+ const ctxBar = document.getElementById('chart-rain30-bar').getContext('2d');
759
+ if(rain30ChartBar) rain30ChartBar.destroy();
760
+ rain30ChartBar = new Chart(ctxBar,{
761
+ type:'bar',
762
+ data:{ labels, datasets:[ {label:t.dailyRainLabel, data:precs, backgroundColor:'#7fbf3f', borderRadius:3} ] },
763
+ options:{responsive:true, maintainAspectRatio:false,
764
+ plugins:{legend:{display:false}, tooltip:{ callbacks:{ label:(item)=> `${item.parsed.y.toFixed(1)} mm` } }},
765
+ scales:{ x:{ticks:{color:C.text,maxRotation:0,autoSkip:true,maxTicksLimit:8}, grid:{display:false}},
766
+ y:{ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}} } }
767
+ });
768
+ document.getElementById('meta-30d').textContent = t.metaRef(region, Object.keys(byYear).filter(y=>Number(y)!==new Date().getFullYear()).length);
769
+ const total30 = actualCum[actualCum.length-1], normal30 = normalCum[normalCum.length-1];
770
+ const gap30 = total30 - normal30, gap30Pct = normal30>0 ? (gap30/normal30*100) : null;
771
+ document.getElementById('stats-30d').innerHTML = `
772
+ <div class="stat"><div class="k">Cumul 30 jours</div><div class="v">${total30.toFixed(0)} mm</div></div>
773
+ <div class="stat"><div class="k">Normale 30 jours</div><div class="v">${normal30.toFixed(0)} mm</div></div>
774
+ <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>
775
+ `;
776
+ }catch(err){
777
+ document.getElementById('rain30-cum-body').innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="buildRain30('${region}')">↻ Réessayer</button></div>`;
778
+ document.getElementById('rain30-bar-body').innerHTML = '';
779
+ document.getElementById('stats-30d').innerHTML = '';
780
+ }
781
+ }
782
+
783
+ async function generate(){
784
+ const t = I18N[currentLang];
785
+ const region = document.getElementById('sel-region').value;
786
+ const selYear = currentYearValue();
787
+ document.getElementById('cum-body').innerHTML = `<div class="loading">${t.climateHint}</div>`;
788
+ document.getElementById('stats-cum').innerHTML = '';
789
+ refreshClimateTitles();
790
+ try{
791
+ const daily = await fetchArchive(region);
792
+ const byYear = organizeByYear(daily);
793
+ lastClimateResult = {byYear, region, selYear};
794
+ buildCumulativeChart(byYear, region, selYear);
795
+ buildRain30(region);
796
+ }catch(err){
797
+ document.getElementById('cum-body').innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="generate()">↻ Réessayer</button></div>`;
798
+ }
799
+ }
800
+
801
+ function fmtValue(varKey,v){ if(v==null||isNaN(v)) return '—'; return varKey==='sum'?v.toFixed(1):Math.round(v); }
802
+
803
+ /* ---- detailed 7-day forecast chart (rain + probability + sunshine + multi-model spread) ---- */
804
+ function detailChartPalette(){
805
+ return currentTheme==='dark'
806
+ ? { bar:'#5b9bd5', sun:'rgba(224,182,78,0.35)', labelOnBar:'#0f1c2e', labelAbove:'#eef1f6', whisker:'#7c88ab', diamond:'#e0b64e' }
807
+ : { bar:'#3b6ea5', sun:'rgba(240,217,138,0.7)', labelOnBar:'#ffffff', labelAbove:'#171d2e', whisker:'#8a8f9c', diamond:'#c98a12' };
808
+ }
809
+ async function fetchForecastDetailData(region){
810
+ const cacheKey = 'sc_detail_'+region;
811
+ const cached = localCacheGet(cacheKey, 3*3600*1000);
812
+ if(cached) return cached;
813
+ const r = REGIONS.find(x=>x.name===region);
814
+ 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`;
815
+ 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`;
816
+ const baseRes = await fetchWithRetry(baseUrl);
817
+ if(!baseRes.ok) throw new Error('HTTP '+baseRes.status);
818
+ const base = await baseRes.json();
819
+ const n = base.daily.time.length;
820
+ let modelMin=null, modelMean=null, modelMax=null;
821
+ try{
822
+ const modelRes = await fetchWithRetry(modelsUrl);
823
+ if(modelRes.ok){
824
+ const modelData = await modelRes.json();
825
+ const keys = Object.keys(modelData.daily).filter(k=>k.startsWith('precipitation_sum_'));
826
+ if(keys.length){
827
+ modelMin = new Array(n).fill(null); modelMean = new Array(n).fill(null); modelMax = new Array(n).fill(null);
828
+ for(let i=0;i<n;i++){
829
+ const vals = keys.map(k=>modelData.daily[k][i]).filter(v=>v!=null);
830
+ if(vals.length){ modelMin[i]=Math.min(...vals); modelMax[i]=Math.max(...vals); modelMean[i]=vals.reduce((a,b)=>a+b,0)/vals.length; }
831
+ }
832
+ }
833
+ }
834
+ }catch(e){}
835
+ const result = { daily: base.daily, modelMin, modelMean, modelMax };
836
+ localCacheSet(cacheKey, result);
837
+ return result;
838
+ }
839
+ let detailChart = null;
840
+ async function loadDetailChart(region){
841
+ const t = I18N[currentLang];
842
+ const body = document.getElementById('detail-chart-body');
843
+ body.innerHTML = `<div class="loading">${t.loadingForecast}</div>`;
844
+ try{
845
+ const { daily, modelMin, modelMean, modelMax } = await fetchForecastDetailData(region);
846
+ const P = detailChartPalette();
847
+ const localeMap = {fr:'fr-FR', en:'en-US', wo:'fr-FR'};
848
+ const labels = daily.time.map(iso=>{
849
+ const d = new Date(iso+'T00:00:00');
850
+ return d.toLocaleDateString(localeMap[currentLang], {weekday:'short', day:'numeric', month:'short'});
851
+ });
852
+ const precip = daily.precipitation_sum.map(v=>v==null?0:v);
853
+ const prob = daily.precipitation_probability_max;
854
+ const sunHours = daily.sunshine_duration.map(v=>v==null?0:v/3600);
855
+ const precipMax = Math.max(1, ...precip);
856
+ const yMax = Math.max(10, Math.ceil((precipMax*1.6)/5)*5);
857
+
858
+ const items = [];
859
+ precip.forEach((v,i)=>{
860
+ const tall = v >= yMax*0.15;
861
+ items.push({ index:i, y: tall ? v*0.9 : v + yMax*0.13, xScaleId:'x', yScaleId:'y',
862
+ text: fmtValue('prob',prob[i])+'%', color: tall ? P.labelOnBar : P.labelAbove });
863
+ });
864
+ sunHours.forEach((h,i)=>{
865
+ items.push({ index:i, y: Math.max(h*0.55, 1), xScaleId:'x2', yScaleId:'y1',
866
+ text: h.toFixed(1)+' '+t.sunshineUnit, color: P.labelAbove, font:'500 11px IBM Plex Mono, monospace' });
867
+ });
868
+
869
+ body.innerHTML = '<canvas id="chart-detail"></canvas>';
870
+ const ctx = document.getElementById('chart-detail').getContext('2d');
871
+ const C = chartColors();
872
+ if(detailChart) detailChart.destroy();
873
+ detailChart = new Chart(ctx,{
874
+ type:'bar',
875
+ data:{ labels, datasets:[
876
+ { label:'Ensoleillement', data: sunHours, xAxisID:'x2', yAxisID:'y1', backgroundColor:P.sun, barPercentage:0.9, categoryPercentage:0.85, order:2 },
877
+ { label:'Pluie prévue', data: precip, xAxisID:'x', yAxisID:'y', backgroundColor:P.bar, barPercentage:0.42, categoryPercentage:0.85, order:1, borderRadius:3 }
878
+ ]},
879
+ options:{responsive:true, maintainAspectRatio:false,
880
+ plugins:{ legend:{display:false},
881
+ tooltip:{ callbacks:{ label:(item)=> item.dataset.label==='Pluie prévue'
882
+ ? `Pluie: ${item.parsed.y.toFixed(1)} mm (${fmtValue('prob',prob[item.dataIndex])}% de proba)`
883
+ : `Ensoleillement: ${item.parsed.y.toFixed(1)} h` } },
884
+ whiskerDiamond: modelMin ? {mins:modelMin, maxs:modelMax, means:modelMean, color:P.whisker, diamondColor:P.diamond} : null,
885
+ barLabel: {items}
886
+ },
887
+ scales:{
888
+ x:{ type:'category', labels, offset:true, ticks:{color:C.text}, grid:{color:C.grid} },
889
+ x2:{ type:'category', labels, offset:true, display:false },
890
+ y:{ position:'left', min:0, suggestedMax:yMax, ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text} },
891
+ y1:{ position:'right', min:0, max:14, display:false }
892
+ } }
893
+ });
894
+ let bestIdx=-1, bestScore=-1;
895
+ precip.forEach((v,i)=>{ const score=v*(prob[i]||0); if(score>bestScore){ bestScore=score; bestIdx=i; } });
896
+ const takeawayEl = document.getElementById('stats-detail');
897
+ if(bestIdx>=0 && precip[bestIdx]>=1){
898
+ 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>`;
899
+ } else {
900
+ 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>`;
901
+ }
902
+ }catch(err){
903
+ body.innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="loadDetailChart('${region}')">↻ Réessayer</button></div>`;
904
+ document.getElementById('stats-detail').innerHTML = '';
905
+ }
906
+ }
907
+
908
+ /* ---- monthly climate: rainfall history heatmap + normals ---- */
909
+ 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)]; }
910
+ function contrastForRgb(rgb){ const lum=(0.299*rgb[0]+0.587*rgb[1]+0.114*rgb[2])/255; return lum>0.6?'#111318':'#ffffff'; }
911
+ function heatColor(ratio, theme){
912
+ ratio = Math.max(0, Math.min(1, ratio));
913
+ const stops = theme==='dark'
914
+ ? [[0,[26,33,56]],[0.5,[59,110,165]],[1,[224,182,78]]]
915
+ : [[0,[245,247,251]],[0.5,[91,155,213]],[1,[28,58,94]]];
916
+ 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); } }
917
+ return stops[stops.length-1][1];
918
+ }
919
+ function organizeMonthlyStats(daily){
920
+ const byYear = {};
921
+ daily.time.forEach((t,i)=>{
922
+ const d = new Date(t+'T00:00:00');
923
+ const year = d.getFullYear(), month = d.getMonth();
924
+ if(!byYear[year]) byYear[year] = { totals:new Array(12).fill(0), rainyDays:new Array(12).fill(0) };
925
+ const p = daily.precipitation_sum[i]||0;
926
+ byYear[year].totals[month] += p;
927
+ if(p>=1) byYear[year].rainyDays[month] += 1;
928
+ });
929
+ return byYear;
930
+ }
931
+ function buildHeatmapTable(byYear){
932
+ const months = MONTHS[currentLang];
933
+ const years = Object.keys(byYear).map(Number).sort((a,b)=>a-b);
934
+ let maxVal = 0, maxYear=null, maxMonth=null;
935
+ years.forEach(y=> byYear[y].totals.forEach((v,m)=>{ if(v>maxVal){ maxVal=v; maxYear=y; maxMonth=m; } }));
936
+ let html = '<div class="heatmap-scroll"><table class="heatmap-table"><thead><tr><th></th>';
937
+ years.forEach(y=> html += `<th>${y}</th>`);
938
+ html += '</tr></thead><tbody>';
939
+ for(let m=0;m<12;m++){
940
+ html += `<tr><th>${months[m]}</th>`;
941
+ years.forEach(y=>{
942
+ const v = byYear[y].totals[m];
943
+ const rgb = heatColor(maxVal ? v/maxVal : 0, currentTheme);
944
+ const bg = `rgb(${rgb.join(',')})`, fg = contrastForRgb(rgb);
945
+ 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>`;
946
+ });
947
+ html += '</tr>';
948
+ }
949
+ html += '</tbody></table></div>';
950
+ const legendEl = document.getElementById('monthly-heatmap-legend');
951
+ if(legendEl) legendEl.innerHTML = `<span>Faible</span><span class="heatmap-gradient"></span><span>Élevé — max : ${Math.round(maxVal)} mm (${months[maxMonth]} ${maxYear})</span>`;
952
+ return html;
953
+ }
954
+ let monthlyNormalsChart = null;
955
+ function buildMonthlyNormalsChart(byYear){
956
+ const t = I18N[currentLang], C = chartColors();
957
+ const years = Object.keys(byYear).map(Number);
958
+ const avgTotals = new Array(12).fill(0), avgRainyDays = new Array(12).fill(0);
959
+ for(let m=0;m<12;m++){
960
+ let sumT=0,sumR=0;
961
+ years.forEach(y=>{ sumT += byYear[y].totals[m]; sumR += byYear[y].rainyDays[m]; });
962
+ avgTotals[m] = years.length ? sumT/years.length : 0;
963
+ avgRainyDays[m] = years.length ? sumR/years.length : 0;
964
+ }
965
+ document.getElementById('monthly-normals-body').innerHTML = '<canvas id="chart-monthly-normals"></canvas>';
966
+ const ctx = document.getElementById('chart-monthly-normals').getContext('2d');
967
+ if(monthlyNormalsChart) monthlyNormalsChart.destroy();
968
+ monthlyNormalsChart = new Chart(ctx,{
969
+ data:{ labels: MONTHS[currentLang], datasets:[
970
+ { type:'bar', label:t.legendMonthlyPrecip, data:avgTotals, backgroundColor:C.blue, yAxisID:'y', borderRadius:4 },
971
+ { type:'line', label:t.legendRainyDays, data:avgRainyDays, borderColor:'#c98a12', backgroundColor:'#c98a12', yAxisID:'y1', pointRadius:3, pointHoverRadius:5, tension:.3 }
972
+ ]},
973
+ options:{responsive:true, maintainAspectRatio:false,
974
+ interaction:{mode:'index', intersect:false},
975
+ 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)}` } }},
976
+ scales:{ x:{ticks:{color:C.text}, grid:{display:false}},
977
+ y:{position:'left', ticks:{color:C.text}, grid:{color:C.grid}, title:{display:true,text:'mm',color:C.text}},
978
+ y1:{position:'right', ticks:{color:C.text}, grid:{display:false}, title:{display:true,text:t.legendRainyDays,color:C.text}} } }
979
+ });
980
+ }
981
+ let monthlyLoadedRegion = null;
982
+ async function loadMonthlyClimate(region){
983
+ const t = I18N[currentLang];
984
+ monthlyLoadedRegion = region;
985
+ document.getElementById('monthly-heatmap-body').innerHTML = `<div class="loading">${t.loadingClimate}</div>`;
986
+ document.getElementById('monthly-normals-body').innerHTML = '<div class="loading">—</div>';
987
+ try{
988
+ const daily = await fetchArchive(region);
989
+ const byYear = organizeMonthlyStats(daily);
990
+ document.getElementById('monthly-heatmap-body').innerHTML = buildHeatmapTable(byYear);
991
+ buildMonthlyNormalsChart(byYear);
992
+ document.getElementById('meta-monthly-norm').textContent = t.metaRef(region, Object.keys(byYear).length);
993
+ }catch(err){
994
+ document.getElementById('monthly-heatmap-body').innerHTML = `<div class="error">${explainFetchError(err)}<br><button class="retry-btn" onclick="loadMonthlyClimate('${region}')">↻ Réessayer</button></div>`;
995
+ document.getElementById('monthly-normals-body').innerHTML = '';
996
+ }
997
+ }
998
+
999
+ /* ---- unified load: one region drives all 5 figures ---- */
1000
+ function loadAll(region){
1001
+ generate();
1002
+ loadDetailChart(region);
1003
+ loadMonthlyClimate(region);
1004
+ }
1005
+ document.getElementById('btn-submit').addEventListener('click', ()=> loadAll(document.getElementById('sel-region').value));
1006
+
1007
+ /* ============================= BOOT ============================= */
1008
+ function loadScript(src){
1009
+ return new Promise((resolve,reject)=>{
1010
+ const s = document.createElement('script');
1011
+ s.src = src; s.onload = ()=>resolve(true); s.onerror = ()=>reject(new Error(src));
1012
+ document.head.appendChild(s);
1013
+ });
1014
+ }
1015
+ async function ensureChartJs(){
1016
+ if(window.Chart) return true;
1017
+ 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'];
1018
+ for(const src of sources){ try{ await loadScript(src); if(window.Chart) return true; }catch(e){} }
1019
+ return false;
1020
+ }
1021
+
1022
+ initSelects();
1023
+ applyI18n();
1024
+
1025
+ (async function boot(){
1026
+ const ok = await ensureChartJs();
1027
+ if(!ok){
1028
+ const t = I18N[currentLang];
1029
+ document.getElementById('cum-body').innerHTML = `<div class="error">${t.chartErr('cdnjs / jsdelivr')}</div>`;
1030
+ return;
1031
+ }
1032
+ Chart.register(todayLinePlugin, pointLabelPlugin, whiskerDiamondPlugin, barLabelPlugin);
1033
+ loadAll(document.getElementById('sel-region').value);
1034
+ })();
1035
+ </script>
1036
+ </body>
1037
  </html>