File size: 26,039 Bytes
30257a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Gola Reference Labelling</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap">
<style>
html{color-scheme:light}body{margin:0}img{max-width:100%}[hidden]{display:none!important}
/* Layout: sticky progress bar; image sheet on the left, label form on the right; one column on phones */
:root{
  --bg:#f3f5f2; --panel:#ffffff; --ink:#15231c; --ink-2:#4a5a52; --ink-3:#7b8a82; --rule:#d5ddd8; --band:#e6ece8;
  --forest:#1f6b45; --forest-soft:#d9ecdf; --loss:#b5481e; --loss-soft:#f4ddd0; --unsure:#8a6d1c; --unsure-soft:#f3e9cc; --focus:#2c62a8;
  --f-body:"IBM Plex Sans","Segoe UI",system-ui,sans-serif; --f-data:"IBM Plex Mono",ui-monospace,Menlo,monospace;
}
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
  --bg:#0f1613; --panel:#16201b; --ink:#e6eee9; --ink-2:#a9b8b0; --ink-3:#7d8c84; --rule:#2a3630; --band:#1e2a24;
  --forest:#5cc28a; --forest-soft:#183024; --loss:#e8835a; --loss-soft:#3a2219; --unsure:#e0bd5c; --unsure-soft:#332a14; --focus:#7aa8e0; color-scheme:dark}}
