-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwizard.js
More file actions
3125 lines (2826 loc) · 147 KB
/
wizard.js
File metadata and controls
3125 lines (2826 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================
// LAHMP Wizard — wizard.js
// All algorithm logic and UI rendering.
// index.html is presentation only; all content comes from data/.
// ============================================================
'use strict';
// ── Constants ─────────────────────────────────────────────────────────────
const SITE_COUNT_MIDPOINT = { '1': 1, '2-5': 3, '6-20': 13, '21-100': 60, '100+': 100 };
const TEAM_PROTOCOL_LEVEL = { A: 1, B: 1, C: 2, D: 2, E: 3, F: 3 };
const TEAM_LABELS = {
A: 'Land managers / farmers',
B: 'Extension officers',
C: 'Field technicians / agronomists',
D: 'Biologists / ecologists',
E: 'Research scientists',
F: 'External contracted specialists',
};
const EQUIPMENT_CATEGORIES = [
'Basic field kit (tape measure, compass, stakes, clipboard)',
'Soil sampling tools (auger, bulk density cores, trowel)',
'Water quality meters (pH, EC, dissolved oxygen)',
'Camera / photo-documentation (DSLR, smartphone with macro)',
'GPS / GIS device or smartphone with mapping app',
'Insect sampling equipment (sweep nets, pitfall traps, Malaise trap)',
'Bioacoustic recorder (bat detector, bird / frog recorder)',
'eDNA sampling kit (filters, sterile containers, field kit)',
'Soil laboratory access (pH, texture, bulk density, SOC)',
'Molecular laboratory access (PCR, sequencing, PLFA/NLFA)',
'Microscopy (light microscope or compound microscope)',
'Spectrophotometer or colorimeter (nutrient analysis)',
'Access to external analytical laboratory (contract services)',
];
const PRESCREEN_LABELS = {
q1_trees: 'Are you open to integrating trees into your farming system? (agroforestry, hedgerows, shade trees)',
q2_livestock: 'Are you open to integrating or diversifying livestock? (mixed farming, rotational grazing)',
q3_set_aside: 'Are you open to setting aside land for habitat creation? (wildflower margins, buffer strips, ponds)',
q4_inputs: 'Are you open to reducing external inputs? (fertilisers, pesticides, herbicides)',
};
const PRESCREEN_ANSWERS = [
{ value: 'open', label: 'Yes — open to this now' },
{ value: 'open_conditionally', label: 'Yes — open in the longer term / conditionally' },
{ value: 'not_currently', label: 'Not currently possible' },
];
// Area weighting: keywords that must appear in a land_use_composition category name
// for that pressure to be relevant to that land parcel. null = landscape-wide (no weighting).
const PRESSURE_LAND_USE_KEYWORDS = {
1: ['cropland','agroforestry','plantation'], // Intensive tillage
2: ['cropland','agroforestry','plantation'], // Soil compaction
3: ['cropland','agroforestry'], // Excessive synthetic fertilizer
4: ['cropland','agroforestry'], // Excessive insecticides
5: ['cropland','agroforestry'], // Excessive herbicide
6: ['cropland','agroforestry'], // Excessive fungicide
7: ['cropland','agroforestry'], // Excessive nematicide
8: ['cropland','agroforestry'], // Excessive rodenticide
9: ['cropland','agroforestry'], // Excessive molluscicide
10: ['cropland','agroforestry'], // Soil fumigation
11: ['cropland','agroforestry'], // Excessive manure
12: ['irrigated','wetland','paddy','flooded'], // Excessive irrigation
13: ['cropland','agroforestry'], // Monoculture
14: ['cropland','agroforestry'], // Removal of crop residues
15: null, // Unsustainable water abstraction — landscape-wide
16: ['irrigated','wetland','paddy','flooded'], // Drainage/irrigation modification
17: null, // Water pollution — landscape-wide
18: ['grassland','pasture','rangeland','mixed crop-livestock'], // Overgrazing
19: ['grassland','shrubland','forest','natural','semi-natural'],// Removal of non-crop vegetation
20: ['forest','shrubland','plantation','woodland','grassland'], // Overextraction of wood
21: null, // Invasive species — landscape-wide
22: null, // Land-use change — landscape-wide
23: null, // Landscape fragmentation — landscape-wide
24: null, // Fire — landscape-wide
25: null, // Soil pollution — landscape-wide
26: null, // External pollution — landscape-wide
27: null, // Abandonment — landscape-wide
28: null, // Other — landscape-wide
};
const THEME_TO_CHAIN = {
'Soil Management': 'Soil recovery and biological function chain',
'Crop System Diversification': 'Crop system diversity and soil health chain',
'Integrated Pest and Disease Management': 'Natural regulation and IPM chain',
'Water Management': 'Water quality and hydrology chain',
'Livestock and Pasture Management': 'Grazing management and pasture recovery chain',
'Agroforestry and Tree Integration': 'Woody cover and landscape connectivity chain',
'Habitat and Landscape Management': 'Above-ground habitat recovery chain',
'Nutrient Cycling and Resource Efficiency':'Nutrient cycling and soil chemistry chain',
'Carbon and Land Restoration': 'Land restoration chain',
'Agrobiodiversity': 'Agrobiodiversity and genetic resource chain',
'System-Level': null,
};
const MONTHS = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
// ── Global data ────────────────────────────────────────────────────────────
let practicesData = [];
let indicatorsData = [];
let abioticData = [];
let referenceData = {};
let currentStep = 1;
window.demoMode = false; // true when a demo fixture is loaded via the demo button
// EFG map data (loaded once at init, stored globally)
window.lahmpData = { metadata: null, gridIndex: null };
let _efgMap = null; // Leaflet map instance for Block 1.2 EFG selector
let _efgMapRect = null; // Current 0.5° cell highlight rectangle
// ── Assessment state ────────────────────────────────────────────────────────
window.assessment = {
assessment_id: null,
landscape_name: '',
created_at: null,
last_updated: null,
step1: {
landscape_name: '',
country: '',
admin_region: '',
monitoring_programme_name: '',
area_ha: null,
ipcc_land_use_categories: [],
soil_types: [],
efg_codes: [],
map_click_lng: null, // longitude of last confirmed map click (context, not polygon)
map_click_lat: null, // latitude of last confirmed map click
description: '',
land_uses: [],
crops: [],
livestock: [],
land_use_composition: [],
pressures: [],
challenges: [],
services: [],
},
step2: {
prescreen: { q1_trees: null, q2_livestock: null, q3_set_aside: null, q4_inputs: null },
selected_practices: [],
practice_count: 0,
theme_counts: {},
standard_count: 0,
transformative_count: 0,
},
step3: {
team_types: [],
willingness_recruit: null,
willingness_recruit_roles: '',
days_by_type: {},
willingness_time: null,
equipment_capabilities: [],
willingness_equipment: null,
willingness_equipment_categories: [],
budget_tier: null,
site_count_category: null,
site_count: 1,
site_distribution: null,
access_calendar: MONTHS.map(m => ({ month: m, access: 'accessible', reason: '' })),
capacity_profile: null,
},
step4_outputs: {
practice_chains: [],
selected_indicator_groups: [],
selected_abiotic: [],
protocol_assignments: [],
trimmed_groups: [],
calendar: [],
narrative: { paragraph1: '', paragraph2: '', paragraph3: '', paragraph4: '' },
},
};
// ── Data loading ──────────────────────────────────────────────────────────
async function loadData() {
const [p, i, a, r, meta, grid] = await Promise.all([
fetch('data/practices.json').then(r => r.json()),
fetch('data/indicators.json').then(r => r.json()),
fetch('data/abiotic.json').then(r => r.json()),
fetch('data/reference.json').then(r => r.json()),
fetch('data/metadata.json').then(r => r.json()),
fetch('data/grid_index.json').then(r => r.json()),
]);
practicesData = p;
indicatorsData = i;
abioticData = a;
referenceData = r;
window.lahmpData.metadata = meta;
window.lahmpData.gridIndex = grid;
}
// ── localStorage ──────────────────────────────────────────────────────────
function saveState() {
window.assessment.last_updated = new Date().toISOString();
// Strip computed Step 4 outputs — they are re-derived on Step 4 load, not user input
const { step4_outputs, ...toSave } = window.assessment;
localStorage.setItem('lahmp_assessment', JSON.stringify(toSave));
localStorage.setItem('lahmp_step', String(currentStep));
const el = document.getElementById('autosave');
if (el) { el.textContent = 'Saved'; el.classList.add('visible'); setTimeout(() => el.classList.remove('visible'), 2000); }
// Live checklist + button update
updateStepUI(currentStep);
}
function loadSavedState() {
try {
const s = localStorage.getItem('lahmp_assessment');
const step = localStorage.getItem('lahmp_step');
if (s) {
const parsed = JSON.parse(s);
// Deep merge to preserve default structure
Object.keys(parsed).forEach(k => { window.assessment[k] = parsed[k]; });
if (step) currentStep = Math.max(1, Math.min(4, parseInt(step) || 1));
return true;
}
} catch(e) { console.warn('Could not restore saved state', e); }
return false;
}
// ── Algorithm functions ────────────────────────────────────────────────────
function reduceConfidence(c) {
if (c === 'high') return 'medium';
if (c === 'medium') return 'low';
return null;
}
function confidenceRank(c) {
return { high: 3, medium: 2, low: 1 }[c] ?? 0;
}
function pressureAreaFraction(pressureId, landUseComposition) {
const keywords = PRESSURE_LAND_USE_KEYWORDS[pressureId];
if (!keywords || !landUseComposition || !landUseComposition.length) return 1; // no weighting
const total = landUseComposition.reduce((s, e) => s + (e.area_pct || 0), 0);
if (!total) return 1;
const relevant = landUseComposition
.filter(e => keywords.some(kw => (e.category || '').toLowerCase().includes(kw)))
.reduce((s, e) => s + (e.area_pct || 0), 0);
return relevant / total;
}
// ── Equipment keyword → category index (0-based, matches EQUIPMENT_CATEGORIES array) ──
function equipmentTextToIds(text) {
if (!text) return [];
const t = text.toLowerCase();
const ids = [];
if (/auger|soil.*sampl|bulk.density|soil.cor/.test(t)) ids.push(1);
if (/water quality|ph meter|dissolved oxygen|conductivity/.test(t)) ids.push(2);
if (/sweep net|pitfall|malaise|insect.*sampl/.test(t)) ids.push(5);
if (/bat detector|bioacoustic|acoustic recorder|ultrasonic/.test(t)) ids.push(6);
if (/\bedna\b|dna.*filter|sterile.*field.*kit/.test(t)) ids.push(7);
if (/soil laborator|infrared.*co|toc analys|loss.on.ignition|walkley/.test(t)) ids.push(8);
if (/molecular lab|pcr|sequencing|plfa|nlfa|freeze.dr/.test(t)) ids.push(9);
if (/microscop/.test(t)) ids.push(10);
if (/spectrophotometer|colorimeter/.test(t)) ids.push(11);
if (/gc.ms|external.*analytic.*lab|contract.*lab|specialist.*lab/.test(t)) ids.push(12);
return ids;
}
// Hard prerequisite check — true if step1 context satisfies the indicator's prerequisite.
// 'None...' always passes. Unknown text defaults to true (include by default).
function hardPrerequisiteMet(text, step1, step2) {
if (!text || /^\s*none\b/i.test(text)) return true;
const t = text.toLowerCase();
const lu = (step1.land_uses || []).map(l => l.toLowerCase()).join(' ');
const efg = (step1.efg_codes || []).join(' ').toLowerCase();
const geo = ((step1.country || '') + ' ' + (step1.admin_region || '')).toLowerCase();
if (/water body|pond|stream|river|wetland|ditch|paddy|aquatic/.test(t))
return /water|wetland|paddy|rice|irrigat|aquatic|riparian|f3\.3/.test(lu + ' ' + efg);
if (/arable crop|annual.*crop|biennial crop/.test(t))
return /crop|arable|cereal|annual/.test(lu);
if (/grassland|pasture|sward|meadow/.test(t))
return /grass|pasture|meadow|rangeland|sward/.test(lu);
if (/hedgerow|woody boundary|tree line|shelter belt/.test(t)) {
const pcodes = (step2?.selected_practices || []).map(p => p.p_code);
return /agroforest|hedgerow|woodland|orchard|plantation/.test(lu)
|| pcodes.some(p => ['P19','P20','P21','P22','P23'].includes(p));
}
if (/livestock.*dung|dung.*livestock|vertebrate.*dung/.test(t))
return (step1.livestock || []).length > 0 || /livestock|pasture|mixed.*livestock|grazing/.test(lu);
if (/at least one tree|individual woody plant >3m/.test(t))
return /agroforest|orchard|plantation|woodland|tree/.test(lu);
if (/termite presence/.test(t))
return /t7\.4|t7\.5|t4|t5|f3/.test(efg)
|| /tropical|subtropical|sahel|africa|asia|vietnam|india/.test(geo);
if (/permanent crop.*inter.row|inter.row.*orchard/.test(t))
return /permanent crop|orchard|plantation/.test(lu);
return true; // unknown prerequisite: include by default
}
// Conditionality check — true if landscape context activates this conditional indicator.
function conditionalityMet(text, step1) {
if (!text || !text.trim()) return true;
const t = text.toLowerCase();
const lu = (step1.land_uses || []).map(l => l.toLowerCase()).join(' ');
const efg = (step1.efg_codes || []).join(' ').toLowerCase();
const geo = ((step1.country || '') + ' ' + (step1.admin_region || '')).toLowerCase();
if (/dung beetle|livestock.*dung|vertebrate.*dung/.test(t))
return (step1.livestock || []).length > 0 || /livestock|pasture|mixed.*livestock/.test(lu);
if (/water body|breeding.*water|amphibian|no suitable breeding/.test(t))
return /water|wetland|paddy|rice|irrigat|aquatic/.test(lu + ' ' + efg);
if (/tropical.*subtropical|scarab|centipede/.test(t))
return /t7\.4|t7\.5|t4|t5|f3/.test(efg)
|| /tropical|subtropical|sahel|africa|asia|vietnam/.test(geo);
if (/crop pest|economic.*pest|ipm/.test(t))
return /crop|arable|cereal|annual/.test(lu);
return true;
}
function prepopulateChallenges(pressures, landUseComposition) {
const mapping = referenceData.pressure_to_challenge_mapping || {};
const challengeMap = {};
for (const pressure of pressures) {
if (pressure.status === 'not_relevant') continue;
for (const m of (mapping[pressure.id] || [])) {
let conf = m.confidence;
if (pressure.status === 'past' || pressure.status === 'not_sure') conf = reduceConfidence(conf);
if (!conf) continue;
// Area weighting: if this pressure's relevant land use covers < 10% of landscape, reduce confidence
const fraction = pressureAreaFraction(pressure.id, landUseComposition);
if (fraction < 0.10) conf = reduceConfidence(conf);
if (!conf) continue;
if (!challengeMap[m.challenge_id] || confidenceRank(conf) > confidenceRank(challengeMap[m.challenge_id])) {
challengeMap[m.challenge_id] = conf;
}
}
}
return Object.entries(challengeMap).map(([id, confidence]) => ({
id: parseInt(id), confidence, pre_populated: true, confirmed: false,
}));
}
function prepopulateServices(challenges) {
const mapping = referenceData.challenge_to_service_mapping || {};
const svcMap = {};
for (const c of challenges) {
if (!c.confirmed) continue;
for (const m of (mapping[c.id] || [])) {
let conf = m.confidence;
if (!svcMap[m.service_id] || confidenceRank(conf) > confidenceRank(svcMap[m.service_id])) {
svcMap[m.service_id] = conf;
}
}
}
return Object.entries(svcMap).map(([id]) => ({
id: parseInt(id), selected: true, priority_rank: null, pre_populated: true,
}));
}
function scorePractice(practice, step1) {
let pressurePts = 0, challengePts = 0, servicePts = 0;
const pressureIds = (step1.pressures || []).filter(p => p.status !== 'not_relevant').map(p => p.id);
pressurePts += (practice.block4_pressures || []).filter(id => pressureIds.includes(id)).length;
for (const cid of (practice.block5_challenges || [])) {
const uc = (step1.challenges || []).find(c => c.id === cid && c.confirmed);
if (!uc) continue;
challengePts += uc.confidence === 'high' ? 2 : uc.confidence === 'medium' ? 1 : 0;
}
for (const sid of (practice.block6_services || [])) {
const us = (step1.services || []).find(s => s.id === sid && s.selected);
if (!us || !us.priority_rank) continue;
servicePts += us.priority_rank === 1 ? 3 : us.priority_rank === 2 ? 2 : 1;
}
const total = pressurePts + challengePts + servicePts;
return { total, pressurePts, challengePts, servicePts };
}
function getEligiblePractices() {
const step1 = window.assessment.step1;
const prescreen = window.assessment.step2.prescreen;
const userLandUses = (step1.land_uses || []).map(l => l.toLowerCase());
const userEFGs = step1.efg_codes || [];
const PRESCREEN_QMAP = { q1: 'q1_trees', q2: 'q2_livestock', q3: 'q3_set_aside', q4: 'q4_inputs' };
return practicesData.map(p => {
// EFG filter
if (p.relevant_efgs && p.relevant_efgs.length && userEFGs.length) {
if (!p.relevant_efgs.some(e => userEFGs.includes(e))) return null;
}
// Land use filter
if (userLandUses.length) {
const allApp = [...(p.primary_applicability || []), ...(p.transformative_applicability || [])];
// Entries containing 'all' land use or 'none' (= universally applicable) always pass
const isUniversal = allApp.some(a => {
const al = a.toLowerCase();
return al.startsWith('none') || al.startsWith('all cropland') || al.startsWith('all land use');
});
if (!isUniversal) {
const overlap = allApp.some(a =>
userLandUses.some(ul => a.toLowerCase().includes(ul) || ul.includes(a.toLowerCase().split(' ')[0]))
);
if (allApp.length && !overlap) return null;
}
}
// Tier / pre-screen
let tier = 'standard';
if (p.prescreen_question) {
const key = PRESCREEN_QMAP[p.prescreen_question.toLowerCase()];
const answer = prescreen[key];
if (answer === 'not_currently') return null;
if (answer === 'open' || answer === 'open_conditionally') tier = 'transformative';
}
const scoreObj = scorePractice(p, step1);
return { ...p, score: scoreObj.total, scoreBreakdown: scoreObj, tier };
}).filter(Boolean);
}
function computeCapacityProfile(step3) {
const types = (step3.team_types || []);
const levels = types.map(t => TEAM_PROTOCOL_LEVEL[t.type] ?? 1);
const maxLevel = levels.length ? Math.max(...levels) : 1;
const totalDays = Object.values(step3.days_by_type || {}).reduce((a, b) => a + (Number(b) || 0), 0);
const siteCount = SITE_COUNT_MIDPOINT[step3.site_count_category] || 1;
return {
max_protocol_level: maxLevel,
available_days_total: totalDays,
per_site_days: totalDays / siteCount,
equipment_ids: step3.equipment_capabilities || [],
budget_tier: step3.budget_tier ?? 0,
willingness_profile: {
recruit: step3.willingness_recruit !== 'no',
time: step3.willingness_time !== 'no',
equipment: step3.willingness_equipment !== 'no',
},
};
}
function selectIndicatorGroups(step1, step2) {
const selectedPCodes = (step2.selected_practices || []).map(p => p.p_code);
const userEFGs = (step1.efg_codes || []);
const userLandUses = (step1.land_uses || []).map(l => l.toLowerCase());
const confirmedChallengeIds = (step1.challenges || []).filter(c => c.confirmed).map(c => c.id);
return indicatorsData
.filter(ind => ind.populated === true || ind.populated === 'draft' || ind.populated === 'partial')
.map(ind => {
// EFG filter
if (ind.relevant_efgs?.length && userEFGs.length) {
if (!ind.relevant_efgs.some(e => userEFGs.includes(e))) return null;
}
// Land use filter
if (ind.relevant_ipcc_land_use?.length && userLandUses.length) {
const indLU = ind.relevant_ipcc_land_use.map(l => l.toLowerCase());
const luPass = indLU.some(il =>
il === 'all categories' ||
userLandUses.some(ul => ul.includes(il) || il.includes(ul.split(' ')[0]))
);
if (!luPass) return null;
}
// Hard prerequisite check
if (ind.hard_prerequisite && !hardPrerequisiteMet(ind.hard_prerequisite, step1, step2)) return null;
// Conditionality check (Conditional-tier indicators only)
if (ind.tier === 'Conditional' && !conditionalityMet(ind.conditionality_criteria, step1)) return null;
const b2 = (ind.b2_practices_primarily_verified || []).some(p => selectedPCodes.includes(p));
const b1 = (ind.b1_practices_that_benefit || []).some(p => selectedPCodes.includes(p));
const ch = (ind.block5_challenges || []).some(id => confirmedChallengeIds.includes(id));
if (!b2 && !b1 && !ch) return null;
return { ...ind, inclusion_reason: b2 ? 'B2 primary verifier' : b1 ? 'B1 supporting' : 'Challenge signal', priority: b2 ? 3 : b1 ? 2 : 1 };
})
.filter(Boolean);
}
function assignProtocol(group, cap) {
const hasL1 = !!group.level1_protocol_name;
const hasL2 = !!group.level2_protocol_name;
const hasL3 = !!group.level3_protocol_name;
const maxAvail = hasL3 ? 3 : hasL2 ? 2 : hasL1 ? 1 : 0;
const minAvail = hasL1 ? 1 : hasL2 ? 2 : hasL3 ? 3 : 0;
if (maxAvail === 0) {
// Partial profile — linkages present but protocol content not yet authored
if (group.populated === 'partial') {
return { ...group, assigned_level: null, assigned_protocol: null, assigned_metric: null,
assigned_reference: null, assigned_reference_link: null, assigned_equipment_ids: [],
requires_upgrade: false, protocol_pending: true };
}
return null; // fully empty — skip
}
let level = Math.min(cap.max_protocol_level, maxAvail);
if (level < minAvail) level = minAvail; // upgrade to lowest available level
if (level === 3 && cap.budget_tier === 0) level = Math.max(minAvail, 2);
// Equipment override: downgrade to highest level where required equipment is available
{
const availableEq = cap.equipment_ids || [];
let equipLevel = level;
while (equipLevel > minAvail) {
const reqIds = equipmentTextToIds(group[`level${equipLevel}_equipment`] || '');
if (!reqIds.length || reqIds.every(id => availableEq.includes(id))) break;
equipLevel--;
}
level = equipLevel;
}
const proto = level === 3 ? group.level3_protocol_name : level === 2 ? group.level2_protocol_name : group.level1_protocol_name;
const metric = level === 3 ? group.level3_output_metric : level === 2 ? group.level2_output_metric : group.level1_output_metric;
const ref = group[`level${level}_reference`] || group.primary_reference || null;
const refLink = group[`level${level}_reference_link`] || null;
const assignedEqIds = equipmentTextToIds(group[`level${level}_equipment`] || '');
const requires_upgrade = level > cap.max_protocol_level;
// Draft profiles have system-proposed protocols awaiting expert validation
const protocol_draft = (group.populated === 'draft');
return { ...group, assigned_level: level, assigned_protocol: proto, assigned_metric: metric, assigned_reference: ref, assigned_reference_link: refLink, assigned_equipment_ids: assignedEqIds, requires_upgrade, protocol_draft };
}
// ── Operation 5 — Monitoring calendar ─────────────────────────────────────
// Seasonal preference windows (month indices, 0-based)
const SPRING_IDX = [2,3,4,5]; // March–June
const AUTUMN_IDX = [7,8,9,10]; // August–November
const WINTER_IDX = [11,0,1]; // December–February
const ALL_IDX = Array.from({length:12},(_,i)=>i);
const MONTH_NAMES_LC = ['january','february','march','april','may','june',
'july','august','september','october','november','december'];
// Split a sorted array of month indices into non-adjacent groups.
// Groups separated by a gap > 1 become separate windows.
function splitIntoWindows(indices) {
if (!indices.length) return [];
const groups = [];
let cur = [indices[0]];
for (let i = 1; i < indices.length; i++) {
if (indices[i] - indices[i-1] <= 1) { cur.push(indices[i]); }
else { groups.push(cur); cur = [indices[i]]; }
}
groups.push(cur);
return groups;
}
// Parse seasonal guidance text into one or two arrays of month indices.
// Returns an array of window arrays (e.g. [[2,3,4],[8,9,10]] for spring + autumn),
// or null if the text contains no usable season information.
function parseSeasonalWindow(text) {
if (!text || !text.trim()) return null;
const t = text.toLowerCase();
// Year-round
if (/\byear.round\b/.test(t) || t.includes('any season')) return [ALL_IDX];
const found = new Set();
// 1. "Month1–Month2" (en-dash, em-dash, or hyphen) — highest priority
const dashRe = new RegExp(
`\\b(${MONTH_NAMES_LC.join('|')})[\u2013\u2014\\-](${MONTH_NAMES_LC.join('|')})\\b`, 'g'
);
let m;
while ((m = dashRe.exec(t)) !== null) {
const s = MONTH_NAMES_LC.indexOf(m[1]), e = MONTH_NAMES_LC.indexOf(m[2]);
if (s !== -1 && e !== -1) {
if (e >= s) { for (let i = s; i <= e; i++) found.add(i); }
else { for (let i = s; i < 12; i++) found.add(i); for (let i = 0; i <= e; i++) found.add(i); }
}
}
// 2. "Month1 to Month2"
const toRe = new RegExp(
`\\b(${MONTH_NAMES_LC.join('|')})\\s+to\\s+(${MONTH_NAMES_LC.join('|')})\\b`, 'g'
);
while ((m = toRe.exec(t)) !== null) {
const s = MONTH_NAMES_LC.indexOf(m[1]), e = MONTH_NAMES_LC.indexOf(m[2]);
if (s !== -1 && e !== -1) {
if (e >= s) { for (let i = s; i <= e; i++) found.add(i); }
else { for (let i = s; i < 12; i++) found.add(i); for (let i = 0; i <= e; i++) found.add(i); }
}
}
// 3. Individual month names
MONTH_NAMES_LC.forEach((mn, i) => {
if (new RegExp(`\\b${mn}\\b`).test(t)) found.add(i);
});
if (found.size) {
const groups = splitIntoWindows([...found].sort((a,b) => a-b));
return groups.length ? groups : null;
}
// 4. Season keyword fallback
// Catch-all patterns use negative lookbehind to avoid double-matching
// inside "early spring", "late summer", etc.
const seasonMap = [
[/\bearly spring\b/, [1,2,3]],
[/\blate spring\b/, [3,4,5]],
[/(?<!early |late )\bspring\b/, [2,3,4]],
[/\bearly summer\b/, [4,5,6]],
[/\bmidsummer\b|\bmid.summer\b/, [5,6,7]],
[/\blate summer\b/, [7,8]],
[/(?<!early |late |mid)\bsummer\b/, [5,6,7]],
[/\bearly autumn\b|\bearly fall\b/, [8,9]],
[/(?<!early )\bautumn\b|(?<!early )\bfall\b/, [8,9,10]],
[/\bwinter\b/, [11,0,1]],
[/\bwet season\b/, [5,6,7,8]],
[/\bdry season\b/, [11,0,1,2]],
[/\bwarm season\b/, [4,5,6,7,8,9]],
];
const seasonFound = new Set();
for (const [re, idx] of seasonMap) {
if (re.test(t)) idx.forEach(i => seasonFound.add(i));
}
if (seasonFound.size) {
const groups = splitIntoWindows([...seasonFound].sort((a,b) => a-b));
return groups.length ? groups : null;
}
return null;
}
function stageSpeed(monitoringStage) {
const s = (monitoringStage || '').toLowerCase();
// Compound descriptors (e.g. "Fast–medium") → take the slower/more conservative end
if (s.startsWith('fast–medium') || s.startsWith('fast-medium')) return 'medium';
if (s.startsWith('slow–very') || s.startsWith('slow-very')) return 'slow';
if (s.startsWith('fast')) return 'fast';
if (s.startsWith('medium')) return 'medium';
if (s.startsWith('slow') || s.startsWith('very slow')) return 'slow';
return 'medium';
}
function buildMonitoringCalendar(groups, accessCalendar) {
// Pending-protocol groups have no seasonal window — exclude from calendar
groups = groups.filter(g => !g.protocol_pending);
// Build accessible month index set
const accessByIdx = {};
MONTHS.forEach((m, i) => {
const entry = accessCalendar.find(e => e.month === m);
accessByIdx[i] = entry ? entry.access : 'accessible';
});
const accessibleIdx = Object.entries(accessByIdx).filter(([,v]) => v === 'accessible').map(([k]) => parseInt(k));
const constrainedIdx = Object.entries(accessByIdx).filter(([,v]) => v === 'constrained').map(([k]) => parseInt(k));
function pickWindow(preferredIdx, fallbackIdx) {
const hits = preferredIdx.filter(i => accessibleIdx.includes(i));
if (hits.length) return hits;
return fallbackIdx.filter(i => accessibleIdx.includes(i));
}
function idxToRange(indices) {
if (!indices || !indices.length) return null;
const sorted = [...indices].sort((a,b)=>a-b);
if (sorted.length === 1) return MONTHS[sorted[0]].slice(0,3);
if (sorted[sorted.length-1] - sorted[0] === sorted.length - 1)
return `${MONTHS[sorted[0]].slice(0,3)}–${MONTHS[sorted[sorted.length-1]].slice(0,3)}`;
return sorted.map(i => MONTHS[i].slice(0,3)).join(', ');
}
return groups.map(g => {
const speed = stageSpeed(g.monitoring_stage);
// Use seasonal guidance from the assigned protocol level; fall back to level1 text
const seasonalText = g[`level${g.assigned_level}_seasonal_primary`]
|| g.level1_seasonal_primary || '';
const seasonalSecText = g[`level${g.assigned_level}_seasonal_secondary`]
|| g.level1_seasonal_secondary || '';
const parsed = parseSeasonalWindow(seasonalText);
const parsedSec = parseSeasonalWindow(seasonalSecText);
let windows = [];
let windowIndices = [];
if (accessibleIdx.length === 0) {
windows = ['No accessible months specified — define in Step 3'];
} else if (parsed && parsed.length) {
// Use indicator-specific windows, filtered to accessible months
const w1 = pickWindow(parsed[0], accessibleIdx);
// Use parsed[1] if primary text contained two windows; otherwise use secondary seasonal field
const w2 = parsed[1]
? pickWindow(parsed[1], [])
: (parsedSec?.[0] ? pickWindow(parsedSec[0], []) : null);
windowIndices = [...new Set([...w1, ...(w2 || [])])];
const r1 = idxToRange(w1);
const r2 = w2 && w2.length ? idxToRange(w2) : null;
if (r1 && r2 && r1 !== r2) windows = [r1, r2];
else if (r1) windows = [r1];
else windows = ['Any accessible month'];
} else {
// Speed-based heuristic fallback (no parseable seasonal text)
if (speed === 'fast') {
const sp = pickWindow(SPRING_IDX, WINTER_IDX);
const au = pickWindow(AUTUMN_IDX, SPRING_IDX);
windowIndices = [...new Set([...sp, ...au])];
const spRange = idxToRange(sp), auRange = idxToRange(au);
if (spRange && auRange && spRange !== auRange) windows = [spRange, auRange];
else if (spRange) windows = [spRange];
else windows = [auRange || 'Any accessible month'];
} else if (speed === 'medium') {
const sp = pickWindow(SPRING_IDX, [...AUTUMN_IDX, ...WINTER_IDX]);
windowIndices = sp;
windows = [idxToRange(sp) || 'Any accessible month'];
} else {
const best = pickWindow([...SPRING_IDX, ...AUTUMN_IDX], ALL_IDX);
windowIndices = best;
windows = [idxToRange(best) || 'Any accessible month'];
}
}
const constrainedNames = constrainedIdx.map(i => MONTHS[i].slice(0,3));
const caveat = constrainedNames.length
? ` (avoid: ${constrainedNames.join(', ')})`
: '';
return {
profile_name: g.profile_name,
category: g.category,
monitoring_stage: g.monitoring_stage || '—',
response_timescale: g.response_timescale || '—',
suggested_window: windows.join(' and ') + caveat,
window_month_indices: windowIndices,
frequency: speed === 'fast' ? 'Annual (×2)' : speed === 'medium' ? 'Annual' : 'Every 2–5 years',
};
});
}
// ── Operation 4 — Capacity fitting ─────────────────────────────────────────
// Estimated field days per indicator per site at each protocol level
const DAYS_PER_LEVEL = { 1: 0.5, 2: 1.0, 3: 1.5 };
function priorityScore(group, step2, step1) {
const selectedPCodes = (step2.selected_practices || []).map(p => p.p_code);
const top3Challenges = (step1.challenges || [])
.filter(c => c.confirmed)
.sort((a, b) => confidenceRank(b.confidence) - confidenceRank(a.confidence))
.slice(0, 3).map(c => c.id);
const top3Services = (step1.services || [])
.filter(s => s.selected && s.priority_rank)
.sort((a, b) => a.priority_rank - b.priority_rank)
.slice(0, 3).map(s => s.id);
let score = 0;
score += (group.b2_practices_primarily_verified || []).filter(p => selectedPCodes.includes(p)).length * 3;
score += (group.block5_challenges || []).filter(id => top3Challenges.includes(id)).length * 2;
score += (group.block6_services || []).filter(id => top3Services.includes(id)).length * 1;
if (group.tier === 'Universal') score += 2;
if (group.monitoring_stage?.startsWith('Fast')) score += 1;
return score;
}
function capacityFit(assigned, cap, step2, step1) {
// Pending-protocol groups are never counted against capacity — separate them out
const pendingGroups = assigned.filter(g => g.protocol_pending);
const activeGroups = assigned.filter(g => !g.protocol_pending);
if (!cap.available_days_total || !cap.per_site_days) return { kept: [...activeGroups, ...pendingGroups], trimmed: [] };
const siteCount = SITE_COUNT_MIDPOINT[window.assessment.step3.site_count_category] || 1;
// Score and sort active groups only
const scored = activeGroups.map(g => ({
...g,
_priority: priorityScore(g, step2, step1),
_days_required: (DAYS_PER_LEVEL[g.assigned_level] || 0.5) * siteCount,
})).sort((a, b) => b._priority - a._priority || b.assigned_level - a.assigned_level);
const kept = [];
const trimmed = [];
let usedDays = 0;
for (const g of scored) {
if (usedDays + g._days_required <= cap.available_days_total) {
usedDays += g._days_required;
kept.push(g);
} else {
const daysShort = (g._days_required - (cap.available_days_total - usedDays)).toFixed(1);
const unlockParts = [`+${daysShort} monitoring days/year`];
if (!cap.willingness_profile.time) unlockParts.push('or increase monitoring time (Step 3 Q2b)');
if (!cap.willingness_profile.recruit) unlockParts.push('or recruit additional team members (Step 3 Q1b)');
trimmed.push({
...g,
trim_reason: `Exceeds capacity (needs ${g._days_required.toFixed(1)} days/cycle; ${(cap.available_days_total - usedDays).toFixed(1)} remaining).`,
unlock_hint: unlockParts.join(', '),
});
}
}
return { kept: [...kept, ...pendingGroups], trimmed };
}
function runStep4Algorithm() {
const { step1, step2, step3 } = window.assessment;
const cap = computeCapacityProfile(step3);
step3.capacity_profile = cap;
// Op 1 – Practice chains
const themeMap = {};
for (const p of (step2.selected_practices || [])) {
if (!themeMap[p.theme]) themeMap[p.theme] = [];
themeMap[p.theme].push(p);
}
const practice_chains = Object.entries(themeMap).map(([theme, practices]) => ({
theme, chain_label: THEME_TO_CHAIN[theme] || theme, practices,
}));
// Op 2 – Indicator group selection
const rawGroups = selectIndicatorGroups(step1, step2);
const selectedPCodes = (step2.selected_practices || []).map(p => p.p_code);
const availableEq = cap.equipment_ids || [];
const selected_abiotic = abioticData
.filter(a => a.universal_baseline || (a.linked_practices || []).some(p => selectedPCodes.includes(p)))
.map(a => {
const reqEq = a.equipment_required || [];
const missing = reqEq.filter(id => !availableEq.includes(id));
if (!missing.length) return a;
return {
...a,
equipment_gap: true,
missing_equipment: missing.map(id => EQUIPMENT_CATEGORIES[id] || `Cat. ${id}`),
};
});
// Op 3 – Protocol assignment
const withProtocols = rawGroups.map(g => assignProtocol(g, cap)).filter(Boolean);
// Op 4 – Capacity fitting
const { kept: protocol_assignments, trimmed: trimmed_groups } = capacityFit(withProtocols, cap, step2, step1);
// Op 5 – Calendar (uses Step 3 access calendar to suggest monitoring windows)
const calendar = buildMonitoringCalendar(protocol_assignments, step3.access_calendar || []);
// Narrative
const ongoingPressures = (step1.pressures || [])
.filter(p => p.status === 'ongoing')
.slice(0, 3)
.map(p => {
if (p.id === 28) return p.other_text?.trim() || null;
return (referenceData.block4_pressures || []).find(r => r.id === p.id)?.name;
})
.filter(Boolean);
const topChallenges = (step1.challenges || []).filter(c => c.confirmed)
.sort((a, b) => confidenceRank(b.confidence) - confidenceRank(a.confidence))
.slice(0, 3)
.map(c => (referenceData.block5_challenges || []).find(r => r.id === c.id)?.name).filter(Boolean);
const topServices = (step1.services || []).filter(s => s.selected && s.priority_rank)
.sort((a,b) => a.priority_rank - b.priority_rank).slice(0, 3)
.map(s => (referenceData.block6_services || []).find(r => r.id === s.id)?.name).filter(Boolean);
const levelLabel = cap.max_protocol_level === 1
? 'community observer level (Protocol Level 1)'
: cap.max_protocol_level === 2
? 'technician level (Protocol Level 2)'
: 'research level (Protocol Level 3)';
const totalDaysNeeded = withProtocols.reduce((sum, g) => {
const siteCount = SITE_COUNT_MIDPOINT[step3.site_count_category] || 1;
return sum + (DAYS_PER_LEVEL[g.assigned_level] || 0.5) * siteCount;
}, 0);
// EFG context for narrative
const efgNames = (step1.efg_codes || []).map(code => {
const opt = (referenceData.efg_options || []).find(e => e.code === code);
return opt ? opt.name : code;
});
const efgContext = efgNames.length
? ` — a landscape characterised by ${efgNames.slice(0, 2).join(' and ')} ecosystems`
: '';
window.assessment.step4_outputs = {
practice_chains,
selected_indicator_groups: rawGroups,
selected_abiotic,
protocol_assignments,
trimmed_groups,
calendar,
narrative: {
paragraph1: `Your monitoring programme has been designed specifically for ${step1.landscape_name || 'your landscape'}${step1.country ? ', ' + step1.country : ''}${efgContext}. In Step 1, you identified ${(step1.pressures||[]).filter(p=>p.status!=='not_relevant').length} pressures currently affecting your land${ongoingPressures.length ? ' — particularly ' + ongoingPressures.join(', ') : ''}. These pressures are contributing to ${(step1.challenges||[]).filter(c=>c.confirmed).length} confirmed land health challenges${topChallenges.length ? ', with ' + topChallenges.join(', ') + ' being the most significant' : ''}.`,
paragraph2: `In Step 2, you selected ${(step2.selected_practices||[]).length} sustainable land management practice${(step2.selected_practices||[]).length!==1?'s':''} across ${practice_chains.length} theme${practice_chains.length!==1?'s':''}. The ecosystem services you most want to see recover are${topServices.length ? ': ' + topServices.join(', ') : ' as described in your profile'}.`,
paragraph3: (function() {
const activeCount = protocol_assignments.filter(g => !g.protocol_pending).length;
const pendingCount = protocol_assignments.filter(g => g.protocol_pending).length;
const pendingNote = pendingCount > 0 ? ` An additional ${pendingCount} group${pendingCount!==1?'s are':' is'} identified but awaiting protocol specification.` : '';
return `Your team capacity supports ${levelLabel} monitoring. ${totalDaysNeeded > cap.available_days_total ? `The full indicator set requires an estimated ${totalDaysNeeded.toFixed(0)} field days; your programme has been fitted to your ${cap.available_days_total} available days, retaining` : 'Your programme includes'} ${activeCount} biological indicator group${activeCount!==1?'s':''} and ${selected_abiotic.length} abiotic indicator${selected_abiotic.length!==1?'s':''}.${pendingNote} ${selected_abiotic.filter(a=>a.universal_baseline).length} abiotic indicators form your universal baseline package, to be established in Year 1 before biological monitoring begins.`;
})(),
paragraph4: `With ${cap.available_days_total} monitoring days available across your team (${cap.per_site_days.toFixed(1)} days per site), ${trimmed_groups.length > 0 ? `${trimmed_groups.length} indicator group${trimmed_groups.length!==1?'s were':' was'} deferred to the Enhancement Recommendations section below — these could be added if your team or budget grows.` : 'your full indicator set fits within your current capacity.'}`,
},
};
}
// ── Tag picker (reusable autocomplete multi-select) ───────────────────
function renderTagPickerHtml(id, selectedArr, placeholder) {
const arr = selectedArr || [];
const hasTags = arr.length > 0 ? ' has-tags' : '';
const tags = arr.map(v =>
`<span class="tp-tag">${esc(v)}<button type="button" class="tp-remove" data-value="${esc(v)}" aria-label="Remove ${esc(v)}">×</button></span>`
).join('');
return `<div class="tag-picker${hasTags}" id="${esc(id)}-picker">
<div class="tp-tags" id="${esc(id)}-tp-tags">${tags}</div>
<div class="tp-control">
<input type="text" class="tp-input" id="${esc(id)}-tp-input"
placeholder="${esc(placeholder)}" autocomplete="off" spellcheck="false">
<ul class="tp-dropdown is-hidden" id="${esc(id)}-tp-dropdown" role="listbox"></ul>
</div>
</div>`;
}
function initTagPicker({ id, items, getSelected, onAdd, onRemove, showAllIfEmpty = true, limit = 30 }) {
const input = document.getElementById(id + '-tp-input');
const dropdown = document.getElementById(id + '-tp-dropdown');
const tagsEl = document.getElementById(id + '-tp-tags');
const pickerEl = document.getElementById(id + '-picker');
if (!input || !dropdown || !tagsEl || !pickerEl) return;
function hl(text, q) {
if (!q) return esc(text);
const lo = text.toLowerCase(), qi = lo.indexOf(q.toLowerCase());
if (qi < 0) return esc(text);
return esc(text.slice(0, qi))
+ '<strong>' + esc(text.slice(qi, qi + q.length)) + '</strong>'
+ esc(text.slice(qi + q.length));
}
function positionDropdown() {
const rect = input.getBoundingClientRect();
dropdown.style.top = (rect.bottom + 3) + 'px';
dropdown.style.left = rect.left + 'px';
dropdown.style.width = rect.width + 'px';
}
function open(query) {
const q = (query || '').trim();
const sel = getSelected();
let pool = items.filter(item => !sel.includes(item.value));
if (q) {
const ql = q.toLowerCase();
pool = pool.filter(item =>
item.label.toLowerCase().includes(ql) || (item.sublabel || '').toLowerCase().includes(ql)
);
} else if (!showAllIfEmpty) {
dropdown.innerHTML = `<li class="tp-hint">Type to search…</li>`;
positionDropdown();
dropdown.classList.remove('is-hidden');
return;
}
pool = pool.slice(0, limit);
if (!pool.length) {
dropdown.innerHTML = `<li class="tp-empty">${q ? 'No matches' : 'All options selected'}</li>`;
} else {
dropdown.innerHTML = pool.map(item =>
`<li class="tp-item" data-value="${esc(item.value)}" tabindex="-1" role="option">
<span class="tp-label">${hl(item.label, q)}</span>
${item.sublabel ? `<span class="tp-sublabel">${hl(item.sublabel, q)}</span>` : ''}
</li>`
).join('');
dropdown.querySelectorAll('.tp-item').forEach(li => {
li.addEventListener('mousedown', e => { e.preventDefault(); select(li.dataset.value); });
});
}
positionDropdown();
dropdown.classList.remove('is-hidden');
}
function close() { dropdown.classList.add('is-hidden'); }
function select(value) {
if (getSelected().includes(value)) return;
onAdd(value);
const span = document.createElement('span');
span.className = 'tp-tag';
span.innerHTML = `${esc(value)}<button type="button" class="tp-remove" data-value="${esc(value)}" aria-label="Remove ${esc(value)}">×</button>`;
tagsEl.appendChild(span);
pickerEl.classList.add('has-tags');
input.value = '';
close();
input.focus();
}
input.addEventListener('focus', () => open(input.value));
input.addEventListener('input', () => open(input.value));
input.addEventListener('blur', () => setTimeout(close, 200));
input.addEventListener('keydown', e => {
if (e.key === 'Escape') { close(); input.blur(); }
if (e.key === 'Enter') { e.preventDefault(); }
if (e.key === 'ArrowDown') {
e.preventDefault();
dropdown.querySelector('.tp-item')?.focus();
}
});
dropdown.addEventListener('keydown', e => {
const els = [...dropdown.querySelectorAll('.tp-item')];
const idx = els.indexOf(document.activeElement);
if (e.key === 'ArrowDown') { e.preventDefault(); els[Math.min(idx + 1, els.length - 1)]?.focus(); }
if (e.key === 'ArrowUp') { e.preventDefault(); idx <= 0 ? input.focus() : els[idx - 1].focus(); }
if (e.key === 'Enter') { e.preventDefault(); if (idx >= 0) select(els[idx].dataset.value); }
if (e.key === 'Escape') { close(); input.focus(); }
});
tagsEl.addEventListener('click', e => {
const btn = e.target.closest('.tp-remove');