@burdenoff/microfe-healthybowl 2026.709.4 → 2026.710.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,18 +2,19 @@ import { __toESM as e } from "../../_virtual/_rolldown/runtime.js";
2
2
  import { useHealthyBowl as t } from "../context/HealthyBowlContext.js";
3
3
  import { ToastContainer as n } from "./Toast.js";
4
4
  import { require_leaflet_src as r } from "../../node_modules/leaflet/dist/leaflet-src.js";
5
- import { useToast as i } from "../hooks/useToast.js";
5
+ import { geocodePlace as i } from "../utils/geocode.js";
6
+ import { useToast as a } from "../hooks/useToast.js";
6
7
  import { ensureLeafletCss as ee } from "../utils/leaflet.js";
7
- import { extractPolygon as te, isValidPolygon as a, polygonAreaInUnit as o, ringToPolygon as s } from "../utils/geo.js";
8
- import { useCallback as c, useEffect as ne, useRef as l, useState as u } from "react";
9
- import { useI18n as re } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
10
- import { Check as ie, LocateFixed as ae, MapPin as oe, MapPinned as se, Pencil as ce, Save as le, Trash2 as ue, Upload as de, X as fe } from "lucide-react";
11
- import { Fragment as d, jsx as f, jsxs as p } from "react/jsx-runtime";
12
- import { Button as m } from "@burdenoff/fe-libs/ui";
13
- import { gql as h } from "@apollo/client";
14
- import { useMutation as pe } from "@apollo/client/react";
8
+ import { extractPolygon as te, isValidPolygon as ne, polygonAreaInUnit as o, ringToPolygon as re } from "../utils/geo.js";
9
+ import { useCallback as s, useEffect as c, useRef as l, useState as u } from "react";
10
+ import { useI18n as ie } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
11
+ import { Check as ae, LocateFixed as oe, MapPin as se, MapPinned as ce, Pencil as le, Save as ue, Search as de, Trash2 as fe, Upload as pe, X as d } from "lucide-react";
12
+ import { Fragment as f, jsx as p, jsxs as m } from "react/jsx-runtime";
13
+ import { Button as h } from "@burdenoff/fe-libs/ui";
14
+ import { gql as g } from "@apollo/client";
15
+ import { useMutation as me } from "@apollo/client/react";
15
16
  //#region src/healthybowl/components/FieldMap.tsx
