import { useEffect, useRef, useState } from "react" import { Pill, Check, Clock, SkipForward, X } from "lucide-react" import { getToday, respondDose } from "../api" import { useAuth } from "../auth/AuthContext" import { useI18n } from "../i18n/I18nContext" // In-app "alarm": polls today's doses and pops a modal (with a beep) when a // dose becomes due. Works on every authenticated page (mounted in AppShell). const POLL_MS = 30000 function beep() { try { const Ctx = window.AudioContext || window.webkitAudioContext if (!Ctx) return const ctx = new Ctx() const play = (freq, start) => { const o = ctx.createOscillator(); const g = ctx.createGain() o.connect(g); g.connect(ctx.destination) o.type = "sine"; o.frequency.value = freq g.gain.setValueAtTime(0.0001, ctx.currentTime + start) g.gain.exponentialRampToValueAtTime(0.25, ctx.currentTime + start + 0.05) g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + start + 0.5) o.start(ctx.currentTime + start); o.stop(ctx.currentTime + start + 0.55) } play(880, 0); play(660, 0.3); play(880, 0.6) } catch { /* autoplay may be blocked; ignore */ } } export default function DoseReminder() { const { isAuthenticated } = useAuth() const { t } = useI18n() const [active, setActive] = useState(null) // the due dose to show const alarmed = useRef(new Set()) // dose ids already alarmed this session const isDue = (d) => { if (d.status !== "pending") return false const [h, m] = d.time.split(":").map(Number) const due = new Date(); due.setHours(h, m, 0, 0) return due.getTime() <= Date.now() } useEffect(() => { if (!isAuthenticated) return let stop = false const check = async () => { try { const doses = await getToday() if (stop) return const due = doses.find((d) => isDue(d) && !alarmed.current.has(d.id)) if (due && !active) { alarmed.current.add(due.id) beep() setActive(due) } } catch { /* ignore */ } } check() const id = setInterval(check, POLL_MS) return () => { stop = true; clearInterval(id) } }, [isAuthenticated, active]) const act = async (action) => { if (!active) return try { await respondDose(active.id, action) } catch { /* ignore */ } setActive(null) window.dispatchEvent(new CustomEvent("doses-changed")) } if (!active) return null return (