:root[data-theme="dark"]{
  --bg:#0f1613; --panel:#16201b; --ink:#e6eee9; --ink-2:#a9b8b0; --ink-3:#7d8c84; --rule:#2a3630; --band:#1e2a24;
  --forest:#5cc28a; --forest-soft:#183024; --loss:#e8835a; --loss-soft:#3a2219; --unsure:#e0bd5c; --unsure-soft:#332a14; --focus:#7aa8e0; color-scheme:dark}
*{box-sizing:border-box}
body{background:var(--bg);color:var(--ink);font:400 15px/1.5 var(--f-body);padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:0 32px}
body::before{content:"";position:fixed;inset:0 0 auto;height:env(safe-area-inset-top,0px);z-index:10;background:var(--bg)}
button,select,input,textarea{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
.top{position:sticky;top:env(safe-area-inset-top,0px);z-index:5;background:var(--bg);border-bottom:1px solid var(--rule);padding-block:12px;display:grid;gap:8px}
.top .row{display:flex;flex-wrap:wrap;gap:10px 18px;align-items:center;justify-content:space-between}
h1{font-size:17px;font-weight:600;margin:0;letter-spacing:.01em}
h1 span{color:var(--ink-3);font-weight:400}
.count{font:500 13px var(--f-data);font-variant-numeric:tabular-nums;color:var(--ink-2)}
.bar{height:6px;background:var(--band);border-radius:3px;overflow:hidden}
.bar i{display:block;height:100%;background:var(--forest);width:0;transition:width .3s}
.nav{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.btn{border:1px solid var(--rule);background:var(--panel);padding:7px 12px;border-radius:4px;cursor:pointer;font-size:14px}
.btn:hover{border-color:var(--ink-3)}
.btn.primary{background:var(--forest);border-color:var(--forest);color:var(--bg);font-weight:600}
.btn[disabled]{opacity:.45;cursor:not-allowed}
select.btn{padding-right:28px}
main{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:24px;margin-top:18px;align-items:start}
@media (max-width:960px){main{grid-template-columns:minmax(0,1fr)}}
.sheet{background:var(--panel);border:1px solid var(--rule);padding:12px;display:grid;gap:10px;min-width:0}
.sheet .head{display:flex;flex-wrap:wrap;gap:6px 16px;align-items:baseline;justify-content:space-between}
.pid{font:600 22px var(--f-data)}
.coords{font:400 13px var(--f-data);color:var(--ink-2)}
.imgwrap{position:relative;background:var(--band);aspect-ratio:968/644;max-width:100%}
.imgwrap img{display:block;width:100%;height:auto}
.imgwrap .miss{position:absolute;inset:0;display:grid;place-items:center;color:var(--ink-3);font-size:14px}
.imgwrap .miss[hidden]{display:none}
.imgwrap a{display:block}
.dates{display:grid;grid-template-columns:auto 1fr;gap:2px 12px;font-size:13px;color:var(--ink-2)}
.dates b{font-weight:500;color:var(--ink)}
.flag{color:var(--unsure)}
.links{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:13px}
.links a{color:var(--focus)}
form{background:var(--panel);border:1px solid var(--rule);padding:16px;display:grid;gap:16px;min-width:0}
fieldset{border:0;margin:0;padding:0;display:grid;gap:6px}
legend{font-weight:600;font-size:14px;padding:0;margin-bottom:6px}
legend kbd{font:400 11px var(--f-data);color:var(--ink-3);border:1px solid var(--rule);border-radius:3px;padding:0 4px;margin-left:6px}
.seg{display:flex;flex-wrap:wrap;gap:6px}
.seg label{position:relative}
.seg input{position:absolute;opacity:0;inset:0;margin:0;cursor:pointer}
.seg span{display:inline-block;border:1px solid var(--rule);border-radius:4px;padding:6px 12px;font-size:14px;background:var(--panel);cursor:pointer;user-select:none}
.seg input:focus-visible+span{outline:2px solid var(--focus);outline-offset:2px}
.seg input:checked+span{border-color:var(--ink);background:var(--band);font-weight:600}
.seg input[value="yes"]:checked+span{background:var(--forest-soft);border-color:var(--forest);color:var(--forest)}
.seg input[value="no"]:checked+span{background:var(--loss-soft);border-color:var(--loss);color:var(--loss)}
.seg input[value="unsure"]:checked+span{background:var(--unsure-soft);border-color:var(--unsure);color:var(--unsure)}
.two{display:grid;grid-template-columns:1fr 1fr;gap:10px}
@media (max-width:420px){.two{grid-template-columns:1fr}}
.field{display:grid;gap:4px;font-size:13px;color:var(--ink-2);min-width:0}
.field input,.field select,.field textarea{border:1px solid var(--rule);border-radius:4px;background:var(--bg);padding:6px 8px;color:var(--ink);width:100%}
textarea{resize:vertical;min-height:52px}
.actions{display:flex;flex-wrap:wrap;gap:10px;align-items:center}
.status{font-size:13px;color:var(--ink-2);min-height:1.5em}
.status.err{color:var(--loss)}
.saved{font:500 12px var(--f-data);color:var(--forest)}
.signin{background:var(--panel);border:1px solid var(--rule);padding:20px;max-width:420px;margin:24px auto 0;display:grid;gap:12px}
.signin h2{margin:0;font-size:18px}
.signin p{margin:0;color:var(--ink-2);font-size:14px}
.who{font:500 13px var(--f-data);color:var(--ink-2)}
details.guide{background:var(--panel);border:1px solid var(--rule);padding:12px 18px;margin-top:16px}
details.guide summary{cursor:pointer;font-weight:600;font-size:16px}
.gbody{max-width:82ch;color:var(--ink);display:grid;gap:4px}
.gbody h3{font-size:15px;margin:14px 0 2px}
.gbody p{margin:4px 0;color:var(--ink-2)}
.gbody ul{margin:4px 0;padding-left:20px;display:grid;gap:4px;color:var(--ink-2)}
.gt{border-collapse:collapse;font-size:14px;margin:6px 0;width:100%}
.gt th,.gt td{border:1px solid var(--rule);padding:6px 8px;text-align:left;vertical-align:top;color:var(--ink-2)}
.gt th{background:var(--band);color:var(--ink);font-weight:600}
.gbody .wrap{overflow-x:auto}
.notice{background:var(--unsure-soft);color:var(--ink);border:1px solid var(--unsure);padding:10px 14px;border-radius:4px;font-size:14px;margin-top:14px}
@media (prefers-reduced-motion:reduce){.bar i{transition:none}}
</style>
</head>
<body>

<header class="top">
  <div class="row">
    <h1>Gola reference labelling <span>2017 vs 2023</span></h1>
    <span class="count" id="count">Loading points</span>
  </div>
  <div class="bar" aria-hidden="true"><i id="bar"></i></div>
  <div class="row">
    <div class="nav">
      <button type="button" class="btn" id="prev" aria-label="Previous point">&larr; Prev</button>
      <button type="button" class="btn" id="next" aria-label="Next point">Next &rarr;</button>
      <button type="button" class="btn" id="todo">Next unlabelled</button>
      <button type="button" class="btn" id="howto">How to label</button>
      <select class="btn" id="jump" aria-label="Go to point"></select>
    </div>
    <div class="nav">
      <span class="who" id="whotag"></span><button type="button" class="btn" id="switch">Change name</button><button type="button" class="btn" id="export">Download my labels (CSV)</button>
    </div>
  </div>
</header>
<div class="notice" id="notice" hidden></div>
<details class="guide" id="guide">
<summary>How to label (read this first)</summary>
<div class="gbody">
<h3>What this is for</h3>
<p>We are checking how accurate satellite maps of forest loss are in the Gola forest area (Sierra Leone and Liberia). Your job is to look at each point on detailed images and record what was really on the ground in 2017 and in 2023. Your answers are the "truth" the maps are compared against, so careful, honest answers matter more than speed. There are 250 points. Each takes about 2 to 4 minutes, and you can stop and come back any time.</p>

<h3>What you see for each point</h3>
<ul>
  <li><b>Top row = about 2017, bottom row = about 2023.</b> The exact date of each image is printed on it and under the images.</li>
  <li><b>Left:</b> a close-up. The <b>yellow square</b> is the area you are judging (30 x 30 m, about the size of a small house plot).</li>
  <li><b>Middle:</b> a wider view of the same place, to see the surroundings.</li>
  <li><b>Right:</b> a satellite view that is less detailed and sometimes hazy. Use it only as a rough check.</li>
  <li>Click the images to open them full size.</li>
</ul>

<h3>Step 1. Was the square forest in 2017? In 2023?</h3>
<p>Answer <b>Yes</b> if tall trees cover <b>at least about a third</b> of the yellow square. Tall means real trees (taller than about 5 m), with large rounded crowns that cast shadows.</p>
<p>Answer <b>No</b> if the square is mostly bare soil, crops, grass, low bush, roads, houses or water.</p>
<p>Answer <b>Unsure</b> if clouds, haze or a missing image mean you really cannot tell. Unsure is a valid answer. Please do not guess.</p>
<div class="wrap"><table class="gt">
<tr><th>Looks like</th><th>Forest?</th></tr>
<tr><td>Dense, bumpy dark-green canopy with many round crowns</td><td>Yes</td></tr>
<tr><td>Trees in neat rows, star-shaped crowns all the same size (oil palm), or regular rows of cocoa or rubber</td><td>Yes, but choose "Plantation or agroforest" in Step 2</td></tr>
<tr><td>A few scattered trees on mostly open ground</td><td>No</td></tr>
<tr><td>Smooth light green (grass, crops, young bush), brown or orange soil</td><td>No</td></tr>
</table></div>

<h3>Step 2. What happened?</h3>
<p>This fills itself in from your two answers. Only change it in the cases marked below.</p>
<div class="wrap"><table class="gt">
<tr><th>2017</th><th>2023</th><th>What happened</th></tr>
<tr><td>Forest</td><td>Forest</td><td>No change (filled in for you). Change it to <b>Degradation</b> if the canopy is clearly thinner, with new gaps or logging tracks, but still forest</td></tr>
<tr><td>Forest</td><td>Not forest</td><td>Clearing (filled in for you)</td></tr>
<tr><td>Not forest</td><td>Forest</td><td>Regrowth (filled in for you)</td></tr>
<tr><td>Not forest</td><td>Not forest</td><td>No change (filled in for you)</td></tr>
<tr><td colspan="2">Plantation in either year</td><td>Change it to <b>Plantation or agroforest</b></td></tr>
<tr><td colspan="2">Anything else (burn scar, mine, flooding)</td><td>Choose <b>Other</b> and write a short note</td></tr>
</table></div>

<h3>Step 3. How sure are you?</h3>
<ul>
  <li><b>High:</b> clear images close to both years, and the answer is obvious.</li>
  <li><b>Medium:</b> one image is more than a year away from 2017 or 2023 (shown in orange), or the square is a mix of trees and open ground.</li>
  <li><b>Low:</b> hazy or cloudy images, or you had to judge mostly from the wider view.</li>
</ul>

<h3>Step 4. If an image is missing or too far from the year</h3>
<p>Some points have no detailed image for one of the years (the panel is grey). Use the links under the images:</p>
<ul>
  <li><b>Google Earth:</b> click the clock icon (historical imagery) and move the slider to an image from 2016 to 2018, or from 2022 to 2024.</li>
  <li><b>Google Maps satellite</b> or <b>Copernicus Browser</b> as a back-up.</li>
</ul>
<p>Then set "Imagery used" to what you used, so we know where each answer came from. If nothing helps, answer Unsure for that year.</p>

<h3>Step 5. Save</h3>
<p>Press <b>Save and next</b> (or the Enter key). Your answer is stored straight away and the next unlabelled point opens. You can go back to any point with Prev, Next or the list, change it and save again.</p>

<h3>Tips</h3>
<ul>
  <li>Judge only what is <b>inside</b> the yellow square. Forest just outside it does not count.</li>
  <li>Images from different dates can be shifted by a few metres. Compare the same landmarks (roads, clearings, rivers).</li>
  <li>Shadows and dark crowns mean tall trees. Smooth, even texture usually means low vegetation.</li>
  <li>Keyboard shortcuts: 1, 2, 3 for 2017 (Yes, No, Unsure); Q, W, E for 2023; H, M, L for confidence; Enter to save; arrow keys to move without saving.</li>
  <li>Do not look up what the maps say about a point. Your answers must come from the images only.</li>
</ul>
</div>
</details>
<form class="signin" id="signin" hidden>
  <h2>Start labelling</h2>
  <p>Enter your name so your labels are kept together. You can stop at any time and continue later with the same name.</p>
  <label class="field">Your name<input type="text" id="who" required maxlength="40" autocomplete="name"></label>
  <label class="field" id="codewrap">Access code<input type="text" id="code" maxlength="40" autocomplete="off"></label>
  <button type="submit" class="btn primary">Start</button>
  <div class="status" id="signstatus" role="status"></div>
</form>

<main id="work" hidden>
  <section class="sheet" aria-label="Imagery">
    <div class="head"><span class="pid" id="pid">-</span><span class="coords" id="coords"></span></div>
    <div class="imgwrap"><a id="chiplink" target="_blank" rel="noopener" title="Open full size"><img id="chip" alt="High-resolution and Sentinel-2 imagery for 2017 and 2023 around the point"></a><div class="miss" id="miss" hidden>Image not available for this point</div></div>
    <div class="dates" id="dates"></div>
    <div class="links" id="links"></div>
  </section>

  <form id="form" autocomplete="off">
    <fieldset id="fs17"><legend>Forest in 2017 <kbd>1 2 3</kbd></legend>
      <div class="seg">
        <label><input type="radio" name="forest_2017" value="yes" id="f17y"><span>Yes</span></label>
        <label><input type="radio" name="forest_2017" value="no" id="f17n"><span>No</span></label>
        <label><input type="radio" name="forest_2017" value="unsure" id="f17u"><span>Unsure</span></label>
      </div></fieldset>
    <fieldset id="fs23"><legend>Forest in 2023 <kbd>Q W E</kbd></legend>
      <div class="seg">
        <label><input type="radio" name="forest_2023" value="yes" id="f23y"><span>Yes</span></label>
        <label><input type="radio" name="forest_2023" value="no" id="f23n"><span>No</span></label>
        <label><input type="radio" name="forest_2023" value="unsure" id="f23u"><span>Unsure</span></label>
      </div></fieldset>
    <fieldset><legend>What happened</legend>
      <div class="seg">
        <label><input type="radio" name="change_type" value="none" id="ctn"><span>No change</span></label>
        <label><input type="radio" name="change_type" value="clearing" id="ctc"><span>Clearing</span></label>
        <label><input type="radio" name="change_type" value="degradation" id="ctd"><span>Degradation</span></label>
        <label><input type="radio" name="change_type" value="regrowth" id="ctr"><span>Regrowth</span></label>
        <label><input type="radio" name="change_type" value="plantation" id="ctp"><span>Plantation or agroforest</span></label>
        <label><input type="radio" name="change_type" value="other" id="cto"><span>Other</span></label>
      </div></fieldset>
    <fieldset><legend>Confidence <kbd>H M L</kbd></legend>
      <div class="seg">
        <label><input type="radio" name="confidence" value="high" id="cfh"><span>High</span></label>
        <label><input type="radio" name="confidence" value="medium" id="cfm"><span>Medium</span></label>
        <label><input type="radio" name="confidence" value="low" id="cfl"><span>Low</span></label>
      </div></fieldset>
    <div class="two">
      <label class="field">Imagery used for 2017
        <select id="src17" name="source_2017"><option value="esri">Esri imagery on this page</option><option value="nicfi">Planet NICFI</option><option value="google_earth">Google Earth history</option><option value="sentinel2">Sentinel-2</option></select></label>
      <label class="field">Imagery used for 2023
        <select id="src23" name="source_2023"><option value="esri">Esri imagery on this page</option><option value="nicfi">Planet NICFI</option><option value="google_earth">Google Earth history</option><option value="sentinel2">Sentinel-2</option></select></label>
    </div>
    <label class="field">Note (optional)<textarea id="note" name="note" maxlength="500"></textarea></label>
    <div class="actions">
      <button type="submit" class="btn primary" id="save">Save and next <span style="font-weight:400;opacity:.8">(Enter)</span></button>
      <span class="saved" id="savedtag"></span>
    </div>
    <div class="status" id="status" role="status"></div>
  </form>
</main>


<script>
(() => {
  const $ = id => document.getElementById(id);
  let P = [], L = {}, i = 0, saving = false, who = "", code = "";
  const ls = { get(k){ try { return localStorage.getItem(k); } catch(e) { return null; } }, set(k,v){ try { localStorage.setItem(k,v); } catch(e) {} } };

  /* ---------- data ---------- */
  async function loadPoints(){
    const r = await fetch("points.json");
    P = await r.json();
    $("jump").innerHTML = P.map((p,k)=>`<option value="${k}">${p.id}</option>`).join("");
    let start = 0;
    try { const s = localStorage.getItem("gola-label-pos"); if (s !== null && +s < P.length) start = +s; } catch(e) {}
    i = start;
  }

  async function api(path, opts){
    const r = await fetch(path, opts);
    if (!r.ok) { let m = "Request failed"; try { m = (await r.json()).detail || m; } catch(e) {} throw new Error(m); }
    return r.json();
  }

  async function signIn(name, c){
    L = await api(`api/labels?labeller=${encodeURIComponent(name)}&code=${encodeURIComponent(c)}`);
    who = name; code = c; ls.set("gola-who", name); ls.set("gola-code", c);
    $("whotag").textContent = `Labelling as ${name}`;
    $("signin").hidden = true; $("work").hidden = false;
    progress(); show(i); goFirstUnlabelled();
  }

  function goFirstUnlabelled(){ const j = P.findIndex(p => !L[p.id]); if (j >= 0) show(j); }

  $("signin").addEventListener("submit", async e => {
    e.preventDefault();
    const name = $("who").value.trim(), c = $("code").value.trim();
    if (!name) return;
    $("signstatus").textContent = "Loading...";
    try { await signIn(name, c); $("signstatus").textContent = ""; }
    catch (err) { $("signstatus").textContent = err.message; }
  });
  $("switch").onclick = () => { $("work").hidden = true; $("signin").hidden = false; $("who").value = who; };

  

  /* ---------- view ---------- */
  function show(k){
    i = Math.max(0, Math.min(P.length - 1, k));
    const p = P[i];
    ls.set("gola-label-pos", i);
    $("jump").value = i; $("pid").textContent = p.id;
    $("coords").textContent = `${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}`;
    const img = $("chip"); $("miss").hidden = true;
    img.onerror = () => { $("miss").hidden = false; }; img.src = `chips/${p.id}.jpg`; $("chiplink").href = img.src;
    const far = (d, y) => d && Math.abs(new Date(d) - new Date(`${y}-07-01`)) > 400 * 864e5;
    const row = (y, d, s, r) => d ? `<span>${y} high-res</span><b class="${far(d, y) ? "flag" : ""}">${d} &middot; ${s} &middot; ${r} m${far(d, y) ? " (more than a year from " + y + ")" : ""}</b>`
                                   : `<span>${y} high-res</span><b class="flag">none in Esri archive, use NICFI or Google Earth</b>`;
    $("dates").innerHTML = row(2017, p.d17, p.s17, p.r17) + row(2023, p.d23, p.s23, p.r23) + `<span>Sentinel-2</span><b>EOX cloudless 2018 and 2023 (context)</b>`;
    const ge = `https://earth.google.com/web/@${p.lat},${p.lon},150a,400d,35y,0h,0t,0r`;
    const gm = `https://www.google.com/maps/@${p.lat},${p.lon},250m/data=!3m1!1e3`;
    const cb = `https://browser.dataspace.copernicus.eu/?zoom=16&lat=${p.lat}&lng=${p.lon}`;
    $("links").innerHTML = `<a href="${ge}" target="_blank" rel="noopener">Google Earth</a><a href="${gm}" target="_blank" rel="noopener">Google Maps satellite</a><a href="${cb}" target="_blank" rel="noopener">Copernicus Browser</a><a href="https://www.planet.com/nicfi/" target="_blank" rel="noopener">Planet NICFI</a>`;
    fillForm(); markSaved(); status("");
  }

  function fillForm(){
    const p = P[i]; if (!p) return;
    const v = L[p.id] || {};
    for (const name of ["forest_2017","forest_2023","change_type","confidence"])
      document.querySelectorAll(`input[name="${name}"]`).forEach(el => { el.checked = el.value === v[name]; });
    $("src17").value = v.source_2017 || "esri"; $("src23").value = v.source_2023 || "esri"; $("note").value = v.note || "";
  }

  function markSaved(){ const p = P[i]; $("savedtag").textContent = p && L[p.id] ? "Saved" : ""; }

  function progress(){
    const n = Object.keys(L).filter(k => P.some(p => p.id === k)).length;
    $("count").textContent = `${n} of ${P.length} labelled`;
    $("bar").style.width = (P.length ? 100 * n / P.length : 0) + "%";
    [...$("jump").options].forEach((o,k) => { o.textContent = P[k].id + (L[P[k].id] ? "  ✓" : ""); });
  }

  function status(msg, err){ const s = $("status"); s.textContent = msg; s.className = "status" + (err ? " err" : ""); }

  /* ---------- save ---------- */
  function readForm(){
    const val = n => (document.querySelector(`input[name="${n}"]:checked`) || {}).value;
    return { forest_2017: val("forest_2017"), forest_2023: val("forest_2023"), change_type: val("change_type"),
             confidence: val("confidence"), source_2017: $("src17").value, source_2023: $("src23").value, note: $("note").value.trim() };
  }

  async function save(e){
    e.preventDefault();
    if (!who || saving) return;
    const f = readForm(), missing = ["forest_2017","forest_2023","change_type","confidence"].filter(k => !f[k]);
    if (missing.length) return status("Choose " + missing.map(k => k.replace("_"," ").replace("change type","what happened")).join(", ") + " before saving.", true);
    const p = P[i]; saving = true; $("save").disabled = true;
    try {
      L[p.id] = await api("api/labels", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...f, point_id: p.id, labeller: who, code }) });
      progress();
      status(`${p.id} saved.`); goNextUnlabelled(i);
    } catch (err) {
      status(`Not saved: ${err.message}. Try again.`, true);
    } finally { saving = false; $("save").disabled = false; }
  }

  function goNextUnlabelled(from){
    for (let k = 1; k <= P.length; k++) { const j = (from + k) % P.length; if (!L[P[j].id] && j !== from) return show(j); }
    show(Math.min(from + 1, P.length - 1));
  }

  function exportCsv(){
    const cols = ["point_id","forest_2017","forest_2023","change_type","confidence","source_2017","source_2023","note","labelled_at"];
    const esc = v => { v = v == null ? "" : String(v); return /[",\n]/.test(v) ? `"${v.replace(/"/g,'""')}"` : v; };
    const rows = P.filter(p => L[p.id]).map(p => cols.map(c => esc(L[p.id][c])).join(","));
    const url = URL.createObjectURL(new Blob([[cols.join(","), ...rows].join("\n")], { type: "text/csv" }));
    const a = document.createElement("a"); a.href = url; a.download = "gola_labels.csv"; a.click(); URL.revokeObjectURL(url);
  }
  $("export").onclick = exportCsv;

  // open the guide on a first visit
  try { if (!localStorage.getItem("gola-guide-seen")) { $("guide").open = true; localStorage.setItem("gola-guide-seen", "1"); } } catch(e) {}
  $("howto").onclick = () => { const g = $("guide"); g.open = true; g.scrollIntoView({behavior: "smooth", block: "start"}); };
  /* ---------- events ---------- */
  $("form").addEventListener("submit", save);
  // fill "What happened" from the two forest answers; degradation, plantation and other are left as chosen
  function autoChange(){
    const val = n => (document.querySelector(`input[name="${n}"]:checked`) || {}).value;
    const a = val("forest_2017"), b = val("forest_2023"), cur = val("change_type");
    if (["degradation","plantation","other"].includes(cur)) return;
    const pick = a === "yes" && b === "no" ? "ctc" : a === "no" && b === "yes" ? "ctr" : a && b && a === b && a !== "unsure" ? "ctn" : null;
    if (pick) $(pick).checked = true;
  }
  document.querySelectorAll('input[name="forest_2017"],input[name="forest_2023"]').forEach(el => el.addEventListener("change", autoChange));
  $("prev").onclick = () => show(i - 1);
  $("next").onclick = () => show(i + 1);
  $("todo").onclick = () => goNextUnlabelled(i);
  $("jump").onchange = e => show(+e.target.value);
  const keys = { "1":"f17y","2":"f17n","3":"f17u","q":"f23y","w":"f23n","e":"f23u","h":"cfh","m":"cfm","l":"cfl" };
  document.addEventListener("keydown", e => {
    if ($("work").hidden || e.target.matches("textarea, select, input[type=text]") || e.metaKey || e.ctrlKey || e.altKey) return;
    const k = e.key.toLowerCase();
    if (keys[k]) { $(keys[k]).checked = true; autoChange(); e.preventDefault(); }
    else if (e.key === "ArrowRight") show(i + 1);
    else if (e.key === "ArrowLeft") show(i - 1);
    else if (e.key === "Enter" && !e.target.matches("button")) { e.preventDefault(); $("form").requestSubmit(); }
  });

  loadPoints().then(async () => {
    const n = ls.get("gola-who"), c = ls.get("gola-code") || "";
    if (n) { try { return await signIn(n, c); } catch(e) {} }
    $("signin").hidden = false; if (n) $("who").value = n;
  }).catch(() => status("Could not load the points list.", true));
})();
</script>

</body>
</html>