{
  "always_run_in_app": false,
  "icon": {
    "color": "orange",
    "glyph": "smog"
  },
  "name": "HazeNow",
  "script": "// Variables used by Scriptable.\n// These must be at the very top of the file. Do not edit.\n// icon-color: orange; icon-glyph: smog;\n\n/*\n * HazeNow for Scriptable: an iOS home/lock-screen widget with no App Store wait. MIT licensed.\n * Singapore haze right now: NEA's 1-hr PM2.5 with plain-words advice, next to NEA's 24-hr PSI.\n * Data: NEA via data.gov.sg. Your location stays on your device (only used to weight NEA's 5 stations).\n * Copy follows docs/COPY.md verbatim.\n *\n * Setup: one tap on https://hazenow.pages.dev/widget/HazeNow.scriptable imports it into Scriptable (or paste this\n * file into a new script named \"HazeNow\"). Long-press the home screen → + → Scriptable → pick a size → tap the\n * widget → Script: HazeNow. Optional \"Parameter\" (comma-separated):\n *   (empty)                  your location if you allowed it in Scriptable, else Singapore island (all NEA stations)\n *   Tampines, Ang Mo Kio, CBD, Sentosa, …   any planning area or a common name for one (estimated for that spot)\n *   central|north|south|east|west|island    one NEA region, or the islandwide average\n *   general|kids|elderly|pregnant|heart_lung|exercising|outdoor_worker   who you're checking for\n *   e.g. \"Tampines\" or \"west,kids\" or \"Bukit Timah, elderly\"\n * Also works on the lock screen (circular / rectangular / inline) and from Siri Shortcuts.\n */\n\nconst API_V1 = \"https://api.data.gov.sg/v1/environment\"; // primary: fresh (~hh:01), no observed rate limit\nconst API_V2 = \"https://api-open.data.gov.sg/v2/real-time/api\"; // fallback only: rate-limited\nconst WEB = \"https://hazenow.app\";\nconst REGIONS = [\"central\", \"north\", \"south\", \"east\", \"west\"];\nconst PROFILES = [\"general\", \"kids\", \"elderly\", \"pregnant\", \"heart_lung\", \"exercising\", \"outdoor_worker\"];\nconst SENSITIVE = [\"kids\", \"elderly\", \"pregnant\", \"heart_lung\"];\nconst FALLBACK = {\n  north: [1.41803, 103.82], south: [1.29587, 103.82], east: [1.35735, 103.94],\n  west: [1.35735, 103.7], central: [1.35735, 103.82],\n};\n// Planning areas: [name, lat, lon, \"alias|alias\"]. GENERATED from packages/core/src/areas-data.ts (URA Master Plan\n// 2019, data.gov.sg); test/check.mjs fails if it drifts.\nconst AREAS = [[\"Ang Mo Kio\",1.38009,103.8421,\"AMK|Cheng San|Teck Ghee|Yio Chu Kang|Sembawang Hills\"],[\"Bedok\",1.32405,103.92841,\"Bedok North|Bedok South|Bedok Reservoir|Chai Chee|Kembangan|Frankel|Kaki Bukit|Siglap\"],[\"Bishan\",1.35496,103.84044,\"Bishan North|Sin Ming|Marymount\"],[\"Boon Lay\",1.31479,103.70222,\"Boon Lay Place|Liu Fang\"],[\"Bukit Batok\",1.35566,103.75473,\"Bukit Gombak|Hillview|Guilin|Brickworks\"],[\"Bukit Merah\",1.27549,103.82314,\"Redhill|Tiong Bahru|Telok Blangah|HarbourFront|Henderson|Depot Road|Alexandra|Kampong Bahru|Everton Park\"],[\"Bukit Panjang\",1.36682,103.773,\"Senja|Fajar|Bangkit|Segar|Pending|Petir|Jelapang|Saujana\"],[\"Bukit Timah\",1.33,103.7907,\"Sixth Avenue|King Albert Park|Beauty World|Toh Yi|Hillcrest|Coronation Road|Swiss Club|Farrer Court\"],[\"Central Water Catchment\",1.37665,103.8012,\"MacRitchie|MacRitchie Reservoir|Upper Peirce\"],[\"Changi\",1.35032,103.99782,\"Changi Airport|Changi Village|Changi Point\"],[\"Changi Bay\",1.32407,104.02449,\"\"],[\"Choa Chu Kang\",1.38556,103.74719,\"CCK|Chua Chu Kang|Yew Tee|Teck Whye|Keat Hong|Brickland\"],[\"Clementi\",1.31759,103.76075,\"Clementi West|Clementi Central|West Coast|Sunset Way|Faber\"],[\"Downtown Core\",1.28679,103.8555,\"CBD|Raffles Place|City Hall|Marina Centre|Tanjong Pagar|Cecil|Bugis|Bayfront|Anson\"],[\"Geylang\",1.3209,103.88952,\"Aljunied|Geylang East|Kampong Ubi|MacPherson|Eunos\"],[\"Hougang\",1.36364,103.8898,\"Kovan|Lorong Ah Soo|Upper Paya Lebar|Tai Seng|Defu\"],[\"Jurong East\",1.32044,103.73479,\"Yuhua|Toh Guan|Teban Gardens|Jurong Gateway|Jurong Lake|Penjuru\"],[\"Jurong West\",1.34161,103.7049,\"Hong Kah|Taman Jurong|Yunnan|Wenya|Gek Poh|Jurong West Central\"],[\"Kallang\",1.31112,103.86654,\"Kallang Bahru|Bendemeer|Lavender|Boon Keng|Geylang Bahru|Jalan Besar|Crawford|Kallang Riverside\"],[\"Lim Chu Kang\",1.43064,103.71929,\"Sungei Gedong\"],[\"Mandai\",1.42362,103.80246,\"Mandai Estate\"],[\"Marina East\",1.28852,103.87235,\"\"],[\"Marina South\",1.28053,103.86563,\"Gardens by the Bay|Marina Barrage\"],[\"Marine Parade\",1.30023,103.89627,\"Katong|Mountbatten|East Coast|East Coast Park|Joo Chiat\"],[\"Museum\",1.29592,103.84672,\"Dhoby Ghaut|Fort Canning|Bras Basah\"],[\"Newton\",1.30866,103.83808,\"Newton Circus|Cairnhill|Goodwood Park\"],[\"North-Eastern Islands\",1.399,104.0516,\"Pulau Ubin|Pulau Tekong\"],[\"Novena\",1.32698,103.83531,\"Balestier|Moulmein|Thomson|Mount Pleasant\"],[\"Orchard\",1.30381,103.83358,\"Orchard Road|Somerset|Boulevard\"],[\"Outram\",1.28286,103.84206,\"Chinatown|Pearl's Hill|People's Park|China Square\"],[\"Pasir Ris\",1.37862,103.94829,\"Loyang|Elias|Pasir Ris Park|Pasir Ris West\"],[\"Paya Lebar\",1.3594,103.91478,\"Paya Lebar Airbase\"],[\"Pioneer\",1.31259,103.67299,\"Pioneer Sector\"],[\"Punggol\",1.40536,103.91005,\"Punggol Waterway|Matilda|Coney Island|Punggol Field|Northshore\"],[\"Queenstown\",1.28908,103.78457,\"Commonwealth|Dover|Buona Vista|one-north|Tanglin Halt|Kent Ridge|NUS|Mei Chin|Ghim Moh|Holland Village\"],[\"River Valley\",1.29805,103.83398,\"Great World|Leonie Hill|Oxley\"],[\"Rochor\",1.30414,103.85328,\"Little India|Kampong Glam|Farrer Park|Victoria Street|Sungei Road\"],[\"Seletar\",1.41438,103.87707,\"Seletar Aerospace|Seletar Airport\"],[\"Sembawang\",1.45575,103.81883,\"Canberra|Sembawang Springs|Admiralty Park\"],[\"Sengkang\",1.39128,103.88771,\"Anchorvale|Compassvale|Rivervale|Fernvale|Sengkang West\"],[\"Serangoon\",1.3652,103.86782,\"Serangoon Gardens|Serangoon North|Lorong Chuan|Serangoon Central\"],[\"Simpang\",1.44422,103.85003,\"\"],[\"Singapore River\",1.29011,103.84121,\"Clarke Quay|Boat Quay|Robertson Quay\"],[\"Southern Islands\",1.2497,103.8298,\"Sentosa|St John's Island|Kusu Island\"],[\"Straits View\",1.27125,103.85877,\"\"],[\"Sungei Kadut\",1.41813,103.75746,\"Kranji\"],[\"Tampines\",1.34379,103.95403,\"Tampines East|Tampines West|Tampines North|Simei\"],[\"Tanglin\",1.30837,103.8176,\"Botanic Gardens|Dempsey|Nassim|Tyersall|Chatsworth|Ridout\"],[\"Tengah\",1.36385,103.72875,\"Tengah Garden|Tengah Park\"],[\"Toa Payoh\",1.33668,103.86103,\"Braddell|Potong Pasir|Woodleigh|Bidadari|Boon Teck|Caldecott\"],[\"Tuas\",1.28024,103.6331,\"Tuas South|Tuas View|Tuas Link|Joo Koon\"],[\"Western Islands\",1.26599,103.69175,\"Jurong Island|Pulau Bukom\"],[\"Western Water Catchment\",1.38211,103.68974,\"Tengeh|Poyan\"],[\"Woodlands\",1.44068,103.7877,\"Admiralty|Marsiling|Woodlands North|Woodlands South|Causeway\"],[\"Yishun\",1.41504,103.83712,\"Khatib|Chong Pang|Nee Soon|Yishun East|Yishun West\"]];\nconst norm = (x) => String(x).toLowerCase().replace(/[^a-z0-9]+/g, \"\");\nfunction findArea(q) {\n  const n = norm(q);\n  if (n.length < 2) return null;\n  const hit = AREAS.find((a) => norm(a[0]) === n || a[3].split(\"|\").some((x) => x && norm(x) === n))\n    || (n.length >= 4 ? AREAS.find((a) => norm(a[0]).startsWith(n)) : null);\n  return hit ? { name: hit[0], loc: [hit[1], hit[2]] } : null;\n}\n// COPY §3: text label always; shape carries meaning (SF Symbols); never ▲/▼ in the chip.\nconst BANDS = {\n  normal: { label: \"Normal\", color: \"#2E9E5B\", sf: \"circle.fill\", glyph: \"●\" },\n  elevated: { label: \"Elevated\", color: \"#E8A317\", sf: \"circle.lefthalf.filled\", glyph: \"◐\" },\n  high: { label: \"High\", color: \"#E4572E\", sf: \"triangle.fill\", glyph: \"△\" },\n  very_high: { label: \"Very High\", color: \"#7B2D8E\", sf: \"octagon.fill\", glyph: \"⬣\" },\n};\nconst FOR_LABEL = { general: \"For you\", kids: \"For kids\", elderly: \"For older adults\", pregnant: \"For pregnancy\", heart_lung: \"For asthma, COPD & heart\", exercising: \"For your workout\", outdoor_worker: \"For outdoor work\" };\nconst V = { // COPY §2 [long, short]\n  normal: { general: [\"Fine to be out.\", \"Fine to be out\"], kids: [\"Fine for outdoor play.\", \"Fine for outdoor play\"], elderly: [\"Fine to be out.\", \"Fine to be out\"], pregnant: [\"Fine to be out.\", \"Fine to be out\"], heart_lung: [\"Fine to be out.\", \"Fine to be out\"], exercising: [\"Fine to exercise outside.\", \"Fine to exercise outside\"], outdoor_worker: [\"Fine to be out.\", \"Fine to be out\"] },\n  elevated: { general: [\"OK to be out. Go easy on hard exercise.\", \"Go easy outdoors\"], kids: [\"Calm play outside is OK. Skip running games for now.\", \"Calm play only\"], elderly: [\"A gentle walk is OK. Skip hard exercise for now.\", \"Gentle activity only\"], pregnant: [\"Gentle activity is OK. Skip hard exercise for now.\", \"Gentle activity only\"], heart_lung: [\"Gentle activity is OK. Skip hard exercise for now.\", \"Gentle activity only\"], exercising: [\"Keep your workout light, or move it indoors.\", \"Light workout or go indoors\"], outdoor_worker: [\"OK to work outside. Take breaks indoors if you can.\", \"Take breaks indoors\"] },\n  high: { general: [\"Short trips out are OK. Exercise indoors.\", \"No outdoor exercise\"], kids: [\"Indoor play for now. Keep trips out short.\", \"Indoor play for now\"], elderly: [\"Stay indoors for now if you can.\", \"Stay indoors for now\"], pregnant: [\"Stay indoors for now if you can.\", \"Stay indoors for now\"], heart_lung: [\"Stay indoors for now if you can.\", \"Stay indoors for now\"], exercising: [\"Move your workout indoors.\", \"Work out indoors\"], outdoor_worker: [\"Take regular breaks indoors. Ask about lighter outdoor tasks.\", \"Take regular indoor breaks\"] },\n  very_high: { general: [\"Stay indoors for now. Go out only if you need to.\", \"Stay indoors for now\"], kids: [\"Keep kids indoors for now.\", \"Kids indoors for now\"], elderly: [\"Stay indoors for now.\", \"Stay indoors for now\"], pregnant: [\"Stay indoors for now.\", \"Stay indoors for now\"], heart_lung: [\"Stay indoors for now.\", \"Stay indoors for now\"], exercising: [\"Skip outdoor exercise for now.\", \"No outdoor exercise\"], outdoor_worker: [\"Limit time outside for now. Ask about indoor work.\", \"Limit time outside\"] },\n};\nconst ANCHOR = { normal: \"Normal is up to 55.\", elevated: \"Elevated band (56–150). High starts at 151.\", high: \"High band (151–250). Very High starts at 251.\", very_high: \"Very High band (251 and above).\" };\nconst FOOTER = \"Data: NEA via data.gov.sg · Free & open source · No ads, no tracking, no account\";\nconst WHY_SHORT = \"Both are from NEA: the PSI averages 24 hours, PM2.5 shows the last hour.\";\n\n// ------------------------------------------------------------------ SPEC maths\nconst rhu = (x) => Math.floor(x + 0.5);\nconst valid = (v) => typeof v === \"number\" && isFinite(v) && v >= 0;\nconst bandOf = (c) => (c <= 55 ? \"normal\" : c <= 150 ? \"elevated\" : c <= 250 ? \"high\" : \"very_high\");\nconst psiDescriptor = (p) => (p <= 50 ? \"Good\" : p <= 100 ? \"Moderate\" : p <= 200 ? \"Unhealthy\" : p <= 300 ? \"Very Unhealthy\" : \"Hazardous\");\nfunction km(a, b) {\n  const r = (d) => (d * Math.PI) / 180;\n  const h = Math.sin(r(b[0] - a[0]) / 2) ** 2 + Math.cos(r(a[0])) * Math.cos(r(b[0])) * Math.sin(r(b[1] - a[1]) / 2) ** 2;\n  return 6371.0088 * 2 * Math.asin(Math.sqrt(h));\n}\nfunction atSpot(readings, coords, region, loc) {\n  const ok = Object.keys(readings || {}).filter((k) => valid(readings[k]) && coords[k]);\n  if (!ok.length) return null;\n  if (loc) {\n    const d = ok.map((k) => ({ k, v: readings[k], d: km(loc, coords[k]) })).sort((a, b) => a.d - b.d);\n    const nearby = d.length > 1 ? [Math.min(d[0].v, d[1].v), Math.max(d[0].v, d[1].v)] : null;\n    if (d[0].d < 0.5) return { v: rhu(d[0].v), mode: \"gps\", nearest: d[0].k, km: d[0].d, blended: false, nearby };\n    let n = 0, w = 0;\n    for (const x of d) { n += x.v / x.d ** 2; w += 1 / x.d ** 2; }\n    return { v: rhu(n / w), mode: \"gps\", nearest: d[0].k, km: d[0].d, blended: true, nearby };\n  }\n  if (ok.includes(region)) return { v: rhu(readings[region]), mode: \"region\", nearest: region };\n  return { v: rhu(ok.reduce((s, k) => s + readings[k], 0) / ok.length), mode: \"island\", nearest: region, fellBack: region !== \"island\" };\n}\nconst arrowOf = (d) => (d >= 5 ? \"▲\" : d <= -5 ? \"▼\" : \"▶\");\nconst title = (s) => s.charAt(0).toUpperCase() + s.slice(1);\nfunction timeLabel(iso) {\n  const d = new Date(Date.parse(iso) + 8 * 3600e3);\n  const h = d.getUTCHours(), m = d.getUTCMinutes();\n  return `${h % 12 || 12}${m ? \":\" + String(m).padStart(2, \"0\") : \"\"}${h < 12 ? \"am\" : \"pm\"}`;\n}\nfunction ageText(iso) {\n  const m = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 60000));\n  return m < 5 ? \"just now\" : m < 60 ? `${m} min ago` : `${Math.floor(m / 60)} h ${m % 60} min ago`;\n}\nfunction trendPhrase(h) { // COPY §4\n  const n = h.length;\n  if (n < 2) return { words: \"Trend not available yet\", word: \"\" };\n  const d1 = h[n - 1] - h[n - 2], d2 = n >= 3 ? h[n - 1] - h[n - 3] : d1;\n  const word = d1 >= 20 ? \"rising fast\" : d1 >= 5 ? \"rising\" : d1 <= -20 ? \"clearing fast\" : d1 <= -5 ? \"easing\" : \"steady\";\n  if (Math.sign(d2) === Math.sign(d1) && Math.abs(d2) > Math.abs(d1) && Math.abs(d2) >= 20)\n    return { words: d2 > 0 ? `Rising fast: up ${d2} in 2 hours` : `Clearing fast: down ${-d2} in 2 hours`, word };\n  if (d1 >= 20) return { words: `Rising fast: up ${d1} in the last hour`, word };\n  if (d1 >= 5) return { words: `Rising: up ${d1} in the last hour`, word };\n  if (d1 <= -20) return { words: `Clearing fast: down ${-d1} in the last hour`, word };\n  if (d1 <= -5) return { words: `Easing: down ${-d1} in the last hour`, word };\n  return { words: \"Steady over the last hour\", word };\n}\nfunction actionsFor(band, hist, p) { // COPY §5, filtered by profile; masks never lead\n  const sens = SENSITIVE.includes(p);\n  if (band === \"normal\") return hist.slice(-4, -1).some((v) => v > 55) ? [\"Air's cleared. Good time to open the windows.\"] : [\"Enjoy the fresh air.\"];\n  if (p === \"outdoor_worker\") { // COPY §17\n    const w = [\"Take breaks in the shade or indoors, and drink water.\", \"Ask your supervisor about indoor breaks and lighter tasks.\"];\n    return band === \"elevated\" ? w : band === \"high\" ? [...w, \"Out for hours? An N95 mask helps. Not needed for short trips.\"] : [...w, \"Feeling unwell? See a doctor. Chest pain or can't breathe: call 995.\"];\n  }\n  if (band === \"elevated\") {\n    const o = [];\n    if (p === \"heart_lung\") o.push(\"Asthma or COPD? Keep your inhaler with you.\");\n    if (p === \"exercising\") o.push(\"Shorten or slow your run, or move it indoors.\");\n    if (p === \"kids\") o.push(\"Swap running games for calm play for now.\");\n    if (sens) o.push(\"At home? Close the windows. Use a fan or aircon to keep cool.\");\n    if (p === \"general\") o.push(\"Haze isn't always easy to see. Check here before a long run.\");\n    return o.slice(0, 3);\n  }\n  const hi = [\"Close windows. Use aircon or a fan to keep cool.\", \"Run a purifier in the room you're in, if you have one.\"];\n  if (p === \"exercising\" || p === \"general\") hi.push(\"Move exercise indoors, or try later.\");\n  if (p === \"heart_lung\") hi.push(\"Keep your inhaler or medicine close. Follow your doctor's plan.\");\n  if (p === \"kids\") hi.push(\"Plan indoor play. Keep trips out short.\", \"N95 masks aren't made for children. Keeping kids indoors works better.\");\n  else if (p === \"pregnant\") hi.push(\"Pregnant? Wear an N95 only for short periods, and take it off if it feels hard to breathe.\");\n  else if (p === \"heart_lung\") hi.push(\"Heart or lung condition? Ask your doctor before using an N95.\");\n  else hi.push(\"Out for hours? An N95 mask helps. Not needed for short trips.\");\n  if (band === \"high\") return hi.slice(0, 3);\n  return [hi[0], \"Feeling unwell? See a doctor. Chest pain or can't breathe: call 995.\", \"Check on older family and neighbours.\"];\n}\nconst sgtDate = (offDays) => new Date(Date.now() + 8 * 3600e3 - offDays * 86400e3).toISOString().slice(0, 10);\n\n// ------------------------------------------------------------------ data\nconst fm = FileManager.local();\nconst dir = fm.joinPath(fm.documentsDirectory(), \"hazenow\");\nif (!fm.fileExists(dir)) fm.createDirectory(dir, true);\nconst cachePath = (name) => fm.joinPath(dir, name + \".json\");\nconst readCache = (name) => { try { return JSON.parse(fm.readString(cachePath(name))); } catch (e) { return null; } };\nconst writeCache = (name, v) => { try { fm.writeString(cachePath(name), JSON.stringify(v)); } catch (e) {} };\n\nasync function getJSON(url) {\n  const req = new Request(url);\n  req.headers = { \"User-Agent\": \"HazeNow-Scriptable/0.3\", Accept: \"application/json\" };\n  req.timeoutInterval = 12;\n  const body = await req.loadJSON();\n  return { body, status: req.response ? req.response.statusCode : 0 };\n}\nconst fromV1 = (d) => ({\n  regionMetadata: (d.region_metadata || []).map((m) => ({ name: m.name, labelLocation: m.label_location })),\n  items: (d.items || []).map((it) => ({ timestamp: it.timestamp, updatedTimestamp: it.update_timestamp, readings: it.readings })),\n});\n/** SPEC v1.3: v1 first, v2 only as a fallback (one try; the widget refreshes again soon anyway). */\nasync function fetchKind(kind, date) {\n  const q = date ? `?date=${date}` : \"\";\n  try {\n    const { body, status } = await getJSON(`${API_V1}/${kind}${q}`);\n    if (status === 200 && body && body.items) return fromV1(body);\n  } catch (e) {}\n  const { body } = await getJSON(`${API_V2}/${kind}${q}`);\n  if (body && body.code === 0 && body.data) return body.data;\n  throw new Error((body && body.errorMsg) || \"bad response\");\n}\nasync function pastDay(kind, date) {\n  const key = `v1-${kind}-${date}`;\n  const c = readCache(key);\n  if (c) return c;\n  const d = await fetchKind(kind, date);\n  writeCache(key, d);\n  return d;\n}\nasync function loadRaw() {\n  const [t, y] = [sgtDate(0), sgtDate(1)];\n  let pm = await fetchKind(\"pm25\", t);\n  if (!pm.items.length) pm = await fetchKind(\"pm25\", null);\n  const raw = {\n    pm: [pm, await pastDay(\"pm25\", y).catch(() => null)].filter(Boolean),\n    psi: [await fetchKind(\"psi\", t).catch(() => null), await pastDay(\"psi\", y).catch(() => null)].filter(Boolean),\n  };\n  writeCache(\"last\", raw);\n  return raw;\n}\nfunction merge(lists) { // same hour: earlier lists win per region when valid; later ones fill gaps\n  const by = {};\n  for (const d of lists) for (const it of d.items || []) {\n    const have = by[it.timestamp];\n    if (!have) { by[it.timestamp] = JSON.parse(JSON.stringify(it)); continue; }\n    for (const f of Object.keys(it.readings || {})) {\n      have.readings[f] = have.readings[f] || {};\n      for (const k of Object.keys(it.readings[f] || {})) if (!valid(have.readings[f][k]) && valid(it.readings[f][k])) have.readings[f][k] = it.readings[f][k];\n    }\n  }\n  return by;\n}\n\nfunction snapshot(raw, region, loc) {\n  const withMeta = raw.pm.find((d) => d.regionMetadata && d.regionMetadata.length);\n  const coords = Object.assign({}, FALLBACK);\n  for (const m of (withMeta && withMeta.regionMetadata) || []) coords[m.name] = [m.labelLocation.latitude, m.labelLocation.longitude];\n  const items = Object.values(merge(raw.pm)).sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));\n  const psiBy = merge(raw.psi);\n  const idx = items.findIndex((it) => atSpot(it.readings.pm25_one_hourly, coords, region, loc));\n  if (idx < 0) throw new Error(\"No valid readings\");\n  const cur = items[idx];\n  const spot = atSpot(cur.readings.pm25_one_hourly, coords, region, loc);\n  const officialAt = (ts, field) => {\n    const r = psiBy[ts] && psiBy[ts].readings[field];\n    if (!r) return null;\n    if (spot.mode !== \"island\" && valid(r[spot.nearest])) return r[spot.nearest];\n    const vs = Object.values(r).filter(valid);\n    return vs.length ? rhu(vs.reduce((a, b) => a + b, 0) / vs.length) : null;\n  };\n  const hist = [];\n  for (const it of items.slice(idx, idx + 24).reverse()) {\n    const s = atSpot(it.readings.pm25_one_hourly, coords, region, loc);\n    if (s) hist.push({ t: it.timestamp, v: s.v, avg: officialAt(it.timestamp, \"pm25_twenty_four_hourly\") });\n  }\n  const values = hist.map((h) => h.v);\n  const delta = values.length > 1 ? values[values.length - 1] - values[values.length - 2] : 0;\n  const regions = {};\n  for (const k of REGIONS) { const v = cur.readings.pm25_one_hourly[k]; regions[k] = valid(v) ? v : null; }\n  return {\n    pm25: spot.v, band: bandOf(spot.v), delta, arrow: arrowOf(delta), spot, regions, hist, values,\n    officialPsi24h: officialAt(cur.timestamp, \"psi_twenty_four_hourly\"),\n    observedAt: cur.timestamp, publishedAt: cur.updatedTimestamp || cur.timestamp,\n    stale: Date.now() - Date.parse(cur.timestamp) > 135 * 60e3,\n  };\n}\n\nfunction provenance(s) { // COPY §6\n  const obs = timeLabel(s.observedAt), age = ` · ${ageText(s.observedAt)}`, R = title(s.spot.nearest || \"island\");\n  if (s.spot.mode === \"gps\") return s.spot.blended\n    ? `Estimated for ${s.place || \"your spot\"} from NEA stations · nearest: ${R}, ${s.spot.km.toFixed(1)} km · measured ${obs}${age}`\n    : `NEA ${R} station · ${s.spot.km.toFixed(1)} km ${s.place ? `from ${s.place}` : \"away\"} · measured ${obs}${age}`;\n  if (s.spot.mode === \"island\") return s.spot.fellBack ? `${R} station is offline. Showing the average of NEA's other stations.${age}` : `Average of NEA stations islandwide · measured ${obs}${age}`;\n  return `NEA ${R} station · measured ${obs}${age}`;\n}\nfunction uncertainty(s) {\n  if (s.spot.mode !== \"gps\" || !s.spot.nearby) return null;\n  const [lo, hi] = s.spot.nearby;\n  return s.spot.km > 5 || hi - lo > 30 ? `Nearby stations read ${lo}–${hi}.` : null;\n}\nfunction secondLine(s) {\n  if (s.stale) return `Reading is from ${timeLabel(s.observedAt)}. It may not match the air now.`;\n  const el = s.band !== \"normal\";\n  if (s.delta >= 20) return el ? \"Getting worse. Check again in an hour.\" : \"Rising quickly. Check again in an hour.\";\n  if (s.delta <= -20 && el) return \"Getting better. Check again in an hour.\";\n  const h = s.hist, n = h.length;\n  if (el && n >= 3 && h[n - 1].v < h[n - 2].v && h[n - 2].v < h[n - 3].v) {\n    let i = n - 3;\n    while (i > 0 && h[i - 1].v > h[i].v) i--;\n    return `Easing since ${timeLabel(h[i].t)}.`;\n  }\n  return null;\n}\nconst officialLine = (s) => (s.officialPsi24h == null ? \"NEA 24-hr PSI: not available right now\" : `NEA 24-hr PSI: ${s.officialPsi24h} (${psiDescriptor(s.officialPsi24h)})`);\nconst num = (s) => `${s.spot.blended ? \"~\" : \"\"}${s.pm25}`;\n\n// ------------------------------------------------------------------ chart (COPY §8): hourly PM2.5 bars + NEA 24-hr PM2.5 line, both µg/m³\nfunction chartImage(s, w, h) {\n  const dc = new DrawContext();\n  dc.size = new Size(w, h);\n  dc.opaque = false;\n  dc.respectScreenScale = true;\n  const pts = s.hist.slice(-24);\n  const max = Math.max(160, ...pts.map((p) => p.v), ...pts.map((p) => p.avg || 0)) * 1.08;\n  const bw = w / Math.max(pts.length, 12);\n  const y = (v) => h - (v / max) * h;\n  for (const [v, label] of [[56, \"Elevated 56\"], [151, \"High 151\"]]) { // dashed, labelled band guides\n    for (let x = 0; x < w; x += 6) { dc.setFillColor(new Color(\"#8A8F98\", 0.5)); dc.fillRect(new Rect(x, y(v), 3, 0.7)); }\n    dc.setFont(Font.systemFont(7)); dc.setTextColor(new Color(\"#8A8F98\")); dc.drawText(label, new Point(w - 44, y(v) - 9));\n  }\n  pts.forEach((p, i) => {\n    dc.setFillColor(new Color(BANDS[bandOf(p.v)].color, 0.85));\n    const top = y(p.v);\n    dc.fillRect(new Rect(i * bw + bw * 0.15, top, bw * 0.7, h - top));\n  });\n  const path = new Path();\n  let started = false;\n  pts.forEach((p, i) => {\n    if (p.avg == null) return;\n    const pt = new Point(i * bw + bw / 2, y(p.avg));\n    if (!started) { path.move(pt); started = true; } else path.addLine(pt);\n  });\n  if (started) { dc.addPath(path); dc.setStrokeColor(new Color(\"#8A8F98\")); dc.setLineWidth(2); dc.strokePath(); }\n  return dc.getImage();\n}\n\n// ------------------------------------------------------------------ brand mark (brand/svg/mark-small-template.svg)\n// Small variant: dot + 2 haze lines on a 100×100 grid. The dot takes the band colour; the lines stay Mist.\nfunction markImage(band) {\n  const dc = new DrawContext();\n  dc.size = new Size(100, 100);\n  dc.opaque = false;\n  dc.respectScreenScale = true;\n  const mist = new Color(\"#9FB3BB\");\n  dc.setFillColor(band ? new Color(BANDS[band].color) : mist);\n  dc.fillEllipse(new Rect(28, 12, 44, 44)); // circle cx50 cy34 r22\n  const line = (x, y, w, alpha) => {\n    const p = new Path();\n    p.addRoundedRect(new Rect(x, y, w, 12), 6, 6);\n    dc.addPath(p);\n    dc.setFillColor(new Color(\"#9FB3BB\", alpha));\n    dc.fillPath();\n  };\n  line(12, 66, 76, 1);\n  line(30, 86, 40, 0.6);\n  return dc.getImage();\n}\nfunction header(w, band, muted) {\n  const h = w.addStack(); h.centerAlignContent();\n  const m = h.addImage(markImage(band)); m.imageSize = new Size(12, 12);\n  h.addSpacer(4);\n  txt(h, \"HazeNow\", 9, { ...muted, bold: true });\n  w.addSpacer(3);\n}\n\n// ------------------------------------------------------------------ widget\nconst FG = Color.dynamic(new Color(\"#1d232b\"), Color.white());\nfunction txt(stack, s, size, o = {}) {\n  const t = stack.addText(s);\n  t.font = o.bold ? Font.boldSystemFont(size) : Font.systemFont(size);\n  t.textColor = o.color || FG;\n  if (o.opacity) t.textOpacity = o.opacity;\n  t.lineLimit = o.lines || 1;\n  t.minimumScaleFactor = 0.6;\n  return t;\n}\nfunction chip(stack, band, size, trailing) { // icon + label, never colour alone\n  const row = stack.addStack(); row.centerAlignContent();\n  const img = row.addImage(SFSymbol.named(BANDS[band].sf).image);\n  img.imageSize = new Size(size, size); img.tintColor = new Color(BANDS[band].color);\n  row.addSpacer(3);\n  txt(row, `${BANDS[band].label}${trailing || \"\"}`, size, { bold: true });\n  return row;\n}\n\nfunction nextRefresh(s) { // SPEC v1.3: next hour's data lands ~hh:01 → ask for hh:02; if this hour is late, retry in 10 min\n  const now = new Date();\n  const next = new Date(now); next.setMinutes(2, 0, 0); if (next <= now) next.setHours(next.getHours() + 1);\n  const thisHour = new Date(now); thisHour.setMinutes(0, 0, 0);\n  const haveThisHour = s && Date.parse(s.observedAt) >= thisHour.getTime();\n  return haveThisHour ? next : new Date(now.getTime() + 10 * 60e3);\n}\n\nfunction build(s, family, p, offline) {\n  const b = BANDS[s.band];\n  const w = new ListWidget();\n  w.url = WEB;\n  w.refreshAfterDate = nextRefresh(s);\n  const [vLong, vShort] = V[s.band][p];\n\n  if (family === \"accessoryInline\") { txt(w, `${b.glyph} ${s.pm25} ${s.arrow} ${b.label}`, 12); return w; }\n  if (family === \"accessoryCircular\") {\n    w.addAccessoryWidgetBackground = true;\n    txt(w, `${s.pm25}`, 20, { bold: true }).centerAlignText();\n    txt(w, `${b.glyph} ${s.arrow}`, 11).centerAlignText();\n    return w;\n  }\n  if (family === \"accessoryRectangular\") {\n    txt(w, `● ${s.pm25} ${s.arrow} ${b.label}`, 14, { bold: true });\n    txt(w, vShort, 12);\n    txt(w, `${timeLabel(s.observedAt)} · NEA${offline ? \" · offline\" : \"\"}`, 10, { opacity: 0.7 });\n    return w;\n  }\n\n  const bg = Color.dynamic(new Color(\"#FFFFFF\"), new Color(\"#15191E\"));\n  const g = new LinearGradient(); g.colors = [new Color(b.color, 0.10), bg]; g.locations = [0, 1];\n  w.backgroundColor = bg; w.backgroundGradient = g;\n  w.setPadding(12, 14, 12, 14);\n  const muted = { opacity: 0.65 };\n\n  header(w, s.band, muted);\n  const main = w.addStack();\n  const left = main.addStack(); left.layoutVertically();\n  // 1. verdict first (short form on widgets, COPY §16)\n  txt(left, vShort, family === \"small\" ? 14 : 15, { bold: true, lines: 2 });\n  if (family !== \"small\") txt(left, FOR_LABEL[p], 10, muted);\n  left.addSpacer(2);\n  // 2. big number + chip\n  const n = left.addStack(); n.bottomAlignContent();\n  txt(n, num(s), family === \"small\" ? 36 : 40, { bold: true });\n  n.addSpacer(4);\n  txt(n, \"PM2.5\", 10, muted);\n  chip(left, s.band, 12, ` ${s.arrow}`);\n  left.addSpacer();\n  if (family !== \"small\") txt(left, trendPhrase(s.values).words, 10, { ...muted, lines: 2 });\n  txt(left, `${timeLabel(s.observedAt)} · NEA${offline ? \" · offline\" : s.stale ? \" (old)\" : \"\"}`, 10, muted);\n\n  if (family !== \"small\") {\n    main.addSpacer(10);\n    const right = main.addStack(); right.layoutVertically();\n    txt(right, \"Last 24 hours\", 10, { bold: true, ...muted });\n    const W = family === \"large\" ? 150 : 140, H = family === \"large\" ? 84 : 76;\n    const img = right.addImage(chartImage(s, W, H)); img.imageSize = new Size(W, H);\n    txt(right, s.spot.mode === \"gps\" ? `Bars: hourly PM2.5 ${s.place ? `in ${s.place}` : \"at your spot\"}` : \"Bars: hourly PM2.5\", 8, muted);\n    txt(right, \"Line: NEA 24-hr average PM2.5\", 8, muted);\n    txt(right, officialLine(s), 9, { ...muted, bold: true });\n  }\n\n  if (family === \"large\" || family === \"extraLarge\") {\n    w.addSpacer(8);\n    txt(w, vLong, 13, { bold: true, lines: 2 });\n    const sl = secondLine(s); if (sl) txt(w, sl, 11, { lines: 2 });\n    txt(w, ANCHOR[s.band], 10, muted);\n    const u = uncertainty(s); if (u) txt(w, u, 10, muted);\n    txt(w, provenance(s), 9, { ...muted, lines: 2 });\n    w.addSpacer(6);\n    for (const a of actionsFor(s.band, s.values, p)) txt(w, `• ${a}`, 11, { lines: 2 });\n    w.addSpacer(6);\n    const row = w.addStack();\n    for (const k of REGIONS) {\n      const v = s.regions[k];\n      const cell = row.addStack(); cell.layoutVertically();\n      txt(cell, title(k), 9, muted);\n      txt(cell, v == null ? \"offline\" : `${BANDS[bandOf(v)].glyph} ${v}`, 11, { bold: true });\n      row.addSpacer();\n    }\n    w.addSpacer(4);\n    txt(w, `${WHY_SHORT} ${FOOTER}`, 8, { ...muted, lines: 3 });\n  }\n  return w;\n}\n\nfunction shareText(s) { // COPY §15 (no verdict)\n  const tw = trendPhrase(s.values).word || \"steady\";\n  return `Air near me right now: ${BANDS[s.band].label} (PM2.5 ${s.pm25}), ${tw}. NEA 24-hr PSI: ${s.officialPsi24h ?? \"not available\"}. Data: NEA via data.gov.sg. ${WEB}`;\n}\n\n// ------------------------------------------------------------------ main\n// Parameter: comma-separated parts, each a profile, a region, or an area name (\"Tampines\", \"Ang Mo Kio\").\n// A part with spaces that isn't an area is read word by word, so \"west kids\" still works.\nlet profile = \"general\", region = null, area = null;\nfor (const part of String(args.widgetParameter || args.shortcutParameter || \"\").toLowerCase().split(\",\").map((x) => x.trim()).filter(Boolean)) {\n  const one = (w) => (PROFILES.includes(w) ? ((profile = w), true) : REGIONS.includes(w) || w === \"island\" ? ((region = w), true) : false);\n  if (one(part)) continue;\n  const a = findArea(part);\n  if (a) { area = a; continue; }\n  for (const w of part.split(/\\s+/)) if (!one(w)) { const b = findArea(w); if (b) area = b; }\n}\nlet loc = area ? area.loc : null;\nif (!area && !region) {\n  try {\n    Location.setAccuracyToThreeKilometers();\n    const l = await Location.current();\n    loc = [l.latitude, l.longitude];\n  } catch (e) { loc = null; } // not allowed → Singapore island\n}\nregion = region || \"island\";\n\nlet raw, offline = false;\ntry { raw = await loadRaw(); } catch (e) { raw = readCache(\"last\"); offline = true; }\n\nlet widget, s = null;\nif (!raw) {\n  widget = new ListWidget();\n  header(widget, null, { opacity: 0.65 }); // no data → neutral mark, no band colour\n  txt(widget, \"Can't reach NEA's data right now\", 13, { bold: true, lines: 2 });\n  txt(widget, \"We'll try again in a few minutes.\", 11, { lines: 2 });\n  widget.refreshAfterDate = new Date(Date.now() + 10 * 60e3);\n} else {\n  s = snapshot(raw, region, loc);\n  if (area) s.place = area.name;\n  widget = build(s, config.widgetFamily || \"medium\", profile, offline);\n  if (!config.runsInWidget) Script.setShortcutOutput(`${V[s.band][profile][0]} ${shareText(s)}`);\n}\n\nif (config.runsInWidget || config.runsInAccessoryWidget) Script.setWidget(widget);\nelse if (config.runsWithSiri) Speech.speak(s ? `${V[s.band][profile][0]} PM2.5 ${s.pm25}, ${BANDS[s.band].label}.` : \"Can't reach NEA's data right now.\");\nelse await widget.presentMedium();\nScript.complete();\n",
  "share_sheet_inputs": []
}
