{"always_run_in_app":false,"icon":{"color":"deep-purple","glyph":"magic"},"name":"Roni Tracker","script":"// Variables used by Scriptable.\n// These must be at the very top of the file. Do not edit.\n// icon-color: deep-purple; icon-glyph: magic;\n// Roni Tracker for Scriptable. This script makes GET requests only.\nconst API_URL = \"https://go-portal.duckdns.org/parents/api/widget\";\nconst CACHE_FILE = \"roni-widget-cache.json\";\nconst fm = FileManager.local();\nconst cachePath = fm.joinPath(fm.documentsDirectory(), CACHE_FILE);\n\nfunction color(light, dark) { return Color.dynamic(new Color(light), new Color(dark)); }\nconst palette = {\n  bg: color(\"#F7F4EE\", \"#182230\"), card: color(\"#FFFFFF\", \"#243244\"),\n  text: color(\"#18283A\", \"#F4F3EF\"), muted: color(\"#7C8792\", \"#AAB4BE\"),\n  feed: color(\"#D87959\", \"#F09A78\"), sleep: color(\"#7785C8\", \"#A5B0F0\"),\n  diaper: color(\"#58A99A\", \"#79C8B8\"), line: color(\"#E9E5DE\", \"#39485A\"),\n};\n\nfunction hebrewNumber(n) { return String(Math.max(0, Math.floor(n))); }\nfunction relative(iso, now = Date.now()) {\n  if (!iso) return \"\";\n  const ms = Math.max(0, now - new Date(iso).getTime());\n  if (!Number.isFinite(ms)) return \"\";\n  const total = Math.floor(ms / 60000), h = Math.floor(total / 60), m = total % 60;\n  if (h) return `לפני ${hebrewNumber(h)} ש׳${m ? ` ${hebrewNumber(m)} ד׳` : \"\"}`;\n  return `לפני ${hebrewNumber(m)} ד׳`;\n}\nfunction duration(minutes) {\n  if (minutes == null || !Number.isFinite(Number(minutes))) return \"\";\n  const m = Math.max(0, Math.floor(Number(minutes))), h = Math.floor(m / 60), r = m % 60;\n  return h ? `${h}:${String(r).padStart(2, \"0\")}` : `${r} ד׳`;\n}\nfunction clockDuration(minutes) {\n  if (minutes == null || !Number.isFinite(Number(minutes))) return \"—\";\n  const m = Math.max(0, Math.floor(Number(minutes))), h = Math.floor(m / 60), r = m % 60;\n  return `${h}:${String(r).padStart(2, \"0\")}`;\n}\nfunction sideHebrew(value) {\n  const v = String(value || \"\").toLowerCase();\n  if (v === \"left\" || v === \"שמאל\") return \"שמאל\";\n  if (v === \"right\" || v === \"ימין\") return \"ימין\";\n  if (v === \"both\" || v === \"שניהם\") return \"שניהם\";\n  return \"\";\n}\nfunction titleFor(snapshot) { return snapshot?.child?.name || \"רוני\"; }\nfunction snapshotOf(data) { return data && data.snapshot ? data.snapshot : data; }\nfunction validData(data) { return !!snapshotOf(data) && typeof snapshotOf(data) === \"object\"; }\n\nasync function request(url) {\n  const req = new Request(url);\n  req.method = \"GET\";\n  req.timeoutInterval = 12;\n  const raw = await req.loadString();\n  const status = req.response?.statusCode || 200;\n  if (status < 200 || status >= 300) throw new Error(\"request failed\");\n  let body = null;\n  try { body = JSON.parse(raw); } catch (_) {}\n  return { body, status };\n}\n\nfunction writeCache(data) { try { fm.writeString(cachePath, JSON.stringify({ savedAt: new Date().toISOString(), data })); } catch (_) {} }\nfunction readCache() { try { return JSON.parse(fm.readString(cachePath)); } catch (_) { return null; } }\n\nfunction addText(stack, text, size, tint = palette.text, bold = false) {\n  const t = stack.addText(String(text)); t.font = bold ? Font.boldSystemFont(size) : Font.systemFont(size); t.textColor = tint; t.lineLimit = 1; t.minimumScaleFactor = 1; t.rightAlignText(); return t;\n}\nfunction feedAge(s, now) {\n  const f = s.feeding || {};\n  if (!f.lastFeedingAt) return \"—\";\n  const minutes = (now - new Date(f.lastFeedingAt).getTime()) / 60000;\n  return Number.isFinite(minutes) ? clockDuration(minutes) : \"—\";\n}\nfunction sleepLine(s, now) {\n  const sl = s.sleep || {};\n  if (sl.isSleeping && sl.startedAt) return `ישנה ${clockDuration((now - new Date(sl.startedAt).getTime()) / 60000)}`;\n  if (sl.lastSleepEndedAt) return `שינה אחרונה ${clockDuration(sl.lastSleepDurationMinutes)}`;\n  return \"שינה · אין רישום\";\n}\nfunction addHeader(w, snapshot, offlineLabel) {\n  const head = w.addStack(); head.layoutHorizontally(); head.centerAlignContent();\n  addText(head, titleFor(snapshot), 14, palette.text, true);\n  const glyph = head.addText(\"●\"); glyph.font = Font.boldSystemFont(11); glyph.textColor = palette.feed;\n  head.addSpacer();\n  if (offlineLabel) addText(head, `◦ ${offlineLabel}`, 11, palette.muted);\n}\nfunction addFeedHero(parent, s, now) {\n  const f = s.feeding || {}, age = feedAge(s, now), side = sideHebrew(f.side || f.type);\n  const hero = parent.addStack(); hero.layoutVertically(); hero.spacing = 2;\n  const number = addText(hero, age, 30, palette.feed, true); number.font = Font.boldRoundedSystemFont(30);\n  const caption = [\"מאז האכלה\", side, f.amountMl != null ? `${f.amountMl} מ״ל` : \"\"].filter(Boolean).join(\" · \");\n  addText(hero, caption, 11, palette.muted, true);\n}\nfunction addStatusLine(parent, text, tint) {\n  const row = parent.addStack(); row.layoutHorizontally(); row.centerAlignContent(); row.spacing = 6;\n  const dot = row.addText(\"●\"); dot.font = Font.boldSystemFont(11); dot.textColor = tint;\n  addText(row, text, 13, palette.text, true);\n}\nfunction addDiaperLine(parent, s, now) {\n  const d = s.diaper;\n  if (!d || !d.lastAt) return;\n  const kind = d.kind === \"wet\" ? \"רטוב\" : d.kind === \"dirty\" ? \"קקי\" : d.kind === \"both\" ? \"רטוב וקקי\" : (d.kind || \"\");\n  const age = relative(d.lastAt, now).replace(/^לפני /, \"\");\n  addStatusLine(parent, [\"חיתול\", kind, age].filter(Boolean).join(\" · \"), palette.diaper);\n}\nfunction addTotals(parent, s) {\n  const t = s.today || {}, bits = [];\n  if (t.feeds != null) bits.push(`${t.feeds} האכלות`);\n  if (t.naps != null) bits.push(`${t.naps} תנומות`);\n  if (t.sleepMinutes != null) bits.push(`${(Number(t.sleepMinutes) / 60).toFixed(1)} שע׳ שינה`);\n  if (t.diapers != null) bits.push(`${t.diapers} חיתולים`);\n  if (bits.length) {\n    const chips = parent.addStack(); chips.layoutHorizontally(); chips.centerAlignContent(); chips.spacing = 5;\n    for (const bit of bits) {\n      const chip = chips.addStack(); chip.backgroundColor = palette.card; chip.cornerRadius = 10; chip.setPadding(4, 7, 4, 7);\n      addText(chip, bit, 11, palette.muted, true);\n    }\n  }\n}\nfunction widget(s, offlineLabel = \"\") {\n  const w = new ListWidget(); w.backgroundColor = palette.bg; w.setPadding(14, 15, 13, 15); w.url = \"https://go-portal.duckdns.org/parents/\";\n  const now = Date.now();\n  const family = config.widgetFamily || \"medium\";\n  if (family.startsWith(\"accessory\")) {\n    const sl = s.sleep || {}, f = s.feeding || {}, sleep = sleepLine(s, now);\n    if (family === \"accessoryInline\") {\n      const inline = w.addText(`${offlineLabel ? `${offlineLabel} · ` : \"\"}🍼 ${feedAge(s, now)} · 😴 ${sleep.replace(\"ישנה \", \"\").replace(\"שינה אחרונה \", \"\")}`); inline.font = Font.mediumSystemFont(12); inline.textColor = palette.text; inline.lineLimit = 1; inline.minimumScaleFactor = 1;\n    } else if (family === \"accessoryCircular\") {\n      const image = w.addImage(SFSymbol.named(sl.isSleeping ? \"moon.zzz.fill\" : \"drop.fill\").image);\n      image.tintColor = sl.isSleeping ? palette.sleep : palette.feed; image.imageSize = new Size(22, 22); image.centerAlignImage();\n      const label = w.addText(sl.isSleeping ? clockDuration((now - new Date(sl.startedAt).getTime()) / 60000) : feedAge(s, now));\n      label.font = Font.systemFont(11); label.textColor = palette.text; label.centerAlignText();\n      if (offlineLabel) { const status = w.addText(offlineLabel); status.font = Font.systemFont(7); status.textColor = palette.muted; status.centerAlignText(); }\n    } else {\n      if (offlineLabel) addText(w, offlineLabel, 10, palette.muted, true);\n      addText(w, [\"האכלה\", `לפני ${feedAge(s, now)}`, sideHebrew(f.side || f.type)].filter(Boolean).join(\" · \"), 12, palette.feed, true); w.addSpacer(3);\n      addText(w, sleep, 12, palette.sleep, true);\n    }\n    return w;\n  }\n  addHeader(w, s, offlineLabel);\n  w.addSpacer(8);\n  if (family === \"small\") {\n    addFeedHero(w, s, now); w.addSpacer(7);\n    addStatusLine(w, sleepLine(s, now), palette.sleep); addDiaperLine(w, s, now);\n  } else {\n    const columns = w.addStack(); columns.layoutHorizontally(); columns.centerAlignContent();\n    const status = columns.addStack(); status.layoutVertically(); status.spacing = 8;\n    addStatusLine(status, sleepLine(s, now), palette.sleep); addDiaperLine(status, s, now);\n    columns.addSpacer();\n    const feed = columns.addStack(); feed.layoutVertically(); addFeedHero(feed, s, now);\n    w.addSpacer(8); const div = w.addStack(); div.size = new Size(0, 1); div.backgroundColor = palette.line; w.addSpacer(6); addTotals(w, s);\n  }\n  return w;\n}\nfunction errorWidget() { const w = new ListWidget(); w.backgroundColor = palette.bg; w.setPadding(14, 15, 13, 15); w.url = \"https://go-portal.duckdns.org/parents/\"; w.refreshAfterDate = new Date(Date.now() + 10 * 60 * 1000); addText(w, \"אין חיבור\", 14, palette.text, true); return w; }\n\nasync function run() {\n  let data = null, offlineLabel = \"\";\n  try {\n    const result = await request(API_URL);\n    if (!validData(result.body)) throw new Error(\"invalid payload\");\n    data = result.body; writeCache(data);\n  } catch (_) {\n    const cached = readCache();\n    if (cached && validData(cached.data)) {\n      data = cached.data;\n      offlineLabel = `אין חיבור · עודכן ${relative(cached.savedAt)}`;\n    } else {\n      const w = errorWidget(); if (config.runsInWidget) Script.setWidget(w); else await w.presentMedium(); Script.complete(); return;\n    }\n  }\n  const w = widget(snapshotOf(data), offlineLabel); w.refreshAfterDate = new Date(Date.now() + 10 * 60 * 1000);\n  if (config.runsInWidget) Script.setWidget(w);\n  else await w.presentMedium();\n  Script.complete();\n}\n\nawait run();\n"}