16
- var g = /* @__PURE__ */ e(r(), 1), me = h`
17
+ var _ = /* @__PURE__ */ e(r(), 1), he = g`
17
18
  mutation UpdateHealthyBowlFieldBoundary($input: UpdateHealthyBowlFieldInput!) {
18
19
  updateHealthyBowlField(input: $input) {
19
20
  id
@@ -22,42 +23,73 @@ var g = /* @__PURE__ */ e(r(), 1), me = h`
22
23
  location
23
24
  }
24
25
  }
25
- `, he = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", ge = "Esri, Maxar, Earthstar Geographics", _ = "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", v = "© OpenTopoMap (CC-BY-SA) · © OpenStreetMap contributors", _e = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", ve = {
26
+ `, ge = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", _e = "Esri, Maxar, Earthstar Geographics", ve = "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", ye = "© OpenTopoMap (CC-BY-SA) · © OpenStreetMap contributors", be = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", xe = {
26
27
  color: "#16a34a",
27
28
  weight: 2,
28
29
  fillColor: "#16a34a",
29
30
  fillOpacity: .25
30
- }, ye = {
31
+ }, Se = {
31
32
  color: "#f59e0b",
32
33
  weight: 2,
33
34
  dashArray: "6 4",
34
35
  fillColor: "#f59e0b",
35
36
  fillOpacity: .15
36
- }, y = 16, be = 17, b = (e) => !!(e && Number.isFinite(e.lat) && Number.isFinite(e.lng) && e.lat >= -90 && e.lat <= 90 && e.lng >= -180 && e.lng <= 180 && (e.lat !== 0 || e.lng !== 0)), x = ({ fieldId: e, unit: r, center: h, initialBoundary: x, onSaved: S }) => {
37
- let { t: C } = re(), { workspaceId: w } = t(), { toasts: xe, toast: T, dismiss: Se } = i(), E = l(null), D = l(null), O = l(null), k = l(null), A = l(null), j = l(null), M = l(null), N = l([]), P = l([]), F = l(null), I = l("view"), [L, Ce] = u("loading"), [R, z] = u("view"), [B, V] = u(!1), [H, U] = u(null), [we, W] = u(0), [Te, G] = u(!1), [K, q] = u(!1), [J, Y] = u(!1), [Ee] = pe(me), X = c(() => {
38
- let e = O.current;
39
- A.current && e && e.removeLayer(A.current), A.current = null, N.current.forEach((t) => e?.removeLayer(t)), N.current = [], P.current = [], W(0);
40
- }, []), Z = c((e, t) => {
41
- let n = O.current;
37
+ }, Ce = 16, we = 17, v = (e) => !!(e && Number.isFinite(e.lat) && Number.isFinite(e.lng) && e.lat >= -90 && e.lat <= 90 && e.lng >= -180 && e.lng <= 180 && (e.lat !== 0 || e.lng !== 0)), Te = (e) => {
38
+ let t = e.trim().match(/^(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)$/);
39
+ if (!t) return null;
40
+ let n = Number(t[1]), r = Number(t[2]);
41
+ return v({
42
+ lat: n,
43
+ lng: r
44
+ }) ? {
45
+ lat: n,
46
+ lng: r,
47
+ label: `${n.toFixed(6)}, ${r.toFixed(6)}`
48
+ } : null;
49
+ }, y = ({ fieldId: e, unit: r, center: g, initialBoundary: y, onSaved: Ee }) => {
50
+ let { t: b } = ie(), { workspaceId: De } = t(), { toasts: Oe, toast: x, dismiss: ke } = a(), Ae = l(null), S = l(null), C = l(null), w = l(null), T = l(null), E = l(null), D = l(null), O = l(null), k = l(g ?? null), A = l([]), j = l([]), M = l(null), N = l("view"), [P, je] = u("loading"), [F, I] = u("view"), [L, R] = u(!1), [z, B] = u(null), [Me, V] = u(0), [Ne, H] = u(!1), [Pe, U] = u(!1), [Fe, Ie] = u(!1), [Le, W] = u(!1), [G, Re] = u(""), [K, ze] = u(!1), [q, J] = u(null), Be = Ne || Pe, [Ve] = me(he);
51
+ c(() => {
52
+ k.current = g ?? null;
53
+ }, [g]);
54
+ let Y = s(() => {
55
+ let e = C.current;
56
+ T.current && e && e.removeLayer(T.current), T.current = null, A.current.forEach((t) => e?.removeLayer(t)), A.current = [], j.current = [], V(0);
57
+ }, []), X = s((e, t) => {
58
+ let n = C.current;
42
59
  if (!n) return;
43
- k.current && n.removeLayer(k.current);
44
- let i = g.default.geoJSON(e, { style: () => ve }).addTo(n);
45
- if (k.current = i, F.current = e, V(!0), U(o(e, r)), t) try {
60
+ w.current && n.removeLayer(w.current);
61
+ let i = _.default.geoJSON(e, { style: () => xe }).addTo(n);
62
+ if (w.current = i, M.current = e, R(!0), B(o(e, r)), t) try {
46
63
  n.fitBounds(i.getBounds(), {
47
64
  padding: [24, 24],
48
65
  maxZoom: 18
49
66
  });
50
67
  } catch {}
51
- }, [r]), Q = c(() => {
52
- let e = O.current;
53
- k.current && e && e.removeLayer(k.current), k.current = null, F.current = null, V(!1), U(null);
54
- }, []), De = c(() => {
55
- let e = O.current;
56
- j.current && e && e.removeLayer(j.current), M.current && e && e.removeLayer(M.current), j.current = null, M.current = null;
57
- }, []), Oe = c(() => {
58
- let e = O.current;
68
+ }, [r]), Z = s(() => {
69
+ let e = C.current;
70
+ w.current && e && e.removeLayer(w.current), w.current = null, M.current = null, R(!1), B(null);
71
+ }, []), He = s(() => {
72
+ let e = C.current;
73
+ E.current && e && e.removeLayer(E.current), D.current && e && e.removeLayer(D.current), E.current = null, D.current = null;
74
+ }, []), Ue = s(() => {
75
+ let e = C.current;
76
+ O.current && e && e.removeLayer(O.current), O.current = null, J(null), U(!1);
77
+ }, []), Q = s((e) => {
78
+ let t = C.current;
79
+ if (!t) return;
80
+ O.current && t.removeLayer(O.current);
81
+ let n = [e.lat, e.lng], r = document.createElement("span");
82
+ r.textContent = e.label, O.current = _.default.circleMarker(n, {
83
+ radius: 8,
84
+ color: "#ffffff",
85
+ weight: 2,
86
+ fillColor: "#16a34a",
87
+ fillOpacity: 1
88
+ }).addTo(t).bindPopup(r).openPopup(), t.flyTo(n, Math.max(t.getZoom(), we), { duration: .75 }), J(e), U(!0);
89
+ }, []), We = s(() => {
90
+ let e = C.current;
59
91
  if (!e) return;
60
- let t = k.current;
92
+ let t = w.current;
61
93
  if (t) try {
62
94
  let n = t.getBounds();
63
95
  if (n.isValid()) {
@@ -68,53 +100,58 @@ var g = /* @__PURE__ */ e(r(), 1), me = h`
68
100
  return;
69
101
  }
70
102
  } catch {}
71
- if (b(h)) {
72
- e.flyTo([h.lat, h.lng], y, { duration: .6 });
103
+ let n = k.current;
104
+ if (v(n)) {
105
+ e.flyTo([n.lat, n.lng], Ce, { duration: .6 });
73
106
  return;
74
107
  }
75
- T({
76
- title: C("healthybowl.fieldMap.toast.noFieldLocation.title", "No field location set"),
77
- description: C("healthybowl.fieldMap.toast.noFieldLocation.description", "Draw a boundary or save GPS coordinates for this field first."),
108
+ x({
109
+ title: b("healthybowl.fieldMap.toast.noFieldLocation.title", "No field location set"),
110
+ description: b("healthybowl.fieldMap.toast.noFieldLocation.description", "Draw a boundary or save GPS coordinates for this field first."),
78
111
  variant: "warning"
79
112
  });
80
- }, [
81
- h,
82
- C,
83
- T
84
- ]), ke = c(() => {
85
- let e = O.current;
113
+ }, [b, x]), Ge = s(() => {
114
+ let e = C.current;
86
115
  if (e) {
87
116
  if (typeof navigator > "u" || !navigator.geolocation) {
88
- T({
89
- title: C("healthybowl.fieldMap.toast.locationUnsupported.title", "Location unavailable"),
90
- description: C("healthybowl.fieldMap.toast.locationUnsupported.description", "This browser does not support device location."),
117
+ x({
118
+ title: b("healthybowl.fieldMap.toast.locationUnsupported.title", "Location unavailable"),
119
+ description: b("healthybowl.fieldMap.toast.locationUnsupported.description", "This browser does not support device location."),
91
120
  variant: "warning"
92
121
  });
93
122
  return;
94
123
  }
95
- Y(!0), navigator.geolocation.getCurrentPosition((t) => {
124
+ W(!0), navigator.geolocation.getCurrentPosition((t) => {
96
125
  let n = [t.coords.latitude, t.coords.longitude];
97
- De(), M.current = g.default.circle(n, {
126
+ He(), D.current = _.default.circle(n, {
98
127
  radius: Math.max(10, t.coords.accuracy || 0),
99
128
  color: "#2563eb",
100
129
  fillColor: "#3b82f6",
101
130
  fillOpacity: .12,
102
131
  opacity: .45,
103
132
  weight: 1
104
- }).addTo(e), j.current = g.default.circleMarker(n, {
133
+ }).addTo(e), E.current = _.default.circleMarker(n, {
105
134
  radius: 7,
106
135
  color: "#ffffff",
107
136
  weight: 2,
108
137
  fillColor: "#2563eb",
109
138
  fillOpacity: 1
110
- }).addTo(e), e.flyTo(n, Math.max(e.getZoom(), be), { duration: .75 }), Y(!1);
139
+ }).addTo(e), e.flyTo(n, Math.max(e.getZoom(), we), { duration: .75 }), Q({
140
+ lat: t.coords.latitude,
141
+ lng: t.coords.longitude,
142
+ label: b("healthybowl.fieldMap.location.currentLabel", "My current location")
143
+ }), W(!1), x({
144
+ title: b("healthybowl.fieldMap.toast.locationReady.title", "Location ready"),
145
+ description: b("healthybowl.fieldMap.toast.locationReady.description", "Save to store this as the field GPS location."),
146
+ variant: "success"
147
+ });
111
148
  }, (e) => {
112
149
  let t = e.code === e.PERMISSION_DENIED;
113
- T({
114
- title: t ? C("healthybowl.fieldMap.toast.locationBlocked.title", "Location blocked") : C("healthybowl.fieldMap.toast.locationFailed.title", "Could not get location"),
115
- description: t ? C("healthybowl.fieldMap.toast.locationBlocked.description", "Allow location access in the browser, then try again.") : C("healthybowl.fieldMap.toast.locationFailed.description", "Make sure GPS is enabled and the page is open over HTTPS."),
150
+ x({
151
+ title: t ? b("healthybowl.fieldMap.toast.locationBlocked.title", "Location blocked") : b("healthybowl.fieldMap.toast.locationFailed.title", "Could not get location"),
152
+ description: t ? b("healthybowl.fieldMap.toast.locationBlocked.description", "Allow location access in the browser, then try again.") : b("healthybowl.fieldMap.toast.locationFailed.description", "Make sure GPS is enabled and the page is open over HTTPS."),
116
153
  variant: "warning"
117
- }), Y(!1);
154
+ }), W(!1);
118
155
  }, {
119
156
  enableHighAccuracy: !0,
120
157
  timeout: 12e3,
@@ -122,39 +159,91 @@ var g = /* @__PURE__ */ e(r(), 1), me = h`
122
159
  });
123
160
  }
124
161
  }, [
125
- De,
126
- C,
127
- T
128
- ]), Ae = c(() => {
129
- let e = O.current;
162
+ He,
163
+ Q,
164
+ b,
165
+ x
166
+ ]), Ke = s(async (e) => {
167
+ e.preventDefault();
168
+ let t = G.trim();
169
+ if (!t) {
170
+ x({
171
+ title: b("healthybowl.fieldMap.toast.searchRequired.title", "Place required"),
172
+ description: b("healthybowl.fieldMap.toast.searchRequired.description", "Enter a village, city, region, or coordinates."),
173
+ variant: "warning"
174
+ });
175
+ return;
176
+ }
177
+ let n = Te(t);
178
+ if (n) {
179
+ Q(n);
180
+ return;
181
+ }
182
+ ze(!0);
183
+ try {
184
+ let e = await i(t);
185
+ if (!e) {
186
+ x({
187
+ title: b("healthybowl.fieldMap.toast.searchNotFound.title", "Place not found"),
188
+ description: b("healthybowl.fieldMap.toast.searchNotFound.description", "Try a more specific location, such as village, district, and state."),
189
+ variant: "warning"
190
+ });
191
+ return;
192
+ }
193
+ let n = [
194
+ e.name,
195
+ e.admin1,
196
+ e.country
197
+ ].filter(Boolean).join(", ") || t;
198
+ Q({
199
+ lat: e.latitude,
200
+ lng: e.longitude,
201
+ label: n
202
+ });
203
+ } catch (e) {
204
+ x({
205
+ title: b("healthybowl.fieldMap.toast.searchFailed.title", "Search failed"),
206
+ description: e instanceof Error ? e.message : String(e),
207
+ variant: "error"
208
+ });
209
+ } finally {
210
+ ze(!1);
211
+ }
212
+ }, [
213
+ G,
214
+ Q,
215
+ b,
216
+ x
217
+ ]), qe = s(() => {
218
+ let e = C.current;
130
219
  if (!e) return;
131
- let t = P.current;
132
- A.current && e.removeLayer(A.current), t.length >= 2 ? A.current = g.default.polygon(t, ye).addTo(e) : A.current = null;
133
- }, []), $ = c(() => {
134
- if (P.current.length < 3) {
135
- T({
136
- title: C("healthybowl.fieldMap.toast.needPoints.title", "Need at least 3 points"),
137
- description: C("healthybowl.fieldMap.toast.needPoints.description", "Click on the map to add more boundary corners."),
220
+ let t = j.current;
221
+ T.current && e.removeLayer(T.current), t.length >= 2 ? T.current = _.default.polygon(t, Se).addTo(e) : T.current = null;
222
+ }, []), $ = s(() => {
223
+ if (j.current.length < 3) {
224
+ x({
225
+ title: b("healthybowl.fieldMap.toast.needPoints.title", "Need at least 3 points"),
226
+ description: b("healthybowl.fieldMap.toast.needPoints.description", "Click on the map to add more boundary corners."),
138
227
  variant: "warning"
139
228
  });
140
229
  return;
141
230
  }
142
- let e = s(P.current.map((e) => ({
231
+ let e = re(j.current.map((e) => ({
143
232
  lat: e.lat,
144
233
  lng: e.lng
145
234
  })));
146
- X(), I.current = "view", z("view"), e && (Z(e, !1), G(!0));
235
+ Y(), N.current = "view", I("view"), e && (X(e, !1), H(!0));
147
236
  }, [
237
+ Y,
148
238
  X,
149
- Z,
150
- C,
151
- T
152
- ]), je = c((e) => {
153
- if (I.current !== "draw") return;
154
- let t = O.current;
239
+ b,
240
+ x
241
+ ]), Je = s((e) => {
242
+ if (N.current !== "draw") return;
243
+ let t = C.current;
155
244
  if (!t) return;
156
- P.current.push(e.latlng);
157
- let n = P.current.length === 1, r = g.default.circleMarker(e.latlng, {
245
+ j.current.push(e.latlng);
246
+ let n = j.current.length === 1, r = _.default.circleMarker(e.latlng, {
158
247
  radius: n ? 7 : 5,
159
248
  color: "#fff",
160
249
  weight: 2,
@@ -162,267 +251,324 @@ var g = /* @__PURE__ */ e(r(), 1), me = h`
162
251
  fillOpacity: 1
163
252
  }).addTo(t);
164
253
  n && r.on("click", (e) => {
165
- g.default.DomEvent.stopPropagation(e), $();
166
- }), N.current.push(r), W(P.current.length), Ae();
167
- }, [$, Ae]), Me = c(() => {
168
- Q(), X(), I.current = "draw", z("draw"), G(!0);
169
- }, [X, Q]), Ne = c(() => {
170
- X(), I.current = "view", z("view");
171
- }, [X]), Pe = c(() => {
172
- X(), Q(), I.current = "view", z("view"), G(!0);
173
- }, [X, Q]), Fe = c(async (e) => {
254
+ _.default.DomEvent.stopPropagation(e), $();
255
+ }), A.current.push(r), V(j.current.length), qe();
256
+ }, [$, qe]), Ye = s(() => {
257
+ Z(), Y(), N.current = "draw", I("draw"), H(!0);
258
+ }, [Y, Z]), Xe = s(() => {
259
+ Y(), N.current = "view", I("view");
260
+ }, [Y]), Ze = s(() => {
261
+ Y(), Z(), N.current = "view", I("view"), H(!0);
262
+ }, [Y, Z]), Qe = s(async (e) => {
174
263
  try {
175
264
  let t = await e.text(), n = JSON.parse(t);
176
- if (!a(n)) {
177
- T({
178
- title: C("healthybowl.fieldMap.toast.importInvalid.title", "No polygon found"),
179
- description: C("healthybowl.fieldMap.toast.importInvalid.description", "The file must contain a GeoJSON Polygon (Feature, FeatureCollection or geometry)."),
265
+ if (!ne(n)) {
266
+ x({
267
+ title: b("healthybowl.fieldMap.toast.importInvalid.title", "No polygon found"),
268
+ description: b("healthybowl.fieldMap.toast.importInvalid.description", "The file must contain a GeoJSON Polygon (Feature, FeatureCollection or geometry)."),
180
269
  variant: "error"
181
270
  });
182
271
  return;
183
272
  }
184
273
  let r = te(n);
185
- X(), I.current = "view", z("view"), Z(r, !0), G(!0), T({
186
- title: C("healthybowl.fieldMap.toast.imported.title", "Boundary imported"),
187
- description: C("healthybowl.fieldMap.toast.imported.description", "Review it on the map, then Save to persist."),
274
+ Y(), N.current = "view", I("view"), X(r, !0), H(!0), x({
275
+ title: b("healthybowl.fieldMap.toast.imported.title", "Boundary imported"),
276
+ description: b("healthybowl.fieldMap.toast.imported.description", "Review it on the map, then Save to persist."),
188
277
  variant: "success"
189
278
  });
190
279
  } catch {
191
- T({
192
- title: C("healthybowl.fieldMap.toast.importFailed.title", "Could not read file"),
193
- description: C("healthybowl.fieldMap.toast.importFailed.description", "Make sure it is a valid GeoJSON (.json / .geojson) file."),
280
+ x({
281
+ title: b("healthybowl.fieldMap.toast.importFailed.title", "Could not read file"),
282
+ description: b("healthybowl.fieldMap.toast.importFailed.description", "Make sure it is a valid GeoJSON (.json / .geojson) file."),
194
283
  variant: "error"
195
284
  });
196
285
  }
197
286
  }, [
287
+ Y,
198
288
  X,
199
- Z,
200
- C,
201
- T
202
- ]), Ie = c(async () => {
203
- q(!0);
289
+ b,
290
+ x
291
+ ]), $e = s(async () => {
292
+ Ie(!0);
204
293
  try {
205
- let t = F.current, n = t ? o(t, r) : void 0;
206
- await Ee({ variables: { input: {
294
+ let t = M.current, n = t ? o(t, r) : void 0, i = q ? {
295
+ lat: q.lat,
296
+ lng: q.lng
297
+ } : void 0;
298
+ await Ve({ variables: { input: {
207
299
  id: e,
208
300
  boundary: t,
209
301
  ...n == null ? {} : { area: n },
210
- context: { workspaceId: w }
211
- } } }), G(!1), S?.(), T({
212
- title: C("healthybowl.fieldMap.toast.saved.title", "Boundary saved"),
213
- description: t ? C("healthybowl.fieldMap.toast.saved.description", "Field area updated to {{area}} {{unit}}.", {
302
+ ...i ? { location: i } : {},
303
+ context: { workspaceId: De }
304
+ } } }), i && (k.current = i), H(!1), U(!1), J(null), Ee?.(), x({
305
+ title: b("healthybowl.fieldMap.toast.saved.title", "Map saved"),
306
+ description: i ? b("healthybowl.fieldMap.toast.savedLocation.description", "Field GPS location updated.") : t ? b("healthybowl.fieldMap.toast.saved.description", "Field area updated to {{area}} {{unit}}.", {
214
307
  area: String(n ?? ""),
215
308
  unit: r
216
- }) : C("healthybowl.fieldMap.toast.savedCleared.description", "Boundary removed from this field."),
309
+ }) : b("healthybowl.fieldMap.toast.savedCleared.description", "Boundary removed from this field."),
217
310
  variant: "success"
218
311
  });
219
312
  } catch (e) {
220
- T({
221
- title: C("healthybowl.fieldMap.toast.saveFailed.title", "Save failed"),
313
+ x({
314
+ title: b("healthybowl.fieldMap.toast.saveFailed.title", "Save failed"),
222
315
  description: String(e),
223
316
  variant: "error"
224
317
  });
225
318
  } finally {
226
- q(!1);
319
+ Ie(!1);
227
320
  }
228
321
  }, [
229
322
  e,
230
- S,
231
- C,
232
- T,
233
- r,
234
323
  Ee,
235
- w
324
+ q,
325
+ b,
326
+ x,
327
+ r,
328
+ Ve,
329
+ De
236
330
  ]);
237
- return ne(() => {
238
- let e = D.current;
331
+ return c(() => {
332
+ let e = S.current;
239
333
  if (!e) return;
240
334
  ee();
241
- let t = g.default.tileLayer(he, {
242
- attribution: ge,
335
+ let t = _.default.tileLayer(ge, {
336
+ attribution: _e,
243
337
  maxZoom: 19
244
- }), n = g.default.tileLayer(_, {
245
- attribution: v,
338
+ }), n = _.default.tileLayer(ve, {
339
+ attribution: ye,
246
340
  maxZoom: 17
247
- }), r = g.default.tileLayer(_, {
248
- attribution: v,
341
+ }), r = _.default.tileLayer(ve, {
342
+ attribution: ye,
249
343
  maxZoom: 17,
250
344
  opacity: .6
251
- }), i = g.default.tileLayer(_e, {
345
+ }), i = _.default.tileLayer(be, {
252
346
  attribution: "© OpenStreetMap contributors",
253
347
  maxZoom: 19
254
- }), o = g.default.map(e, {
348
+ }), a = _.default.map(e, {
255
349
  center: [20, 0],
256
350
  zoom: 2,
257
351
  scrollWheelZoom: !0,
258
352
  layers: [t]
259
353
  });
260
- O.current = o, g.default.control.layers({ [C("healthybowl.fieldMap.layers.satellite", "Satellite (Esri)")]: t }, {
261
- [C("healthybowl.fieldMap.layers.terrain", "Terrain (OpenTopoMap)")]: n,
262
- [C("healthybowl.fieldMap.layers.soil", "Soil (placeholder)")]: r,
263
- [C("healthybowl.fieldMap.layers.streets", "Streets (OSM)")]: i
264
- }, { collapsed: !1 }).addTo(o), o.on("click", je);
265
- let s = te(x);
266
- return s && a(s) ? Z(s, !0) : b(h) && o.setView([h.lat, h.lng], y), Ce("ready"), window.setTimeout(() => o.invalidateSize(), 80), () => {
267
- o.off("click", je), o.remove(), O.current = null, k.current = null, A.current = null, j.current = null, M.current = null, N.current = [], P.current = [], F.current = null;
354
+ C.current = a, _.default.control.layers({ [b("healthybowl.fieldMap.layers.satellite", "Satellite (Esri)")]: t }, {
355
+ [b("healthybowl.fieldMap.layers.terrain", "Terrain (OpenTopoMap)")]: n,
356
+ [b("healthybowl.fieldMap.layers.soil", "Soil (placeholder)")]: r,
357
+ [b("healthybowl.fieldMap.layers.streets", "Streets (OSM)")]: i
358
+ }, { collapsed: !1 }).addTo(a), a.on("click", Je);
359
+ let o = te(y);
360
+ return o && ne(o) ? X(o, !0) : v(g) && a.setView([g.lat, g.lng], Ce), je("ready"), window.setTimeout(() => a.invalidateSize(), 80), () => {
361
+ a.off("click", Je), a.remove(), C.current = null, w.current = null, T.current = null, E.current = null, D.current = null, O.current = null, A.current = [], j.current = [], M.current = null;
268
362
  };
269
- }, []), /* @__PURE__ */ p("div", {
363
+ }, []), /* @__PURE__ */ m("div", {
270
364
  className: "relative",
271
365
  children: [
272
- /* @__PURE__ */ p("div", {
366
+ /* @__PURE__ */ m("div", {
273
367
  className: "mb-3 flex flex-wrap items-center gap-2",
274
- children: [R === "view" ? /* @__PURE__ */ p(d, { children: [
275
- /* @__PURE__ */ p(m, {
368
+ children: [F === "view" ? /* @__PURE__ */ m(f, { children: [
369
+ /* @__PURE__ */ m(h, {
276
370
  variant: "outline",
277
371
  size: "sm",
278
- onClick: Me,
372
+ onClick: Ye,
279
373
  children: [
280
- /* @__PURE__ */ f(ce, { className: "h-4 w-4" }),
374
+ /* @__PURE__ */ p(le, { className: "h-4 w-4" }),
281
375
  " ",
282
- B ? C("healthybowl.fieldMap.actions.redraw", "Redraw") : C("healthybowl.fieldMap.actions.draw", "Draw boundary")
376
+ L ? b("healthybowl.fieldMap.actions.redraw", "Redraw") : b("healthybowl.fieldMap.actions.draw", "Draw boundary")
283
377
  ]
284
378
  }),
285
- /* @__PURE__ */ p(m, {
379
+ /* @__PURE__ */ m(h, {
286
380
  variant: "outline",
287
381
  size: "sm",
288
- onClick: () => E.current?.click(),
382
+ onClick: () => Ae.current?.click(),
289
383
  children: [
290
- /* @__PURE__ */ f(de, { className: "h-4 w-4" }),
384
+ /* @__PURE__ */ p(pe, { className: "h-4 w-4" }),
291
385
  " ",
292
- C("healthybowl.fieldMap.actions.import", "Import GeoJSON")
386
+ b("healthybowl.fieldMap.actions.import", "Import GeoJSON")
293
387
  ]
294
388
  }),
295
- /* @__PURE__ */ p(m, {
389
+ /* @__PURE__ */ m(h, {
296
390
  variant: "outline",
297
391
  size: "sm",
298
- onClick: Oe,
299
- title: C("healthybowl.fieldMap.actions.focusField.title", "Fit map to this field"),
300
- "aria-label": C("healthybowl.fieldMap.actions.focusField.title", "Fit map to this field"),
392
+ onClick: We,
393
+ title: b("healthybowl.fieldMap.actions.focusField.title", "Fit map to this field"),
394
+ "aria-label": b("healthybowl.fieldMap.actions.focusField.title", "Fit map to this field"),
301
395
  children: [
302
- /* @__PURE__ */ f(se, { className: "h-4 w-4" }),
396
+ /* @__PURE__ */ p(ce, { className: "h-4 w-4" }),
303
397
  " ",
304
- C("healthybowl.fieldMap.actions.focusField", "Field")
398
+ b("healthybowl.fieldMap.actions.focusField", "Field")
305
399
  ]
306
400
  }),
307
- /* @__PURE__ */ p(m, {
401
+ /* @__PURE__ */ m(h, {
308
402
  variant: "outline",
309
403
  size: "sm",
310
- onClick: ke,
311
- disabled: J,
312
- title: C("healthybowl.fieldMap.actions.locateMe.title", "Go to my current location"),
313
- "aria-label": C("healthybowl.fieldMap.actions.locateMe.title", "Go to my current location"),
404
+ onClick: Ge,
405
+ disabled: Le,
406
+ title: b("healthybowl.fieldMap.actions.locateMe.title", "Go to my current location"),
407
+ "aria-label": b("healthybowl.fieldMap.actions.locateMe.title", "Go to my current location"),
314
408
  children: [
315
- /* @__PURE__ */ f(ae, { className: "h-4 w-4" }),
409
+ /* @__PURE__ */ p(oe, { className: "h-4 w-4" }),
316
410
  " ",
317
- J ? C("healthybowl.fieldMap.actions.locating", "Locating...") : C("healthybowl.fieldMap.actions.locateMe", "My location")
411
+ Le ? b("healthybowl.fieldMap.actions.locating", "Locating...") : b("healthybowl.fieldMap.actions.locateMe", "My location")
318
412
  ]
319
413
  }),
320
- B && /* @__PURE__ */ p(m, {
414
+ L && /* @__PURE__ */ m(h, {
321
415
  variant: "outline",
322
416
  size: "sm",
323
- onClick: Pe,
417
+ onClick: Ze,
324
418
  children: [
325
- /* @__PURE__ */ f(ue, { className: "h-4 w-4" }),
419
+ /* @__PURE__ */ p(fe, { className: "h-4 w-4" }),
326
420
  " ",
327
- C("healthybowl.fieldMap.actions.clear", "Clear")
421
+ b("healthybowl.fieldMap.actions.clear", "Clear")
328
422
  ]
329
423
  })
330
- ] }) : /* @__PURE__ */ p(d, { children: [
331
- /* @__PURE__ */ p(m, {
424
+ ] }) : /* @__PURE__ */ m(f, { children: [
425
+ /* @__PURE__ */ m(h, {
332
426
  variant: "default",
333
427
  size: "sm",
334
428
  onClick: $,
335
429
  children: [
336
- /* @__PURE__ */ f(ie, { className: "h-4 w-4" }),
430
+ /* @__PURE__ */ p(ae, { className: "h-4 w-4" }),
337
431
  " ",
338
- C("healthybowl.fieldMap.actions.finish", "Finish")
432
+ b("healthybowl.fieldMap.actions.finish", "Finish")
339
433
  ]
340
434
  }),
341
- /* @__PURE__ */ p(m, {
435
+ /* @__PURE__ */ m(h, {
342
436
  variant: "outline",
343
437
  size: "sm",
344
- onClick: Ne,
438
+ onClick: Xe,
345
439
  children: [
346
- /* @__PURE__ */ f(fe, { className: "h-4 w-4" }),
440
+ /* @__PURE__ */ p(d, { className: "h-4 w-4" }),
347
441
  " ",
348
- C("healthybowl.common.cancel", "Cancel")
442
+ b("healthybowl.common.cancel", "Cancel")
349
443
  ]
350
444
  }),
351
- /* @__PURE__ */ f("span", {
445
+ /* @__PURE__ */ p("span", {
352
446
  className: "text-xs text-text-secondary",
353
- children: C("healthybowl.fieldMap.draftHint", "Click the map to add corners ({{count}} placed) — click the first point or Finish to close.", { count: String(we) })
447
+ children: b("healthybowl.fieldMap.draftHint", "Click the map to add corners ({{count}} placed) — click the first point or Finish to close.", { count: String(Me) })
354
448
  })
355
- ] }), /* @__PURE__ */ p("div", {
449
+ ] }), /* @__PURE__ */ m("div", {
356
450
  className: "ml-auto flex items-center gap-3",
357
- children: [H != null && /* @__PURE__ */ f("span", {
451
+ children: [z != null && /* @__PURE__ */ p("span", {
358
452
  className: "text-xs text-text-secondary",
359
- children: C("healthybowl.fieldMap.computedArea", "Area: {{area}} {{unit}}", {
360
- area: String(H),
453
+ children: b("healthybowl.fieldMap.computedArea", "Area: {{area}} {{unit}}", {
454
+ area: String(z),
361
455
  unit: r
362
456
  })
363
- }), /* @__PURE__ */ p(m, {
457
+ }), /* @__PURE__ */ m(h, {
364
458
  variant: "default",
365
459
  size: "sm",
366
- onClick: Ie,
367
- disabled: !Te || K || R === "draw",
460
+ onClick: $e,
461
+ disabled: !Be || Fe || F === "draw",
368
462
  children: [
369
- /* @__PURE__ */ f(le, { className: "h-4 w-4" }),
463
+ /* @__PURE__ */ p(ue, { className: "h-4 w-4" }),
370
464
  " ",
371
- K ? C("healthybowl.fieldMap.actions.saving", "Saving…") : C("healthybowl.fieldMap.actions.save", "Save")
465
+ Fe ? b("healthybowl.fieldMap.actions.saving", "Saving…") : b("healthybowl.fieldMap.actions.save", "Save")
372
466
  ]
373
467
  })]
374
468
  })]
375
469
  }),
376
- /* @__PURE__ */ f("input", {
377
- ref: E,
470
+ F === "view" && /* @__PURE__ */ m("div", {
471
+ className: "mb-3 space-y-2",
472
+ children: [/* @__PURE__ */ m("form", {
473
+ className: "flex flex-col gap-2 sm:flex-row",
474
+ onSubmit: Ke,
475
+ children: [
476
+ /* @__PURE__ */ m("div", {
477
+ className: "relative min-w-0 flex-1",
478
+ children: [/* @__PURE__ */ p(de, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-secondary" }), /* @__PURE__ */ p("input", {
479
+ type: "search",
480
+ value: G,
481
+ onChange: (e) => Re(e.target.value),
482
+ disabled: P !== "ready" || K,
483
+ placeholder: b("healthybowl.fieldMap.search.placeholder", "Search village, city, region, or lat,lng..."),
484
+ "aria-label": b("healthybowl.fieldMap.search.label", "Search field map by place or coordinates"),
485
+ className: "h-9 w-full rounded-md border border-border-subtle bg-bg-surface py-2 pl-9 pr-3 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]"
486
+ })]
487
+ }),
488
+ /* @__PURE__ */ m(h, {
489
+ type: "submit",
490
+ variant: "outline",
491
+ size: "sm",
492
+ disabled: P !== "ready" || K,
493
+ children: [
494
+ /* @__PURE__ */ p(de, { className: "h-4 w-4" }),
495
+ " ",
496
+ K ? b("healthybowl.fieldMap.search.searching", "Searching...") : b("healthybowl.fieldMap.search.action", "Search")
497
+ ]
498
+ }),
499
+ q && /* @__PURE__ */ m(h, {
500
+ type: "button",
501
+ variant: "outline",
502
+ size: "sm",
503
+ onClick: Ue,
504
+ children: [
505
+ /* @__PURE__ */ p(d, { className: "h-4 w-4" }),
506
+ " ",
507
+ b("healthybowl.common.clear", "Clear")
508
+ ]
509
+ })
510
+ ]
511
+ }), q && /* @__PURE__ */ p("div", {
512
+ className: "flex flex-wrap items-center gap-2 text-xs text-text-secondary",
513
+ children: /* @__PURE__ */ m("span", {
514
+ className: "inline-flex min-w-0 items-center gap-1.5 rounded-full border border-border-subtle bg-bg-sunken/70 px-2.5 py-1",
515
+ children: [/* @__PURE__ */ p(se, { className: "h-3.5 w-3.5 shrink-0 text-success" }), /* @__PURE__ */ p("span", {
516
+ className: "truncate",
517
+ children: b("healthybowl.fieldMap.search.pendingLocation", "Unsaved field GPS: {{place}}", { place: q.label })
518
+ })]
519
+ })
520
+ })]
521
+ }),
522
+ /* @__PURE__ */ p("input", {
523
+ ref: Ae,
378
524
  type: "file",
379
525
  accept: ".json,.geojson,application/geo+json,application/json",
380
526
  className: "hidden",
381
527
  onChange: (e) => {
382
528
  let t = e.target.files?.[0];
383
- t && Fe(t), e.target.value = "";
529
+ t && Qe(t), e.target.value = "";
384
530
  }
385
531
  }),
386
- /* @__PURE__ */ p("div", {
532
+ /* @__PURE__ */ m("div", {
387
533
  className: "relative",
388
534
  children: [
389
- /* @__PURE__ */ f("div", {
390
- ref: D,
535
+ /* @__PURE__ */ p("div", {
536
+ ref: S,
391
537
  className: "h-[60vh] max-h-[520px] w-full overflow-hidden rounded-md border border-border-subtle bg-bg-sunken"
392
538
  }),
393
- L === "loading" && /* @__PURE__ */ f("div", {
539
+ P === "loading" && /* @__PURE__ */ p("div", {
394
540
  className: "pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/60 text-sm text-text-secondary",
395
- children: C("healthybowl.fieldMap.loading", "Loading map…")
541
+ children: b("healthybowl.fieldMap.loading", "Loading map…")
396
542
  }),
397
- L === "error" && /* @__PURE__ */ f("div", {
543
+ P === "error" && /* @__PURE__ */ p("div", {
398
544
  className: "pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/80 px-4 text-center text-sm text-text-secondary",
399
- children: C("healthybowl.fieldMap.error", "The map needs an internet connection and couldn’t load.")
545
+ children: b("healthybowl.fieldMap.error", "The map needs an internet connection and couldn’t load.")
400
546
  }),
401
- L === "ready" && !B && R === "view" && /* @__PURE__ */ f("div", {
547
+ P === "ready" && !L && F === "view" && /* @__PURE__ */ p("div", {
402
548
  className: "pointer-events-none absolute left-1/2 top-3 z-[400] -translate-x-1/2 rounded-full bg-bg-surface/90 px-3 py-1.5 text-xs text-text-secondary shadow-sm",
403
- children: /* @__PURE__ */ p("span", {
549
+ children: /* @__PURE__ */ m("span", {
404
550
  className: "inline-flex items-center gap-1.5",
405
551
  children: [
406
- /* @__PURE__ */ f(oe, { className: "h-3.5 w-3.5" }),
552
+ /* @__PURE__ */ p(se, { className: "h-3.5 w-3.5" }),
407
553
  " ",
408
- C("healthybowl.fieldMap.empty", "No boundary set — draw or import one.")
554
+ b("healthybowl.fieldMap.empty", "No boundary set — draw or import one.")
409
555
  ]
410
556
  })
411
557
  })
412
558
  ]
413
559
  }),
414
- /* @__PURE__ */ f("p", {
560
+ /* @__PURE__ */ p("p", {
415
561
  className: "mt-2 text-xs text-text-secondary",
416
- children: C("healthybowl.fieldMap.attribution", "Imagery © Esri, Maxar, Earthstar Geographics · overlays © OpenTopoMap / OpenStreetMap")
562
+ children: b("healthybowl.fieldMap.attribution", "Imagery © Esri, Maxar, Earthstar Geographics · overlays © OpenTopoMap / OpenStreetMap")
417
563
  }),
418
- /* @__PURE__ */ f(n, {
419
- toasts: xe,
420
- onDismiss: Se
564
+ /* @__PURE__ */ p(n, {
565
+ toasts: Oe,
566
+ onDismiss: ke
421
567
  })
422
568
  ]
423
569
  });
424
570
  };
425
571
  //#endregion
426
- export { x as FieldMap };
572
+ export { y as FieldMap };
427
573
 
428
574
  //# sourceMappingURL=FieldMap.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"FieldMap.js","names":[],"sources":["../../../src/healthybowl/components/FieldMap.tsx"],"sourcesContent":["import { type FC, useCallback, useEffect, useRef, useState } from 'react';\nimport L from 'leaflet';\nimport { gql } from '@apollo/client';\nimport { useMutation } from '@apollo/client/react';\nimport { Pencil, Trash2, Save, Upload, Check, X, MapPin, LocateFixed, MapPinned } from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\nimport { useToast } from '../hooks/useToast';\nimport { ToastContainer } from './Toast';\nimport {\n ensureLeafletCss,\n extractPolygon,\n isValidPolygon,\n polygonAreaInUnit,\n ringToPolygon,\n type GeoJsonPolygon,\n} from '../utils';\n\n// The service schema (wspace-healthybowl-svc) ships `boundary: JSON` on Field\n// and both field inputs. Until a connected-env `schema:pull` + `codegen` runs,\n// the generated hooks don't type `boundary`, so we persist it via a raw gql\n// document — mirroring the existing raw-gql pattern in useHealthyBowlData.ts.\nconst UPDATE_FIELD_BOUNDARY_DOC = gql`\n mutation UpdateHealthyBowlFieldBoundary($input: UpdateHealthyBowlFieldInput!) {\n updateHealthyBowlField(input: $input) {\n id\n area\n boundary\n location\n }\n }\n`;\n\ninterface UpdateFieldBoundaryVars {\n input: {\n id: string;\n boundary: GeoJsonPolygon | null;\n area?: number;\n context: { workspaceId: string };\n };\n}\n\ninterface FieldMapProps {\n fieldId: string;\n /** Field measurement unit — the computed area is written back in this unit. */\n unit: 'acres' | 'hectares';\n /** Approximate field centre (from Field.location); used only for the initial view. */\n center?: { lat: number; lng: number } | null;\n /** Existing boundary (Field.boundary) to render on load, if any. */\n initialBoundary?: unknown;\n /** Called after a successful save so the parent can refetch. */\n onSaved?: () => void;\n}\n\nconst ESRI_IMAGERY = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';\nconst ESRI_ATTR = 'Esri, Maxar, Earthstar Geographics';\nconst TOPO_URL = 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png';\nconst TOPO_ATTR = '© OpenTopoMap (CC-BY-SA) · © OpenStreetMap contributors';\nconst OSM_URL = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';\n\nconst BOUNDARY_STYLE: L.PathOptions = { color: '#16a34a', weight: 2, fillColor: '#16a34a', fillOpacity: 0.25 };\nconst DRAFT_STYLE: L.PathOptions = {\n color: '#f59e0b',\n weight: 2,\n dashArray: '6 4',\n fillColor: '#f59e0b',\n fillOpacity: 0.15,\n};\nconst FIELD_VIEW_ZOOM = 16;\nconst USER_VIEW_ZOOM = 17;\n\nconst isUsableCoordinate = (value?: { lat: number; lng: number } | null): value is { lat: number; lng: number } =>\n Boolean(\n value &&\n Number.isFinite(value.lat) &&\n Number.isFinite(value.lng) &&\n value.lat >= -90 &&\n value.lat <= 90 &&\n value.lng >= -180 &&\n value.lng <= 180 &&\n (value.lat !== 0 || value.lng !== 0)\n );\n\nexport const FieldMap: FC<FieldMapProps> = ({ fieldId, unit, center, initialBoundary, onSaved }) => {\n const { t } = useI18n();\n const { workspaceId } = useHealthyBowl();\n const { toasts, toast, dismiss } = useToast();\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<L.Map | null>(null);\n const boundaryLayerRef = useRef<L.GeoJSON | null>(null);\n const draftPolyRef = useRef<L.Polygon | null>(null);\n const userLocationMarkerRef = useRef<L.CircleMarker | null>(null);\n const userAccuracyCircleRef = useRef<L.Circle | null>(null);\n const vertexMarkersRef = useRef<L.CircleMarker[]>([]);\n const draftVerticesRef = useRef<L.LatLng[]>([]);\n const currentBoundaryRef = useRef<GeoJsonPolygon | null>(null);\n const modeRef = useRef<'view' | 'draw'>('view');\n\n const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');\n const [mode, setMode] = useState<'view' | 'draw'>('view');\n const [hasBoundary, setHasBoundary] = useState(false);\n const [area, setArea] = useState<number | null>(null);\n const [vertexCount, setVertexCount] = useState(0);\n const [dirty, setDirty] = useState(false);\n const [saving, setSaving] = useState(false);\n const [locating, setLocating] = useState(false);\n\n const [updateBoundary] = useMutation<{ updateHealthyBowlField: { id: string } }, UpdateFieldBoundaryVars>(\n UPDATE_FIELD_BOUNDARY_DOC\n );\n\n // ── Render helpers ──────────────────────────────────────────────────────────\n const clearDraft = useCallback(() => {\n const map = mapRef.current;\n if (draftPolyRef.current && map) map.removeLayer(draftPolyRef.current);\n draftPolyRef.current = null;\n vertexMarkersRef.current.forEach((m) => map?.removeLayer(m));\n vertexMarkersRef.current = [];\n draftVerticesRef.current = [];\n setVertexCount(0);\n }, []);\n\n const showBoundary = useCallback(\n (polygon: GeoJsonPolygon, fit: boolean) => {\n const map = mapRef.current;\n if (!map) return;\n if (boundaryLayerRef.current) map.removeLayer(boundaryLayerRef.current);\n const layer = L.geoJSON(polygon, { style: () => BOUNDARY_STYLE }).addTo(map);\n boundaryLayerRef.current = layer;\n currentBoundaryRef.current = polygon;\n setHasBoundary(true);\n setArea(polygonAreaInUnit(polygon, unit));\n if (fit) {\n try {\n map.fitBounds(layer.getBounds(), { padding: [24, 24], maxZoom: 18 });\n } catch {\n /* empty bounds — ignore */\n }\n }\n },\n [unit]\n );\n\n const removeBoundary = useCallback(() => {\n const map = mapRef.current;\n if (boundaryLayerRef.current && map) map.removeLayer(boundaryLayerRef.current);\n boundaryLayerRef.current = null;\n currentBoundaryRef.current = null;\n setHasBoundary(false);\n setArea(null);\n }, []);\n\n const clearUserLocation = useCallback(() => {\n const map = mapRef.current;\n if (userLocationMarkerRef.current && map) map.removeLayer(userLocationMarkerRef.current);\n if (userAccuracyCircleRef.current && map) map.removeLayer(userAccuracyCircleRef.current);\n userLocationMarkerRef.current = null;\n userAccuracyCircleRef.current = null;\n }, []);\n\n const focusField = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n const boundaryLayer = boundaryLayerRef.current;\n if (boundaryLayer) {\n try {\n const bounds = boundaryLayer.getBounds();\n if (bounds.isValid()) {\n map.fitBounds(bounds, { padding: [24, 24], maxZoom: 18 });\n return;\n }\n } catch {\n /* empty bounds — fall back to field location */\n }\n }\n if (isUsableCoordinate(center)) {\n map.flyTo([center.lat, center.lng], FIELD_VIEW_ZOOM, { duration: 0.6 });\n return;\n }\n toast({\n title: t('healthybowl.fieldMap.toast.noFieldLocation.title', 'No field location set'),\n description: t(\n 'healthybowl.fieldMap.toast.noFieldLocation.description',\n 'Draw a boundary or save GPS coordinates for this field first.'\n ),\n variant: 'warning',\n });\n }, [center, t, toast]);\n\n const handleLocateMe = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n if (typeof navigator === 'undefined' || !navigator.geolocation) {\n toast({\n title: t('healthybowl.fieldMap.toast.locationUnsupported.title', 'Location unavailable'),\n description: t(\n 'healthybowl.fieldMap.toast.locationUnsupported.description',\n 'This browser does not support device location.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n setLocating(true);\n navigator.geolocation.getCurrentPosition(\n (position) => {\n const latlng: L.LatLngExpression = [position.coords.latitude, position.coords.longitude];\n clearUserLocation();\n userAccuracyCircleRef.current = L.circle(latlng, {\n radius: Math.max(10, position.coords.accuracy || 0),\n color: '#2563eb',\n fillColor: '#3b82f6',\n fillOpacity: 0.12,\n opacity: 0.45,\n weight: 1,\n }).addTo(map);\n userLocationMarkerRef.current = L.circleMarker(latlng, {\n radius: 7,\n color: '#ffffff',\n weight: 2,\n fillColor: '#2563eb',\n fillOpacity: 1,\n }).addTo(map);\n map.flyTo(latlng, Math.max(map.getZoom(), USER_VIEW_ZOOM), { duration: 0.75 });\n setLocating(false);\n },\n (error) => {\n const blocked = error.code === error.PERMISSION_DENIED;\n toast({\n title: blocked\n ? t('healthybowl.fieldMap.toast.locationBlocked.title', 'Location blocked')\n : t('healthybowl.fieldMap.toast.locationFailed.title', 'Could not get location'),\n description: blocked\n ? t(\n 'healthybowl.fieldMap.toast.locationBlocked.description',\n 'Allow location access in the browser, then try again.'\n )\n : t(\n 'healthybowl.fieldMap.toast.locationFailed.description',\n 'Make sure GPS is enabled and the page is open over HTTPS.'\n ),\n variant: 'warning',\n });\n setLocating(false);\n },\n { enableHighAccuracy: true, timeout: 12000, maximumAge: 60000 }\n );\n }, [clearUserLocation, t, toast]);\n\n // ── Draw mode ───────────────────────────────────────────────────────────────\n const redrawDraft = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n const pts = draftVerticesRef.current;\n if (draftPolyRef.current) map.removeLayer(draftPolyRef.current);\n if (pts.length >= 2) {\n draftPolyRef.current = L.polygon(pts, DRAFT_STYLE).addTo(map);\n } else {\n draftPolyRef.current = null;\n }\n }, []);\n\n const finishDraw = useCallback(() => {\n if (draftVerticesRef.current.length < 3) {\n toast({\n title: t('healthybowl.fieldMap.toast.needPoints.title', 'Need at least 3 points'),\n description: t(\n 'healthybowl.fieldMap.toast.needPoints.description',\n 'Click on the map to add more boundary corners.'\n ),\n variant: 'warning',\n });\n return;\n }\n const polygon = ringToPolygon(draftVerticesRef.current.map((p) => ({ lat: p.lat, lng: p.lng })));\n clearDraft();\n modeRef.current = 'view';\n setMode('view');\n if (polygon) {\n showBoundary(polygon, false);\n setDirty(true);\n }\n }, [clearDraft, showBoundary, t, toast]);\n\n const handleMapClick = useCallback(\n (e: L.LeafletMouseEvent) => {\n if (modeRef.current !== 'draw') return;\n const map = mapRef.current;\n if (!map) return;\n draftVerticesRef.current.push(e.latlng);\n const isFirst = draftVerticesRef.current.length === 1;\n const marker = L.circleMarker(e.latlng, {\n radius: isFirst ? 7 : 5,\n color: '#fff',\n weight: 2,\n fillColor: isFirst ? '#16a34a' : '#f59e0b',\n fillOpacity: 1,\n }).addTo(map);\n if (isFirst) {\n // Clicking the first vertex again closes the ring.\n marker.on('click', (ev) => {\n L.DomEvent.stopPropagation(ev);\n finishDraw();\n });\n }\n vertexMarkersRef.current.push(marker);\n setVertexCount(draftVerticesRef.current.length);\n redrawDraft();\n },\n [finishDraw, redrawDraft]\n );\n\n const startDraw = useCallback(() => {\n removeBoundary();\n clearDraft();\n modeRef.current = 'draw';\n setMode('draw');\n setDirty(true);\n }, [clearDraft, removeBoundary]);\n\n const cancelDraw = useCallback(() => {\n clearDraft();\n modeRef.current = 'view';\n setMode('view');\n }, [clearDraft]);\n\n const handleClear = useCallback(() => {\n clearDraft();\n removeBoundary();\n modeRef.current = 'view';\n setMode('view');\n setDirty(true);\n }, [clearDraft, removeBoundary]);\n\n // ── Import ──────────────────────────────────────────────────────────────────\n const handleImportFile = useCallback(\n async (file: File) => {\n try {\n const text = await file.text();\n const parsed: unknown = JSON.parse(text);\n if (!isValidPolygon(parsed)) {\n toast({\n title: t('healthybowl.fieldMap.toast.importInvalid.title', 'No polygon found'),\n description: t(\n 'healthybowl.fieldMap.toast.importInvalid.description',\n 'The file must contain a GeoJSON Polygon (Feature, FeatureCollection or geometry).'\n ),\n variant: 'error',\n });\n return;\n }\n const polygon = extractPolygon(parsed) as GeoJsonPolygon;\n clearDraft();\n modeRef.current = 'view';\n setMode('view');\n showBoundary(polygon, true);\n setDirty(true);\n toast({\n title: t('healthybowl.fieldMap.toast.imported.title', 'Boundary imported'),\n description: t(\n 'healthybowl.fieldMap.toast.imported.description',\n 'Review it on the map, then Save to persist.'\n ),\n variant: 'success',\n });\n } catch {\n toast({\n title: t('healthybowl.fieldMap.toast.importFailed.title', 'Could not read file'),\n description: t(\n 'healthybowl.fieldMap.toast.importFailed.description',\n 'Make sure it is a valid GeoJSON (.json / .geojson) file.'\n ),\n variant: 'error',\n });\n }\n },\n [clearDraft, showBoundary, t, toast]\n );\n\n // ── Save ────────────────────────────────────────────────────────────────────\n const handleSave = useCallback(async () => {\n setSaving(true);\n try {\n const polygon = currentBoundaryRef.current;\n const nextArea = polygon ? polygonAreaInUnit(polygon, unit) : undefined;\n await updateBoundary({\n variables: {\n input: {\n id: fieldId,\n boundary: polygon,\n ...(nextArea != null ? { area: nextArea } : {}),\n context: { workspaceId },\n },\n },\n });\n setDirty(false);\n onSaved?.();\n toast({\n title: t('healthybowl.fieldMap.toast.saved.title', 'Boundary saved'),\n description: polygon\n ? t('healthybowl.fieldMap.toast.saved.description', 'Field area updated to {{area}} {{unit}}.', {\n area: String(nextArea ?? ''),\n unit,\n })\n : t('healthybowl.fieldMap.toast.savedCleared.description', 'Boundary removed from this field.'),\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.fieldMap.toast.saveFailed.title', 'Save failed'),\n description: String(err),\n variant: 'error',\n });\n } finally {\n setSaving(false);\n }\n }, [fieldId, onSaved, t, toast, unit, updateBoundary, workspaceId]);\n\n // ── Map init (once) ──────────────────────────────────────────────────────────\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return undefined;\n ensureLeafletCss();\n\n const satellite = L.tileLayer(ESRI_IMAGERY, { attribution: ESRI_ATTR, maxZoom: 19 });\n const terrain = L.tileLayer(TOPO_URL, { attribution: TOPO_ATTR, maxZoom: 17 });\n // TODO soil WMS URL: no reliable keyless soil WMS is confidently known, so the\n // \"Soil\" overlay is wired to a clearly-labelled OpenTopoMap placeholder for now.\n // Swap this for an OpenLandMap / SoilGrids WMS once a stable endpoint is confirmed.\n const soilPlaceholder = L.tileLayer(TOPO_URL, { attribution: TOPO_ATTR, maxZoom: 17, opacity: 0.6 });\n const streets = L.tileLayer(OSM_URL, { attribution: '© OpenStreetMap contributors', maxZoom: 19 });\n\n const map = L.map(el, { center: [20, 0], zoom: 2, scrollWheelZoom: true, layers: [satellite] });\n mapRef.current = map;\n\n L.control\n .layers(\n { [t('healthybowl.fieldMap.layers.satellite', 'Satellite (Esri)')]: satellite },\n {\n [t('healthybowl.fieldMap.layers.terrain', 'Terrain (OpenTopoMap)')]: terrain,\n [t('healthybowl.fieldMap.layers.soil', 'Soil (placeholder)')]: soilPlaceholder,\n [t('healthybowl.fieldMap.layers.streets', 'Streets (OSM)')]: streets,\n },\n { collapsed: false }\n )\n .addTo(map);\n\n map.on('click', handleMapClick);\n\n // Initial view: existing boundary → fit; else field centre; else world.\n const existing = extractPolygon(initialBoundary);\n if (existing && isValidPolygon(existing)) {\n showBoundary(existing, true);\n } else if (isUsableCoordinate(center)) {\n map.setView([center.lat, center.lng], FIELD_VIEW_ZOOM);\n }\n\n setStatus('ready');\n window.setTimeout(() => map.invalidateSize(), 80);\n\n return () => {\n map.off('click', handleMapClick);\n map.remove();\n mapRef.current = null;\n boundaryLayerRef.current = null;\n draftPolyRef.current = null;\n userLocationMarkerRef.current = null;\n userAccuracyCircleRef.current = null;\n vertexMarkersRef.current = [];\n draftVerticesRef.current = [];\n currentBoundaryRef.current = null;\n };\n // Init once; handlers are stable via useCallback and read the latest state through refs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div className=\"relative\">\n <div className=\"mb-3 flex flex-wrap items-center gap-2\">\n {mode === 'view' ? (\n <>\n <Button variant=\"outline\" size=\"sm\" onClick={startDraw}>\n <Pencil className=\"h-4 w-4\" />{' '}\n {hasBoundary\n ? t('healthybowl.fieldMap.actions.redraw', 'Redraw')\n : t('healthybowl.fieldMap.actions.draw', 'Draw boundary')}\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={() => fileInputRef.current?.click()}>\n <Upload className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.import', 'Import GeoJSON')}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={focusField}\n title={t('healthybowl.fieldMap.actions.focusField.title', 'Fit map to this field')}\n aria-label={t('healthybowl.fieldMap.actions.focusField.title', 'Fit map to this field')}\n >\n <MapPinned className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.focusField', 'Field')}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleLocateMe}\n disabled={locating}\n title={t('healthybowl.fieldMap.actions.locateMe.title', 'Go to my current location')}\n aria-label={t('healthybowl.fieldMap.actions.locateMe.title', 'Go to my current location')}\n >\n <LocateFixed className=\"h-4 w-4\" />{' '}\n {locating\n ? t('healthybowl.fieldMap.actions.locating', 'Locating...')\n : t('healthybowl.fieldMap.actions.locateMe', 'My location')}\n </Button>\n {hasBoundary && (\n <Button variant=\"outline\" size=\"sm\" onClick={handleClear}>\n <Trash2 className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.clear', 'Clear')}\n </Button>\n )}\n </>\n ) : (\n <>\n <Button variant=\"default\" size=\"sm\" onClick={finishDraw}>\n <Check className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.finish', 'Finish')}\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={cancelDraw}>\n <X className=\"h-4 w-4\" /> {t('healthybowl.common.cancel', 'Cancel')}\n </Button>\n <span className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.fieldMap.draftHint',\n 'Click the map to add corners ({{count}} placed) — click the first point or Finish to close.',\n {\n count: String(vertexCount),\n }\n )}\n </span>\n </>\n )}\n <div className=\"ml-auto flex items-center gap-3\">\n {area != null && (\n <span className=\"text-xs text-text-secondary\">\n {t('healthybowl.fieldMap.computedArea', 'Area: {{area}} {{unit}}', { area: String(area), unit })}\n </span>\n )}\n <Button variant=\"default\" size=\"sm\" onClick={handleSave} disabled={!dirty || saving || mode === 'draw'}>\n <Save className=\"h-4 w-4\" />{' '}\n {saving\n ? t('healthybowl.fieldMap.actions.saving', 'Saving…')\n : t('healthybowl.fieldMap.actions.save', 'Save')}\n </Button>\n </div>\n </div>\n\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".json,.geojson,application/geo+json,application/json\"\n className=\"hidden\"\n onChange={(e) => {\n const file = e.target.files?.[0];\n if (file) void handleImportFile(file);\n e.target.value = '';\n }}\n />\n\n <div className=\"relative\">\n <div\n ref={containerRef}\n className=\"h-[60vh] max-h-[520px] w-full overflow-hidden rounded-md border border-border-subtle bg-bg-sunken\"\n />\n {status === 'loading' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/60 text-sm text-text-secondary\">\n {t('healthybowl.fieldMap.loading', 'Loading map…')}\n </div>\n )}\n {status === 'error' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/80 px-4 text-center text-sm text-text-secondary\">\n {t('healthybowl.fieldMap.error', 'The map needs an internet connection and couldn’t load.')}\n </div>\n )}\n {status === 'ready' && !hasBoundary && mode === 'view' && (\n <div className=\"pointer-events-none absolute left-1/2 top-3 z-[400] -translate-x-1/2 rounded-full bg-bg-surface/90 px-3 py-1.5 text-xs text-text-secondary shadow-sm\">\n <span className=\"inline-flex items-center gap-1.5\">\n <MapPin className=\"h-3.5 w-3.5\" />{' '}\n {t('healthybowl.fieldMap.empty', 'No boundary set — draw or import one.')}\n </span>\n </div>\n )}\n </div>\n\n <p className=\"mt-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.fieldMap.attribution',\n 'Imagery © Esri, Maxar, Earthstar Geographics · overlays © OpenTopoMap / OpenStreetMap'\n )}\n </p>\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;mCAuBM,KAA4B,CAAG;;;;;;;;;GAgC/B,KAAe,iGACf,KAAY,sCACZ,IAAW,oDACX,IAAY,2DACZ,KAAU,sDAEV,KAAgC;CAAE,OAAO;CAAW,QAAQ;CAAG,WAAW;CAAW,aAAa;CAAM,EACxG,KAA6B;CACjC,OAAO;CACP,QAAQ;CAC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Y,CAAA;OAAC;OAC5B,IACG,EAAE,uCAAuC,UAAU,GACnD,EAAE,qCAAqC,OAAO;OAC3C;QACL;OACF;;GAEN,kBAAC,SAAD;IACE,KAAK;IACL,MAAK;IACL,QAAO;IACP,WAAU;IACV,WAAW,MAAM;KACf,IAAM,IAAO,EAAE,OAAO,QAAQ;AAE9B,KADI,KAAW,GAAiB,EAAK,EACrC,EAAE,OAAO,QAAQ;;IAEnB,CAAA;GAEF,kBAAC,OAAD;IAAK,WAAU;cAAf;KACE,kBAAC,OAAD;MACE,KAAK;MACL,WAAU;MACV,CAAA;KACD,MAAW,aACV,kBAAC,OAAD;MAAK,WAAU;gBACZ,EAAE,gCAAgC,eAAe;MAC9C,CAAA;KAEP,MAAW,WACV,kBAAC,OAAD;MAAK,WAAU;gBACZ,EAAE,8BAA8B,0DAA0D;MACvF,CAAA;KAEP,MAAW,WAAW,CAAC,KAAe,MAAS,UAC9C,kBAAC,OAAD;MAAK,WAAU;gBACb,kBAAC,QAAD;OAAM,WAAU;iBAAhB;QACE,kBAAC,IAAD,EAAQ,WAAU,eAAgB,CAAA;QAAC;QAClC,EAAE,8BAA8B,wCAAwC;QACpE;;MACH,CAAA;KAEJ;;GAEN,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,oCACA,wFACD;IACC,CAAA;GAEJ,kBAAC,GAAD;IAAwB;IAAQ,WAAW;IAAW,CAAA;GAClD"}
1
+ {"version":3,"file":"FieldMap.js","names":[],"sources":["../../../src/healthybowl/components/FieldMap.tsx"],"sourcesContent":["import { type FC, type FormEvent, useCallback, useEffect, useRef, useState } from 'react';\nimport L from 'leaflet';\nimport { gql } from '@apollo/client';\nimport { useMutation } from '@apollo/client/react';\nimport { Pencil, Trash2, Save, Upload, Check, X, MapPin, LocateFixed, MapPinned, Search } from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\nimport { useToast } from '../hooks/useToast';\nimport { ToastContainer } from './Toast';\nimport { geocodePlace } from '../utils/geocode';\nimport {\n ensureLeafletCss,\n extractPolygon,\n isValidPolygon,\n polygonAreaInUnit,\n ringToPolygon,\n type GeoJsonPolygon,\n} from '../utils';\n\n// The service schema (wspace-healthybowl-svc) ships `boundary: JSON` on Field\n// and both field inputs. Until a connected-env `schema:pull` + `codegen` runs,\n// the generated hooks don't type `boundary`, so we persist it via a raw gql\n// document — mirroring the existing raw-gql pattern in useHealthyBowlData.ts.\nconst UPDATE_FIELD_BOUNDARY_DOC = gql`\n mutation UpdateHealthyBowlFieldBoundary($input: UpdateHealthyBowlFieldInput!) {\n updateHealthyBowlField(input: $input) {\n id\n area\n boundary\n location\n }\n }\n`;\n\ninterface UpdateFieldBoundaryVars {\n input: {\n id: string;\n boundary: GeoJsonPolygon | null;\n area?: number;\n location?: { lat: number; lng: number };\n context: { workspaceId: string };\n };\n}\n\ninterface PendingFieldLocation {\n lat: number;\n lng: number;\n label: string;\n}\n\ninterface FieldMapProps {\n fieldId: string;\n /** Field measurement unit — the computed area is written back in this unit. */\n unit: 'acres' | 'hectares';\n /** Approximate field centre (from Field.location); used only for the initial view. */\n center?: { lat: number; lng: number } | null;\n /** Existing boundary (Field.boundary) to render on load, if any. */\n initialBoundary?: unknown;\n /** Called after a successful save so the parent can refetch. */\n onSaved?: () => void;\n}\n\nconst ESRI_IMAGERY = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';\nconst ESRI_ATTR = 'Esri, Maxar, Earthstar Geographics';\nconst TOPO_URL = 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png';\nconst TOPO_ATTR = '© OpenTopoMap (CC-BY-SA) · © OpenStreetMap contributors';\nconst OSM_URL = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';\n\nconst BOUNDARY_STYLE: L.PathOptions = { color: '#16a34a', weight: 2, fillColor: '#16a34a', fillOpacity: 0.25 };\nconst DRAFT_STYLE: L.PathOptions = {\n color: '#f59e0b',\n weight: 2,\n dashArray: '6 4',\n fillColor: '#f59e0b',\n fillOpacity: 0.15,\n};\nconst FIELD_VIEW_ZOOM = 16;\nconst USER_VIEW_ZOOM = 17;\n\nconst isUsableCoordinate = (value?: { lat: number; lng: number } | null): value is { lat: number; lng: number } =>\n Boolean(\n value &&\n Number.isFinite(value.lat) &&\n Number.isFinite(value.lng) &&\n value.lat >= -90 &&\n value.lat <= 90 &&\n value.lng >= -180 &&\n value.lng <= 180 &&\n (value.lat !== 0 || value.lng !== 0)\n );\n\nconst parseCoordinateSearch = (query: string): PendingFieldLocation | null => {\n const match = query.trim().match(/^(-?\\d+(?:\\.\\d+)?)\\s*,\\s*(-?\\d+(?:\\.\\d+)?)$/);\n if (!match) return null;\n const lat = Number(match[1]);\n const lng = Number(match[2]);\n if (!isUsableCoordinate({ lat, lng })) return null;\n return { lat, lng, label: `${lat.toFixed(6)}, ${lng.toFixed(6)}` };\n};\n\nexport const FieldMap: FC<FieldMapProps> = ({ fieldId, unit, center, initialBoundary, onSaved }) => {\n const { t } = useI18n();\n const { workspaceId } = useHealthyBowl();\n const { toasts, toast, dismiss } = useToast();\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<L.Map | null>(null);\n const boundaryLayerRef = useRef<L.GeoJSON | null>(null);\n const draftPolyRef = useRef<L.Polygon | null>(null);\n const userLocationMarkerRef = useRef<L.CircleMarker | null>(null);\n const userAccuracyCircleRef = useRef<L.Circle | null>(null);\n const fieldLocationMarkerRef = useRef<L.CircleMarker | null>(null);\n const savedCenterRef = useRef<{ lat: number; lng: number } | null>(center ?? null);\n const vertexMarkersRef = useRef<L.CircleMarker[]>([]);\n const draftVerticesRef = useRef<L.LatLng[]>([]);\n const currentBoundaryRef = useRef<GeoJsonPolygon | null>(null);\n const modeRef = useRef<'view' | 'draw'>('view');\n\n const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');\n const [mode, setMode] = useState<'view' | 'draw'>('view');\n const [hasBoundary, setHasBoundary] = useState(false);\n const [area, setArea] = useState<number | null>(null);\n const [vertexCount, setVertexCount] = useState(0);\n const [boundaryDirty, setBoundaryDirty] = useState(false);\n const [locationDirty, setLocationDirty] = useState(false);\n const [saving, setSaving] = useState(false);\n const [locating, setLocating] = useState(false);\n const [searchQuery, setSearchQuery] = useState('');\n const [searching, setSearching] = useState(false);\n const [pendingFieldLocation, setPendingFieldLocation] = useState<PendingFieldLocation | null>(null);\n const dirty = boundaryDirty || locationDirty;\n\n const [updateBoundary] = useMutation<{ updateHealthyBowlField: { id: string } }, UpdateFieldBoundaryVars>(\n UPDATE_FIELD_BOUNDARY_DOC\n );\n\n useEffect(() => {\n savedCenterRef.current = center ?? null;\n }, [center]);\n\n // ── Render helpers ──────────────────────────────────────────────────────────\n const clearDraft = useCallback(() => {\n const map = mapRef.current;\n if (draftPolyRef.current && map) map.removeLayer(draftPolyRef.current);\n draftPolyRef.current = null;\n vertexMarkersRef.current.forEach((m) => map?.removeLayer(m));\n vertexMarkersRef.current = [];\n draftVerticesRef.current = [];\n setVertexCount(0);\n }, []);\n\n const showBoundary = useCallback(\n (polygon: GeoJsonPolygon, fit: boolean) => {\n const map = mapRef.current;\n if (!map) return;\n if (boundaryLayerRef.current) map.removeLayer(boundaryLayerRef.current);\n const layer = L.geoJSON(polygon, { style: () => BOUNDARY_STYLE }).addTo(map);\n boundaryLayerRef.current = layer;\n currentBoundaryRef.current = polygon;\n setHasBoundary(true);\n setArea(polygonAreaInUnit(polygon, unit));\n if (fit) {\n try {\n map.fitBounds(layer.getBounds(), { padding: [24, 24], maxZoom: 18 });\n } catch {\n /* empty bounds — ignore */\n }\n }\n },\n [unit]\n );\n\n const removeBoundary = useCallback(() => {\n const map = mapRef.current;\n if (boundaryLayerRef.current && map) map.removeLayer(boundaryLayerRef.current);\n boundaryLayerRef.current = null;\n currentBoundaryRef.current = null;\n setHasBoundary(false);\n setArea(null);\n }, []);\n\n const clearUserLocation = useCallback(() => {\n const map = mapRef.current;\n if (userLocationMarkerRef.current && map) map.removeLayer(userLocationMarkerRef.current);\n if (userAccuracyCircleRef.current && map) map.removeLayer(userAccuracyCircleRef.current);\n userLocationMarkerRef.current = null;\n userAccuracyCircleRef.current = null;\n }, []);\n\n const clearFieldLocationCandidate = useCallback(() => {\n const map = mapRef.current;\n if (fieldLocationMarkerRef.current && map) map.removeLayer(fieldLocationMarkerRef.current);\n fieldLocationMarkerRef.current = null;\n setPendingFieldLocation(null);\n setLocationDirty(false);\n }, []);\n\n const showFieldLocationCandidate = useCallback((candidate: PendingFieldLocation) => {\n const map = mapRef.current;\n if (!map) return;\n if (fieldLocationMarkerRef.current) map.removeLayer(fieldLocationMarkerRef.current);\n\n const latlng: L.LatLngExpression = [candidate.lat, candidate.lng];\n const popupEl = document.createElement('span');\n popupEl.textContent = candidate.label;\n fieldLocationMarkerRef.current = L.circleMarker(latlng, {\n radius: 8,\n color: '#ffffff',\n weight: 2,\n fillColor: '#16a34a',\n fillOpacity: 1,\n })\n .addTo(map)\n .bindPopup(popupEl)\n .openPopup();\n map.flyTo(latlng, Math.max(map.getZoom(), USER_VIEW_ZOOM), { duration: 0.75 });\n setPendingFieldLocation(candidate);\n setLocationDirty(true);\n }, []);\n\n const focusField = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n const boundaryLayer = boundaryLayerRef.current;\n if (boundaryLayer) {\n try {\n const bounds = boundaryLayer.getBounds();\n if (bounds.isValid()) {\n map.fitBounds(bounds, { padding: [24, 24], maxZoom: 18 });\n return;\n }\n } catch {\n /* empty bounds — fall back to field location */\n }\n }\n const savedCenter = savedCenterRef.current;\n if (isUsableCoordinate(savedCenter)) {\n map.flyTo([savedCenter.lat, savedCenter.lng], FIELD_VIEW_ZOOM, { duration: 0.6 });\n return;\n }\n toast({\n title: t('healthybowl.fieldMap.toast.noFieldLocation.title', 'No field location set'),\n description: t(\n 'healthybowl.fieldMap.toast.noFieldLocation.description',\n 'Draw a boundary or save GPS coordinates for this field first.'\n ),\n variant: 'warning',\n });\n }, [t, toast]);\n\n const handleLocateMe = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n if (typeof navigator === 'undefined' || !navigator.geolocation) {\n toast({\n title: t('healthybowl.fieldMap.toast.locationUnsupported.title', 'Location unavailable'),\n description: t(\n 'healthybowl.fieldMap.toast.locationUnsupported.description',\n 'This browser does not support device location.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n setLocating(true);\n navigator.geolocation.getCurrentPosition(\n (position) => {\n const latlng: L.LatLngExpression = [position.coords.latitude, position.coords.longitude];\n clearUserLocation();\n userAccuracyCircleRef.current = L.circle(latlng, {\n radius: Math.max(10, position.coords.accuracy || 0),\n color: '#2563eb',\n fillColor: '#3b82f6',\n fillOpacity: 0.12,\n opacity: 0.45,\n weight: 1,\n }).addTo(map);\n userLocationMarkerRef.current = L.circleMarker(latlng, {\n radius: 7,\n color: '#ffffff',\n weight: 2,\n fillColor: '#2563eb',\n fillOpacity: 1,\n }).addTo(map);\n map.flyTo(latlng, Math.max(map.getZoom(), USER_VIEW_ZOOM), { duration: 0.75 });\n showFieldLocationCandidate({\n lat: position.coords.latitude,\n lng: position.coords.longitude,\n label: t('healthybowl.fieldMap.location.currentLabel', 'My current location'),\n });\n setLocating(false);\n toast({\n title: t('healthybowl.fieldMap.toast.locationReady.title', 'Location ready'),\n description: t(\n 'healthybowl.fieldMap.toast.locationReady.description',\n 'Save to store this as the field GPS location.'\n ),\n variant: 'success',\n });\n },\n (error) => {\n const blocked = error.code === error.PERMISSION_DENIED;\n toast({\n title: blocked\n ? t('healthybowl.fieldMap.toast.locationBlocked.title', 'Location blocked')\n : t('healthybowl.fieldMap.toast.locationFailed.title', 'Could not get location'),\n description: blocked\n ? t(\n 'healthybowl.fieldMap.toast.locationBlocked.description',\n 'Allow location access in the browser, then try again.'\n )\n : t(\n 'healthybowl.fieldMap.toast.locationFailed.description',\n 'Make sure GPS is enabled and the page is open over HTTPS.'\n ),\n variant: 'warning',\n });\n setLocating(false);\n },\n { enableHighAccuracy: true, timeout: 12000, maximumAge: 60000 }\n );\n }, [clearUserLocation, showFieldLocationCandidate, t, toast]);\n\n const handleSearchPlace = useCallback(\n async (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const place = searchQuery.trim();\n if (!place) {\n toast({\n title: t('healthybowl.fieldMap.toast.searchRequired.title', 'Place required'),\n description: t(\n 'healthybowl.fieldMap.toast.searchRequired.description',\n 'Enter a village, city, region, or coordinates.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n const coordinateCandidate = parseCoordinateSearch(place);\n if (coordinateCandidate) {\n showFieldLocationCandidate(coordinateCandidate);\n return;\n }\n\n setSearching(true);\n try {\n const hit = await geocodePlace(place);\n if (!hit) {\n toast({\n title: t('healthybowl.fieldMap.toast.searchNotFound.title', 'Place not found'),\n description: t(\n 'healthybowl.fieldMap.toast.searchNotFound.description',\n 'Try a more specific location, such as village, district, and state.'\n ),\n variant: 'warning',\n });\n return;\n }\n\n const label = [hit.name, hit.admin1, hit.country].filter(Boolean).join(', ') || place;\n showFieldLocationCandidate({ lat: hit.latitude, lng: hit.longitude, label });\n } catch (err) {\n toast({\n title: t('healthybowl.fieldMap.toast.searchFailed.title', 'Search failed'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setSearching(false);\n }\n },\n [searchQuery, showFieldLocationCandidate, t, toast]\n );\n\n // ── Draw mode ───────────────────────────────────────────────────────────────\n const redrawDraft = useCallback(() => {\n const map = mapRef.current;\n if (!map) return;\n const pts = draftVerticesRef.current;\n if (draftPolyRef.current) map.removeLayer(draftPolyRef.current);\n if (pts.length >= 2) {\n draftPolyRef.current = L.polygon(pts, DRAFT_STYLE).addTo(map);\n } else {\n draftPolyRef.current = null;\n }\n }, []);\n\n const finishDraw = useCallback(() => {\n if (draftVerticesRef.current.length < 3) {\n toast({\n title: t('healthybowl.fieldMap.toast.needPoints.title', 'Need at least 3 points'),\n description: t(\n 'healthybowl.fieldMap.toast.needPoints.description',\n 'Click on the map to add more boundary corners.'\n ),\n variant: 'warning',\n });\n return;\n }\n const polygon = ringToPolygon(draftVerticesRef.current.map((p) => ({ lat: p.lat, lng: p.lng })));\n clearDraft();\n modeRef.current = 'view';\n setMode('view');\n if (polygon) {\n showBoundary(polygon, false);\n setBoundaryDirty(true);\n }\n }, [clearDraft, showBoundary, t, toast]);\n\n const handleMapClick = useCallback(\n (e: L.LeafletMouseEvent) => {\n if (modeRef.current !== 'draw') return;\n const map = mapRef.current;\n if (!map) return;\n draftVerticesRef.current.push(e.latlng);\n const isFirst = draftVerticesRef.current.length === 1;\n const marker = L.circleMarker(e.latlng, {\n radius: isFirst ? 7 : 5,\n color: '#fff',\n weight: 2,\n fillColor: isFirst ? '#16a34a' : '#f59e0b',\n fillOpacity: 1,\n }).addTo(map);\n if (isFirst) {\n // Clicking the first vertex again closes the ring.\n marker.on('click', (ev) => {\n L.DomEvent.stopPropagation(ev);\n finishDraw();\n });\n }\n vertexMarkersRef.current.push(marker);\n setVertexCount(draftVerticesRef.current.length);\n redrawDraft();\n },\n [finishDraw, redrawDraft]\n );\n\n const startDraw = useCallback(() => {\n removeBoundary();\n clearDraft();\n modeRef.current = 'draw';\n setMode('draw');\n setBoundaryDirty(true);\n }, [clearDraft, removeBoundary]);\n\n const cancelDraw = useCallback(() => {\n clearDraft();\n modeRef.current = 'view';\n setMode('view');\n }, [clearDraft]);\n\n const handleClear = useCallback(() => {\n clearDraft();\n removeBoundary();\n modeRef.current = 'view';\n setMode('view');\n setBoundaryDirty(true);\n }, [clearDraft, removeBoundary]);\n\n // ── Import ──────────────────────────────────────────────────────────────────\n const handleImportFile = useCallback(\n async (file: File) => {\n try {\n const text = await file.text();\n const parsed: unknown = JSON.parse(text);\n if (!isValidPolygon(parsed)) {\n toast({\n title: t('healthybowl.fieldMap.toast.importInvalid.title', 'No polygon found'),\n description: t(\n 'healthybowl.fieldMap.toast.importInvalid.description',\n 'The file must contain a GeoJSON Polygon (Feature, FeatureCollection or geometry).'\n ),\n variant: 'error',\n });\n return;\n }\n const polygon = extractPolygon(parsed) as GeoJsonPolygon;\n clearDraft();\n modeRef.current = 'view';\n setMode('view');\n showBoundary(polygon, true);\n setBoundaryDirty(true);\n toast({\n title: t('healthybowl.fieldMap.toast.imported.title', 'Boundary imported'),\n description: t(\n 'healthybowl.fieldMap.toast.imported.description',\n 'Review it on the map, then Save to persist.'\n ),\n variant: 'success',\n });\n } catch {\n toast({\n title: t('healthybowl.fieldMap.toast.importFailed.title', 'Could not read file'),\n description: t(\n 'healthybowl.fieldMap.toast.importFailed.description',\n 'Make sure it is a valid GeoJSON (.json / .geojson) file.'\n ),\n variant: 'error',\n });\n }\n },\n [clearDraft, showBoundary, t, toast]\n );\n\n // ── Save ────────────────────────────────────────────────────────────────────\n const handleSave = useCallback(async () => {\n setSaving(true);\n try {\n const polygon = currentBoundaryRef.current;\n const nextArea = polygon ? polygonAreaInUnit(polygon, unit) : undefined;\n const nextLocation = pendingFieldLocation\n ? { lat: pendingFieldLocation.lat, lng: pendingFieldLocation.lng }\n : undefined;\n await updateBoundary({\n variables: {\n input: {\n id: fieldId,\n boundary: polygon,\n ...(nextArea != null ? { area: nextArea } : {}),\n ...(nextLocation ? { location: nextLocation } : {}),\n context: { workspaceId },\n },\n },\n });\n if (nextLocation) savedCenterRef.current = nextLocation;\n setBoundaryDirty(false);\n setLocationDirty(false);\n setPendingFieldLocation(null);\n onSaved?.();\n toast({\n title: t('healthybowl.fieldMap.toast.saved.title', 'Map saved'),\n description: nextLocation\n ? t('healthybowl.fieldMap.toast.savedLocation.description', 'Field GPS location updated.')\n : polygon\n ? t('healthybowl.fieldMap.toast.saved.description', 'Field area updated to {{area}} {{unit}}.', {\n area: String(nextArea ?? ''),\n unit,\n })\n : t('healthybowl.fieldMap.toast.savedCleared.description', 'Boundary removed from this field.'),\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.fieldMap.toast.saveFailed.title', 'Save failed'),\n description: String(err),\n variant: 'error',\n });\n } finally {\n setSaving(false);\n }\n }, [fieldId, onSaved, pendingFieldLocation, t, toast, unit, updateBoundary, workspaceId]);\n\n // ── Map init (once) ──────────────────────────────────────────────────────────\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return undefined;\n ensureLeafletCss();\n\n const satellite = L.tileLayer(ESRI_IMAGERY, { attribution: ESRI_ATTR, maxZoom: 19 });\n const terrain = L.tileLayer(TOPO_URL, { attribution: TOPO_ATTR, maxZoom: 17 });\n // TODO soil WMS URL: no reliable keyless soil WMS is confidently known, so the\n // \"Soil\" overlay is wired to a clearly-labelled OpenTopoMap placeholder for now.\n // Swap this for an OpenLandMap / SoilGrids WMS once a stable endpoint is confirmed.\n const soilPlaceholder = L.tileLayer(TOPO_URL, { attribution: TOPO_ATTR, maxZoom: 17, opacity: 0.6 });\n const streets = L.tileLayer(OSM_URL, { attribution: '© OpenStreetMap contributors', maxZoom: 19 });\n\n const map = L.map(el, { center: [20, 0], zoom: 2, scrollWheelZoom: true, layers: [satellite] });\n mapRef.current = map;\n\n L.control\n .layers(\n { [t('healthybowl.fieldMap.layers.satellite', 'Satellite (Esri)')]: satellite },\n {\n [t('healthybowl.fieldMap.layers.terrain', 'Terrain (OpenTopoMap)')]: terrain,\n [t('healthybowl.fieldMap.layers.soil', 'Soil (placeholder)')]: soilPlaceholder,\n [t('healthybowl.fieldMap.layers.streets', 'Streets (OSM)')]: streets,\n },\n { collapsed: false }\n )\n .addTo(map);\n\n map.on('click', handleMapClick);\n\n // Initial view: existing boundary → fit; else field centre; else world.\n const existing = extractPolygon(initialBoundary);\n if (existing && isValidPolygon(existing)) {\n showBoundary(existing, true);\n } else if (isUsableCoordinate(center)) {\n map.setView([center.lat, center.lng], FIELD_VIEW_ZOOM);\n }\n\n setStatus('ready');\n window.setTimeout(() => map.invalidateSize(), 80);\n\n return () => {\n map.off('click', handleMapClick);\n map.remove();\n mapRef.current = null;\n boundaryLayerRef.current = null;\n draftPolyRef.current = null;\n userLocationMarkerRef.current = null;\n userAccuracyCircleRef.current = null;\n fieldLocationMarkerRef.current = null;\n vertexMarkersRef.current = [];\n draftVerticesRef.current = [];\n currentBoundaryRef.current = null;\n };\n // Init once; handlers are stable via useCallback and read the latest state through refs.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div className=\"relative\">\n <div className=\"mb-3 flex flex-wrap items-center gap-2\">\n {mode === 'view' ? (\n <>\n <Button variant=\"outline\" size=\"sm\" onClick={startDraw}>\n <Pencil className=\"h-4 w-4\" />{' '}\n {hasBoundary\n ? t('healthybowl.fieldMap.actions.redraw', 'Redraw')\n : t('healthybowl.fieldMap.actions.draw', 'Draw boundary')}\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={() => fileInputRef.current?.click()}>\n <Upload className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.import', 'Import GeoJSON')}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={focusField}\n title={t('healthybowl.fieldMap.actions.focusField.title', 'Fit map to this field')}\n aria-label={t('healthybowl.fieldMap.actions.focusField.title', 'Fit map to this field')}\n >\n <MapPinned className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.focusField', 'Field')}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleLocateMe}\n disabled={locating}\n title={t('healthybowl.fieldMap.actions.locateMe.title', 'Go to my current location')}\n aria-label={t('healthybowl.fieldMap.actions.locateMe.title', 'Go to my current location')}\n >\n <LocateFixed className=\"h-4 w-4\" />{' '}\n {locating\n ? t('healthybowl.fieldMap.actions.locating', 'Locating...')\n : t('healthybowl.fieldMap.actions.locateMe', 'My location')}\n </Button>\n {hasBoundary && (\n <Button variant=\"outline\" size=\"sm\" onClick={handleClear}>\n <Trash2 className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.clear', 'Clear')}\n </Button>\n )}\n </>\n ) : (\n <>\n <Button variant=\"default\" size=\"sm\" onClick={finishDraw}>\n <Check className=\"h-4 w-4\" /> {t('healthybowl.fieldMap.actions.finish', 'Finish')}\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={cancelDraw}>\n <X className=\"h-4 w-4\" /> {t('healthybowl.common.cancel', 'Cancel')}\n </Button>\n <span className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.fieldMap.draftHint',\n 'Click the map to add corners ({{count}} placed) — click the first point or Finish to close.',\n {\n count: String(vertexCount),\n }\n )}\n </span>\n </>\n )}\n <div className=\"ml-auto flex items-center gap-3\">\n {area != null && (\n <span className=\"text-xs text-text-secondary\">\n {t('healthybowl.fieldMap.computedArea', 'Area: {{area}} {{unit}}', { area: String(area), unit })}\n </span>\n )}\n <Button variant=\"default\" size=\"sm\" onClick={handleSave} disabled={!dirty || saving || mode === 'draw'}>\n <Save className=\"h-4 w-4\" />{' '}\n {saving\n ? t('healthybowl.fieldMap.actions.saving', 'Saving…')\n : t('healthybowl.fieldMap.actions.save', 'Save')}\n </Button>\n </div>\n </div>\n\n {mode === 'view' && (\n <div className=\"mb-3 space-y-2\">\n <form className=\"flex flex-col gap-2 sm:flex-row\" onSubmit={handleSearchPlace}>\n <div className=\"relative min-w-0 flex-1\">\n <Search className=\"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-secondary\" />\n <input\n type=\"search\"\n value={searchQuery}\n onChange={(event) => setSearchQuery(event.target.value)}\n disabled={status !== 'ready' || searching}\n placeholder={t(\n 'healthybowl.fieldMap.search.placeholder',\n 'Search village, city, region, or lat,lng...'\n )}\n aria-label={t('healthybowl.fieldMap.search.label', 'Search field map by place or coordinates')}\n className=\"h-9 w-full rounded-md border border-border-subtle bg-bg-surface py-2 pl-9 pr-3 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]\"\n />\n </div>\n <Button type=\"submit\" variant=\"outline\" size=\"sm\" disabled={status !== 'ready' || searching}>\n <Search className=\"h-4 w-4\" />{' '}\n {searching\n ? t('healthybowl.fieldMap.search.searching', 'Searching...')\n : t('healthybowl.fieldMap.search.action', 'Search')}\n </Button>\n {pendingFieldLocation && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={clearFieldLocationCandidate}>\n <X className=\"h-4 w-4\" /> {t('healthybowl.common.clear', 'Clear')}\n </Button>\n )}\n </form>\n {pendingFieldLocation && (\n <div className=\"flex flex-wrap items-center gap-2 text-xs text-text-secondary\">\n <span className=\"inline-flex min-w-0 items-center gap-1.5 rounded-full border border-border-subtle bg-bg-sunken/70 px-2.5 py-1\">\n <MapPin className=\"h-3.5 w-3.5 shrink-0 text-success\" />\n <span className=\"truncate\">\n {t('healthybowl.fieldMap.search.pendingLocation', 'Unsaved field GPS: {{place}}', {\n place: pendingFieldLocation.label,\n })}\n </span>\n </span>\n </div>\n )}\n </div>\n )}\n\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\".json,.geojson,application/geo+json,application/json\"\n className=\"hidden\"\n onChange={(e) => {\n const file = e.target.files?.[0];\n if (file) void handleImportFile(file);\n e.target.value = '';\n }}\n />\n\n <div className=\"relative\">\n <div\n ref={containerRef}\n className=\"h-[60vh] max-h-[520px] w-full overflow-hidden rounded-md border border-border-subtle bg-bg-sunken\"\n />\n {status === 'loading' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/60 text-sm text-text-secondary\">\n {t('healthybowl.fieldMap.loading', 'Loading map…')}\n </div>\n )}\n {status === 'error' && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-bg-surface/80 px-4 text-center text-sm text-text-secondary\">\n {t('healthybowl.fieldMap.error', 'The map needs an internet connection and couldn’t load.')}\n </div>\n )}\n {status === 'ready' && !hasBoundary && mode === 'view' && (\n <div className=\"pointer-events-none absolute left-1/2 top-3 z-[400] -translate-x-1/2 rounded-full bg-bg-surface/90 px-3 py-1.5 text-xs text-text-secondary shadow-sm\">\n <span className=\"inline-flex items-center gap-1.5\">\n <MapPin className=\"h-3.5 w-3.5\" />{' '}\n {t('healthybowl.fieldMap.empty', 'No boundary set — draw or import one.')}\n </span>\n </div>\n )}\n </div>\n\n <p className=\"mt-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.fieldMap.attribution',\n 'Imagery © Esri, Maxar, Earthstar Geographics · overlays © OpenTopoMap / OpenStreetMap'\n )}\n </p>\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;mCAwBM,KAA4B,CAAG;;;;;;;;;GAuC/B,KAAe,iGACf,KAAY,sCACZ,KAAW,oDACX,KAAY,2DACZ,KAAU,sDAEV,KAAgC;CAAE,OAAO;CAAW,QAAQ;CAAG,WAAW;CAAW,aAAa;CAAM,EACxG,KAA6B;CACjC,OAAO;CACP,QAAQ;CACR,WAAW;CACX,WAAW;CACX,aAAa;CACd,EACK,KAAkB,IAClB,KAAiB,IAEjB,KAAsB,MAC1B,GACE,KACA,OAAO,SAAS,EAAM,IAAI,IAC1B,OAAO,SAAS,EAAM,IAAI,IAC1B,EAAM,OAAO,OACb,EAAM,OAAO,MACb,EAAM,OAAO,QACb,EAAM,OAAO,QACZ,EAAM,QAAQ,KAAK,EAAM,QAAQ,KAGhC,MAAyB,MAA+C;CAC5E,IAAM,IAAQ,EAAM,MAAM,CAAC,MAAM,8CAA8C;AAC/E,KAAI,CAAC,EAAO,QAAO;CACnB,IAAM,IAAM,OAAO,EAAM,GAAG,EACtB,IAAM,OAAO,EAAM,GAAG;AAE5B,QADK,EAAmB;EAAE;EAAK;EAAK,CAAC,GAC9B;EAAE;EAAK;EAAK,OAAO,GAAG,EAAI,QAAQ,EAAE,CAAC,IAAI,EAAI,QAAQ,EAAE;EAAI,GADpB;GAInC,KAA+B,EAAE,YAAS,SAAM,WAAQ,oBAAiB,kBAAc;CAClG,IAAM,EAAE,SAAM,IAAS,EACjB,E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EAAQ,WAAU,eAAgB,CAAA;QAAC;QAClC,EAAE,8BAA8B,wCAAwC;QACpE;;MACH,CAAA;KAEJ;;GAEN,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,oCACA,wFACD;IACC,CAAA;GAEJ,kBAAC,GAAD;IAAwB;IAAQ,WAAW;IAAW,CAAA;GAClD"}
@@ -1,19 +1,52 @@
1
1
  //#region src/healthybowl/utils/geocode.ts
2
- async function e(e, t) {
3
- let n = /* @__PURE__ */ new Set(), r = [e, e.split(",")[0] ?? ""].map((e) => e.trim()).filter((e) => e.length > 0 && !n.has(e) && !!n.add(e));
4
- for (let e of r) try {
5
- let n = (await (await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1`, t ? { signal: t } : void 0)).json()).results?.[0];
6
- if (n && typeof n.latitude == "number" && typeof n.longitude == "number") return {
7
- latitude: n.latitude,
8
- longitude: n.longitude,
9
- name: n.name,
10
- admin1: n.admin1,
11
- country: n.country
12
- };
2
+ var e = (e) => {
3
+ let t = /* @__PURE__ */ new Set();
4
+ return [e, e.split(",")[0] ?? ""].map((e) => e.trim()).filter((e) => e.length > 0 && !t.has(e) && !!t.add(e));
5
+ }, t = async (e, t) => {
6
+ let n = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1`, t ? { signal: t } : void 0);
7
+ if (!n.ok) return null;
8
+ let r = (await n.json()).results?.[0];
9
+ return r && typeof r.latitude == "number" && typeof r.longitude == "number" ? {
10
+ latitude: r.latitude,
11
+ longitude: r.longitude,
12
+ name: r.name,
13
+ admin1: r.admin1,
14
+ country: r.country
15
+ } : null;
16
+ }, n = async (e, t) => {
17
+ let n = new URLSearchParams({
18
+ format: "jsonv2",
19
+ q: e,
20
+ limit: "1",
21
+ addressdetails: "1"
22
+ }), r = await fetch(`https://nominatim.openstreetmap.org/search?${n.toString()}`, t ? { signal: t } : void 0);
23
+ if (!r.ok) return null;
24
+ let i = (await r.json())[0];
25
+ if (!i) return null;
26
+ let a = Number(i.lat), o = Number(i.lon);
27
+ if (!Number.isFinite(a) || !Number.isFinite(o)) return null;
28
+ let s = i.address;
29
+ return {
30
+ latitude: a,
31
+ longitude: o,
32
+ name: i.name || s?.village || s?.town || s?.city || s?.suburb || s?.postcode || i.display_name?.split(",")[0]?.trim(),
33
+ admin1: s?.state_district || s?.county || s?.state,
34
+ country: s?.country
35
+ };
36
+ };
37
+ async function r(r, i) {
38
+ let a = e(r);
39
+ for (let e of a) try {
40
+ let n = await t(e, i);
41
+ if (n) return n;
42
+ } catch {}
43
+ for (let e of a) try {
44
+ let t = await n(e, i);
45
+ if (t) return t;
13
46
  } catch {}
14
47
  return null;
15
48
  }
16
49
  //#endregion
17
- export { e as geocodePlace };
50
+ export { r as geocodePlace };
18
51
 
19
52
  //# sourceMappingURL=geocode.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"geocode.js","names":[],"sources":["../../../src/healthybowl/utils/geocode.ts"],"sourcesContent":["/**\n * Client-side geocoding via the keyless Open-Meteo API. Shared by the weather\n * map (centering) and the weather-location setter (resolving lat/lng for a farm\n * before calling updateFarm/createFarm). No backend dependency — this is the\n * same candidate strategy the svc geocoder uses (full string, then the segment\n * before the first comma).\n */\nexport interface GeoResult {\n latitude: number;\n longitude: number;\n /** The canonical place name Open-Meteo resolved (e.g. \"Pune\"). */\n name?: string;\n /** Admin region / country, when available (for disambiguation in the UI). */\n admin1?: string;\n country?: string;\n}\n\n/**\n * Resolve the best-match coordinates for a free-text place name. Returns null\n * when nothing matches or the network is unavailable (offline VM, no egress).\n */\nexport async function geocodePlace(name: string, signal?: AbortSignal): Promise<GeoResult | null> {\n const seen = new Set<string>();\n const candidates = [name, name.split(',')[0] ?? '']\n .map((c) => c.trim())\n .filter((c) => c.length > 0 && !seen.has(c) && Boolean(seen.add(c)));\n for (const q of candidates) {\n try {\n const res = await fetch(\n `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(q)}&count=1`,\n signal ? { signal } : undefined\n );\n const data = (await res.json()) as {\n results?: Array<{\n latitude?: number;\n longitude?: number;\n name?: string;\n admin1?: string;\n country?: string;\n }>;\n };\n const hit = data.results?.[0];\n if (hit && typeof hit.latitude === 'number' && typeof hit.longitude === 'number') {\n return {\n latitude: hit.latitude,\n longitude: hit.longitude,\n name: hit.name,\n admin1: hit.admin1,\n country: hit.country,\n };\n }\n } catch {\n /* try the next candidate */\n }\n }\n return null;\n}\n"],"mappings":";AAqBA,eAAsB,EAAa,GAAc,GAAiD;CAChG,IAAM,oBAAO,IAAI,KAAa,EACxB,IAAa,CAAC,GAAM,EAAK,MAAM,IAAI,CAAC,MAAM,GAAG,CAChD,KAAK,MAAM,EAAE,MAAM,CAAC,CACpB,QAAQ,MAAM,EAAE,SAAS,KAAK,CAAC,EAAK,IAAI,EAAE,IAAI,EAAQ,EAAK,IAAI,EAAE,CAAE;AACtE,MAAK,IAAM,KAAK,EACd,KAAI;EAcF,IAAM,KATQ,OAJF,MAAM,MAChB,uDAAuD,mBAAmB,EAAE,CAAC,WAC7E,IAAS,EAAE,WAAQ,GAAG,KAAA,EACvB,EACuB,MAAM,EASb,UAAU;AAC3B,MAAI,KAAO,OAAO,EAAI,YAAa,YAAY,OAAO,EAAI,aAAc,SACtE,QAAO;GACL,UAAU,EAAI;GACd,WAAW,EAAI;GACf,MAAM,EAAI;GACV,QAAQ,EAAI;GACZ,SAAS,EAAI;GACd;SAEG;AAIV,QAAO"}
1
+ {"version":3,"file":"geocode.js","names":[],"sources":["../../../src/healthybowl/utils/geocode.ts"],"sourcesContent":["/**\n * Client-side geocoding via keyless public providers. Open-Meteo is the fast\n * primary lookup for cities/towns; OpenStreetMap Nominatim is the fallback for\n * villages, post offices, pincodes, and other small places Open-Meteo misses.\n */\nexport interface GeoResult {\n latitude: number;\n longitude: number;\n /** The canonical place name the provider resolved (e.g. \"Pune\"). */\n name?: string;\n /** Admin region / country, when available (for disambiguation in the UI). */\n admin1?: string;\n country?: string;\n}\n\nconst buildCandidates = (name: string): string[] => {\n const seen = new Set<string>();\n return [name, name.split(',')[0] ?? '']\n .map((candidate) => candidate.trim())\n .filter((candidate) => candidate.length > 0 && !seen.has(candidate) && Boolean(seen.add(candidate)));\n};\n\nconst geocodeOpenMeteo = async (query: string, signal?: AbortSignal): Promise<GeoResult | null> => {\n const res = await fetch(\n `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(query)}&count=1`,\n signal ? { signal } : undefined\n );\n if (!res.ok) return null;\n const data = (await res.json()) as {\n results?: Array<{\n latitude?: number;\n longitude?: number;\n name?: string;\n admin1?: string;\n country?: string;\n }>;\n };\n const hit = data.results?.[0];\n if (hit && typeof hit.latitude === 'number' && typeof hit.longitude === 'number') {\n return {\n latitude: hit.latitude,\n longitude: hit.longitude,\n name: hit.name,\n admin1: hit.admin1,\n country: hit.country,\n };\n }\n return null;\n};\n\nconst geocodeNominatim = async (query: string, signal?: AbortSignal): Promise<GeoResult | null> => {\n const params = new URLSearchParams({\n format: 'jsonv2',\n q: query,\n limit: '1',\n addressdetails: '1',\n });\n const res = await fetch(\n `https://nominatim.openstreetmap.org/search?${params.toString()}`,\n signal ? { signal } : undefined\n );\n if (!res.ok) return null;\n const data = (await res.json()) as Array<{\n lat?: string;\n lon?: string;\n name?: string;\n display_name?: string;\n address?: {\n village?: string;\n town?: string;\n city?: string;\n suburb?: string;\n county?: string;\n state_district?: string;\n state?: string;\n postcode?: string;\n country?: string;\n };\n }>;\n const hit = data[0];\n if (!hit) return null;\n const latitude = Number(hit.lat);\n const longitude = Number(hit.lon);\n if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;\n\n const address = hit.address;\n const name =\n hit.name ||\n address?.village ||\n address?.town ||\n address?.city ||\n address?.suburb ||\n address?.postcode ||\n hit.display_name?.split(',')[0]?.trim();\n const admin1 = address?.state_district || address?.county || address?.state;\n\n return {\n latitude,\n longitude,\n name,\n admin1,\n country: address?.country,\n };\n};\n\n/**\n * Resolve the best-match coordinates for a free-text place name. Returns null\n * when nothing matches or the network is unavailable (offline VM, no egress).\n */\nexport async function geocodePlace(name: string, signal?: AbortSignal): Promise<GeoResult | null> {\n const candidates = buildCandidates(name);\n for (const q of candidates) {\n try {\n const hit = await geocodeOpenMeteo(q, signal);\n if (hit) return hit;\n } catch {\n /* try the next candidate */\n }\n }\n for (const q of candidates) {\n try {\n const hit = await geocodeNominatim(q, signal);\n if (hit) return hit;\n } catch {\n /* try the next candidate */\n }\n }\n return null;\n}\n"],"mappings":";AAeA,IAAM,KAAmB,MAA2B;CAClD,IAAM,oBAAO,IAAI,KAAa;AAC9B,QAAO,CAAC,GAAM,EAAK,MAAM,IAAI,CAAC,MAAM,GAAG,CACpC,KAAK,MAAc,EAAU,MAAM,CAAC,CACpC,QAAQ,MAAc,EAAU,SAAS,KAAK,CAAC,EAAK,IAAI,EAAU,IAAI,EAAQ,EAAK,IAAI,EAAU,CAAE;GAGlG,IAAmB,OAAO,GAAe,MAAoD;CACjG,IAAM,IAAM,MAAM,MAChB,uDAAuD,mBAAmB,EAAM,CAAC,WACjF,IAAS,EAAE,WAAQ,GAAG,KAAA,EACvB;AACD,KAAI,CAAC,EAAI,GAAI,QAAO;CAUpB,IAAM,KATQ,MAAM,EAAI,MAAM,EASb,UAAU;AAU3B,QATI,KAAO,OAAO,EAAI,YAAa,YAAY,OAAO,EAAI,aAAc,WAC/D;EACL,UAAU,EAAI;EACd,WAAW,EAAI;EACf,MAAM,EAAI;EACV,QAAQ,EAAI;EACZ,SAAS,EAAI;EACd,GAEI;GAGH,IAAmB,OAAO,GAAe,MAAoD;CACjG,IAAM,IAAS,IAAI,gBAAgB;EACjC,QAAQ;EACR,GAAG;EACH,OAAO;EACP,gBAAgB;EACjB,CAAC,EACI,IAAM,MAAM,MAChB,8CAA8C,EAAO,UAAU,IAC/D,IAAS,EAAE,WAAQ,GAAG,KAAA,EACvB;AACD,KAAI,CAAC,EAAI,GAAI,QAAO;CAkBpB,IAAM,KAjBQ,MAAM,EAAI,MAAM,EAiBb;AACjB,KAAI,CAAC,EAAK,QAAO;CACjB,IAAM,IAAW,OAAO,EAAI,IAAI,EAC1B,IAAY,OAAO,EAAI,IAAI;AACjC,KAAI,CAAC,OAAO,SAAS,EAAS,IAAI,CAAC,OAAO,SAAS,EAAU,CAAE,QAAO;CAEtE,IAAM,IAAU,EAAI;AAWpB,QAAO;EACL;EACA;EACA,MAZA,EAAI,QACJ,GAAS,WACT,GAAS,QACT,GAAS,QACT,GAAS,UACT,GAAS,YACT,EAAI,cAAc,MAAM,IAAI,CAAC,IAAI,MAAM;EAOvC,QANa,GAAS,kBAAkB,GAAS,UAAU,GAAS;EAOpE,SAAS,GAAS;EACnB;;AAOH,eAAsB,EAAa,GAAc,GAAiD;CAChG,IAAM,IAAa,EAAgB,EAAK;AACxC,MAAK,IAAM,KAAK,EACd,KAAI;EACF,IAAM,IAAM,MAAM,EAAiB,GAAG,EAAO;AAC7C,MAAI,EAAK,QAAO;SACV;AAIV,MAAK,IAAM,KAAK,EACd,KAAI;EACF,IAAM,IAAM,MAAM,EAAiB,GAAG,EAAO;AAC7C,MAAI,EAAK,QAAO;SACV;AAIV,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.709.4",
3
+ "version": "2026.710.2",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [