/* B1 Meister – Service Worker für tägliche Lern-Erinnerungen */ const STATE_CACHE = "b1meister-state"; const STATE_URL = "/__b1meister_state__"; self.addEventListener("install", () => self.skipWaiting()); self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim())); function today() { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; } async function readState() { try { const cache = await caches.open(STATE_CACHE); const res = await cache.match(STATE_URL); return res ? await res.json() : null; } catch { return null; } } async function writeState(s) { const cache = await caches.open(STATE_CACHE); await cache.put(STATE_URL, new Response(JSON.stringify(s), { headers: { "content-type": "application/json" } })); } self.addEventListener("message", (e) => { if (e.data && e.data.type === "state") { const { lastStudy, reminder, streak } = e.data; e.waitUntil(readState().then((old) => writeState({ ...(old || {}), lastStudy, reminder, streak }))); } }); async function maybeRemind() { const s = await readState(); if (!s || !s.reminder || !s.reminder.enabled) return; const t = today(); if (s.lastStudy === t || s.shown === t) return; const [h, m] = String(s.reminder.time || "19:00").split(":").map(Number); const now = new Date(); if (now.getHours() * 60 + now.getMinutes() < h * 60 + m) return; await self.registration.showNotification("Zeit für Deutsch! 🇦🇹", { body: (s.streak > 0 ? `🔥 ${s.streak} Tage Serie – nicht aufhören! ` : "") + "Nur 10 Minuten für deine B1-Prüfung. • عشر دقائق فقط لامتحانك!", icon: "/icon.svg", badge: "/icon.svg", tag: "daily-reminder", }); await writeState({ ...s, shown: t }); } self.addEventListener("periodicsync", (e) => { if (e.tag === "daily-reminder") e.waitUntil(maybeRemind()); }); self.addEventListener("notificationclick", (e) => { e.notification.close(); e.waitUntil( self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((list) => { for (const c of list) { if ("focus" in c) return c.focus(); } return self.clients.openWindow("/"); }), ); });