"use client"; import { useState, useEffect } from "react"; import { useAuth } from "@/hooks/use-auth"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useRouter } from "next/navigation"; import Link from "next/link"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Badge } from "@/components/ui/badge"; import { Switch } from "@/components/ui/switch"; import { KeyRound, Bell, BellRing, Loader2, MessageCircle, Save, Send, Shield, Key, Trash2, Link2, Unlink, RefreshCw, Download, Sparkles, AlertTriangle, ChevronDown, Eye, EyeOff, User, Smile, } from "lucide-react"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { formatDate, formatDateTime } from "@/lib/format"; import { useTranslations } from "@/lib/i18n/context"; import { locales, localeLabels, type Locale } from "@/lib/i18n/config"; import { invalidateKeys, measurementDependentKeys } from "@/lib/query-keys"; import { describePasskeyError } from "@/lib/passkey-errors"; import { ThresholdsSection } from "@/components/settings/thresholds-section"; import { DashboardLayoutSection } from "@/components/settings/dashboard-layout-section"; function PasswordInput(props: React.ComponentProps) { const [visible, setVisible] = useState(false); return (
); } interface GlobalServiceAvailability { telegramGlobal: boolean; ntfyGlobal: boolean; webPushGlobal: boolean; apiGlobal: boolean; moodLogGlobal: boolean; } export default function SettingsPage() { const { user, isLoading, isAuthenticated, refetch } = useAuth(); const { t, locale, setLocale } = useTranslations(); const queryClient = useQueryClient(); const router = useRouter(); const [email, setEmail] = useState(""); const [heightCm, setHeightCm] = useState(""); const [dateOfBirth, setDateOfBirth] = useState(""); const [gender, setGender] = useState(""); const [saving, setSaving] = useState(false); const [saveMsg, setSaveMsg] = useState(null); const [saveMsgType, setSaveMsgType] = useState<"success" | "error" | null>( null, ); const [currentPassword, setCurrentPassword] = useState(""); const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [passwordSaving, setPasswordSaving] = useState(false); const [passwordMsg, setPasswordMsg] = useState(null); const [passwordMsgType, setPasswordMsgType] = useState< "success" | "error" | null >(null); const [passwordDialogOpen, setPasswordDialogOpen] = useState(false); const [passkeyLoading, setPasskeyLoading] = useState(false); const [passkeyMsg, setPasskeyMsg] = useState(null); const [passkeyMsgType, setPasskeyMsgType] = useState< "success" | "error" | null >(null); const { data: globalServices } = useQuery({ queryKey: ["settings", "global-services"], queryFn: async () => { const res = await fetch("/api/settings/global-services"); if (!res.ok) throw new Error("Failed"); return (await res.json()).data as GlobalServiceAvailability; }, enabled: isAuthenticated, }); useEffect(() => { if (!isLoading && !isAuthenticated) { router.push("/auth/login"); } }, [isLoading, isAuthenticated, router]); useEffect(() => { if (user) { setEmail(user.email ?? ""); setHeightCm(user.heightCm?.toString() ?? ""); setDateOfBirth( user.dateOfBirth ? new Date(user.dateOfBirth).toISOString().slice(0, 10) : "", ); setGender(user.gender ?? ""); } }, [user]); async function handleSaveProfile(e: React.FormEvent) { e.preventDefault(); setSaving(true); setSaveMsg(null); setSaveMsgType(null); const res = await fetch("/api/auth/profile", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: email.trim() || null, heightCm: heightCm ? parseFloat(heightCm) : null, dateOfBirth: dateOfBirth || null, gender: gender || null, }), }); if (res.ok) { setSaveMsg(t("settings.profileSaved")); setSaveMsgType("success"); await refetch(); } else { const json = await res.json(); setSaveMsg(json.error || t("settings.savingError")); setSaveMsgType("error"); } setSaving(false); } async function handleAddPasskey() { setPasskeyLoading(true); setPasskeyMsg(null); setPasskeyMsgType(null); try { const optRes = await fetch("/api/auth/passkey/register-options", { method: "POST", }); if (!optRes.ok) { setPasskeyMsg(t("settings.passkeyOptionsError")); setPasskeyMsgType("error"); setPasskeyLoading(false); return; } const optJson = await optRes.json(); const { options, challengeId } = optJson.data; const { startRegistration } = await import("@simplewebauthn/browser"); const credential = await startRegistration({ optionsJSON: options }); const verifyRes = await fetch("/api/auth/passkey/register-verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ challengeId, credential }), }); if (verifyRes.ok) { setPasskeyMsg(t("settings.passkeyAdded")); setPasskeyMsgType("success"); queryClient.invalidateQueries({ queryKey: ["passkeys"] }); } else { const verifyJson = await verifyRes.json(); setPasskeyMsg( verifyJson.error || t("settings.passkeyRegistrationFailed"), ); setPasskeyMsgType("error"); } } catch (err) { const { key, params } = describePasskeyError(err); setPasskeyMsg(t(key, params)); setPasskeyMsgType("error"); } finally { setPasskeyLoading(false); } } async function handleChangePassword(e: React.FormEvent) { e.preventDefault(); setPasswordSaving(true); setPasswordMsg(null); setPasswordMsgType(null); if (newPassword !== confirmPassword) { setPasswordMsg(t("settings.passwordMismatch")); setPasswordMsgType("error"); setPasswordSaving(false); return; } try { const res = await fetch("/api/auth/password", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ currentPassword, newPassword, confirmPassword, }), }); const json = await res.json(); if (!res.ok) { setPasswordMsg(json.error || t("settings.savingError")); setPasswordMsgType("error"); return; } setPasswordMsg(t("settings.passwordUpdated")); setPasswordMsgType("success"); setCurrentPassword(""); setNewPassword(""); setConfirmPassword(""); } catch { setPasswordMsg(t("common.networkError")); setPasswordMsgType("error"); } finally { setPasswordSaving(false); } } if (isLoading) { return (
); } if (!user) return null; const serviceAvailability: GlobalServiceAvailability = { telegramGlobal: globalServices?.telegramGlobal ?? true, ntfyGlobal: globalServices?.ntfyGlobal ?? true, webPushGlobal: globalServices?.webPushGlobal ?? true, apiGlobal: globalServices?.apiGlobal ?? true, moodLogGlobal: globalServices?.moodLogGlobal ?? true, }; const hasNotificationServices = serviceAvailability.telegramGlobal || serviceAvailability.ntfyGlobal || serviceAvailability.webPushGlobal; return (

{t("settings.title")}

{t("settings.subtitle")}

{user.role === "ADMIN" && (

{t("settings.adminAreaTitle")}

{t("settings.adminAreaDescription")}

)}

{t("settings.categoryGeneral")}

{/* Profile Section */}

{t("settings.profile")}

setEmail(e.target.value)} placeholder={t("auth.emailPlaceholder")} maxLength={320} />

{t("settings.genderHint")}

setHeightCm(e.target.value)} placeholder="175" min={50} max={300} step={0.1} />
setDateOfBirth(e.target.value)} max={new Date().toISOString().slice(0, 10)} />

{t("settings.dateOfBirthHint")}

{t("settings.languageDescription")}

{saveMsg && (

{saveMsg}

)}

{t("settings.security")}

{t("settings.passkeys")}

{passkeyMsg && (

{passkeyMsg}

)}

{t("settings.passwordReset")}

{t("settings.changePasswordDescription")}

{ setPasswordDialogOpen(open); if (!open) { setCurrentPassword(""); setNewPassword(""); setConfirmPassword(""); setPasswordMsg(null); setPasswordMsgType(null); } }} > {t("settings.passwordReset")} {t("settings.changePasswordDescription")}
setCurrentPassword(e.target.value)} />
setNewPassword(e.target.value)} />
setConfirmPassword(e.target.value)} />
{passwordMsg && (

{passwordMsg}

)}
{hasNotificationServices && (

{t("settings.categoryNotifications")}

{serviceAvailability.telegramGlobal && ( )} {serviceAvailability.ntfyGlobal && ( )} {serviceAvailability.webPushGlobal && ( )}
)}

{t("settings.categoryPersonalization")}

{t("settings.categoryIntegration")}

{serviceAvailability.moodLogGlobal !== false && }
{serviceAvailability.apiGlobal && (

{t("settings.categoryApi")}

)}

{t("settings.export")}

{t("settings.dangerZoneTitle")}

); } /* ─────────────────────── Passkey List ─────────────────────── */ interface PasskeyInfo { id: string; name: string; credentialDeviceType: string; credentialBackedUp: boolean; createdAt: string; } function PasskeyListSection({ isAuthenticated }: { isAuthenticated: boolean }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const [deleteMsg, setDeleteMsg] = useState(null); const { data: passkeys } = useQuery({ queryKey: ["passkeys"], queryFn: async () => { const res = await fetch("/api/auth/passkeys"); if (!res.ok) throw new Error("Failed"); return (await res.json()).data as PasskeyInfo[]; }, enabled: isAuthenticated, }); const deletePasskey = useMutation({ mutationFn: async (id: string) => { const res = await fetch(`/api/auth/passkeys/${id}`, { method: "DELETE", }); const json = await res.json(); if (!res.ok) throw new Error(json.error || t("common.error")); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["passkeys"] }); setDeleteMsg(null); }, onError: (err: Error) => { setDeleteMsg(err.message); }, }); const DEVICE_TYPE_LABELS: Record = { singleDevice: t("settings.singleDevice"), multiDevice: t("settings.multiDevice"), }; if (!passkeys || passkeys.length === 0) { return (

{t("settings.passkeys")}

{t("settings.noPasskeys")}

); } return (

{t("settings.registeredPasskeys")}

{t("settings.passkeysDescription")}

{passkeys.map((pk, idx) => ( ))}
{t("settings.passkeyName")} {t("settings.passkeyDevice")} {t("settings.passkeyBackup")} {t("settings.passkeyCreated")} {t("settings.passkeyActions")}
{pk.name} {DEVICE_TYPE_LABELS[pk.credentialDeviceType] ?? pk.credentialDeviceType} {pk.credentialBackedUp ? t("settings.backedUp") : t("common.no")} {formatDate(pk.createdAt)} {t("settings.deletePasskey")} {t("settings.deletePasskeyDescription")} {t("common.cancel")} deletePasskey.mutate(pk.id)} > {t("common.delete")}
{deleteMsg && (
{deleteMsg}
)}
); } /* ─────────────────────── Withings Integration ─────────────────────── */ function WithingsSection({ id, isAuthenticated, }: { id: string; isAuthenticated: boolean; }) { const { t } = useTranslations(); const [syncing, setSyncing] = useState(false); const [syncMsg, setSyncMsg] = useState(null); const [syncMsgType, setSyncMsgType] = useState<"success" | "error" | null>( null, ); const [clientId, setClientId] = useState(""); const [clientSecret, setClientSecret] = useState(""); const [credsSaving, setCredsSaving] = useState(false); const [credsMsg, setCredsMsg] = useState(null); const [credsMsgType, setCredsMsgType] = useState<"success" | "error" | null>( null, ); const queryClient = useQueryClient(); const { data: status } = useQuery({ queryKey: ["withings", "status"], queryFn: async () => { const res = await fetch("/api/withings/status"); if (!res.ok) throw new Error("Failed"); const json = await res.json(); return json.data as { connected: boolean; configured: boolean; lastSyncedAt?: string | null; connectedAt?: string; tokenExpired?: boolean; }; }, enabled: isAuthenticated, }); const disconnect = useMutation({ mutationFn: async () => { const res = await fetch("/api/withings/disconnect", { method: "POST" }); if (!res.ok) throw new Error("Failed"); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["withings"] }); }, }); async function handleSync(fullSync = false) { setSyncing(true); setSyncMsg(null); setSyncMsgType(null); try { const res = await fetch("/api/withings/sync", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fullSync }), }); const json = await res.json(); if (res.ok) { setSyncMsg( fullSync ? t("settings.withingsFullSyncResult", { count: json.data.imported, }) : t("settings.withingsSyncResult", { count: json.data.imported }), ); setSyncMsgType("success"); void invalidateKeys(queryClient, measurementDependentKeys); } else { setSyncMsg(json.error || t("settings.withingsSyncFailed")); setSyncMsgType("error"); } } catch { setSyncMsg(t("settings.withingsSyncFailed")); setSyncMsgType("error"); } finally { setSyncing(false); } } async function handleSaveCredentials(e: React.FormEvent) { e.preventDefault(); setCredsSaving(true); setCredsMsg(null); setCredsMsgType(null); try { const res = await fetch("/api/withings/credentials", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ clientId: clientId.trim(), clientSecret: clientSecret.trim(), }), }); if (res.ok) { setCredsMsg(t("settings.withingsCredentialsSaved")); setCredsMsgType("success"); setClientId(""); setClientSecret(""); queryClient.invalidateQueries({ queryKey: ["withings"] }); } else { try { const json = await res.json(); setCredsMsg(json.error || t("settings.savingError")); } catch { setCredsMsg(t("settings.savingError")); } setCredsMsgType("error"); } } catch { setCredsMsg(t("common.networkError")); setCredsMsgType("error"); } setCredsSaving(false); } return (

{t("settings.withings")}

{status?.configured && !status?.connected && ( {t("settings.configured")} )} {status?.connected && ( {t("settings.withingsConnected")} )} {status?.lastSyncedAt && ( {t("settings.withingsLastSync")}:{" "} {formatDateTime(status.lastSyncedAt)} )} {status?.tokenExpired && ( {t("settings.withingsTokenExpired")} )}

{t("settings.withingsDescription")}

{/* Credentials section */}

{t("settings.withingsCredentials")}

setClientId(e.target.value)} placeholder={ status?.configured ? t("settings.withingsCredentialsSavedPlaceholder") : t("settings.withingsClientId") } maxLength={200} />
setClientSecret(e.target.value)} placeholder={ status?.configured ? t("settings.withingsCredentialsSavedPlaceholderSecret") : t("settings.withingsClientSecret") } maxLength={200} />
{credsMsg && (

{credsMsg}

)}
{/* Connection status */} {status?.connected ? ( <>
{t("settings.withingsFullSyncTitle")} {t("settings.withingsFullSyncDescription")} {t("common.cancel")} handleSync(true)}> {t("settings.withingsSynchronize")} {t("settings.withingsDisconnectTitle")} {t("settings.withingsDisconnectDescription")} {t("common.cancel")} disconnect.mutate()} > {t("settings.withingsDisconnect")}
{syncMsg && (

{syncMsg}

)} ) : status?.configured ? ( ) : (
{t("settings.withingsNoCredentials")}
)}
); } /* ─────────────────────── API Tokens Section ─────────────────────── */ function ApiEndpointsSection({ id }: { id: string }) { const { t } = useTranslations(); return (

{t("settings.apiEndpointsTitle")}

{t("settings.apiEndpointsDescription")}

{t("settings.apiEndpointMethod")} {t("settings.apiEndpointPath")} {t("settings.apiEndpointAuth")} {t("settings.apiEndpointExample")}
POST /api/ingest/medication Authorization: Bearer hlk_... {`{ "medicationName": "...", "scheduledFor": "..." }`}
); } interface ApiTokenInfo { id: string; name: string; permissions: string[]; lastUsedAt: string | null; expiresAt: string | null; createdAt: string; revoked: boolean; } function ApiTokensSection({ id, isAuthenticated, }: { id: string; isAuthenticated: boolean; }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const [newName, setNewName] = useState(""); const [newToken, setNewToken] = useState(null); const [creating, setCreating] = useState(false); const [tokenMsg, setTokenMsg] = useState(null); const [showRevokedTokens, setShowRevokedTokens] = useState(false); const { data: tokens } = useQuery({ queryKey: ["tokens"], queryFn: async () => { const res = await fetch("/api/tokens"); if (!res.ok) throw new Error("Failed"); return (await res.json()).data as ApiTokenInfo[]; }, enabled: isAuthenticated, }); async function handleCreate(e: React.FormEvent) { e.preventDefault(); setCreating(true); setTokenMsg(null); setNewToken(null); try { const res = await fetch("/api/tokens", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: newName.trim() }), }); const json = await res.json(); if (res.ok) { setNewToken(json.data.token); setNewName(""); queryClient.invalidateQueries({ queryKey: ["tokens"] }); } else { setTokenMsg(json.error || t("common.error")); } } catch { setTokenMsg(t("common.networkError")); } finally { setCreating(false); } } async function handleRevoke(tokenId: string) { const res = await fetch(`/api/tokens/${tokenId}`, { method: "DELETE" }); if (res.ok) { queryClient.invalidateQueries({ queryKey: ["tokens"] }); } } const activeTokens = (tokens ?? []).filter((tok) => !tok.revoked); const revokedTokens = (tokens ?? []).filter((tok) => tok.revoked); const latestActiveUse = activeTokens.reduce((latest, tok) => { if (!tok.lastUsedAt) return latest; if (!latest || new Date(tok.lastUsedAt) > new Date(latest)) { return tok.lastUsedAt; } return latest; }, null); return (

{t("settings.apiTokens")}

{activeTokens.length > 0 && ( {t("settings.configured")} )} {latestActiveUse && ( {t("settings.tokenTableLastUsed")}: {formatDateTime(latestActiveUse)} )}

{t("settings.apiTokensDescription")}

{/* Create new token */}
setNewName(e.target.value)} placeholder={t("settings.tokenNamePlaceholder")} maxLength={100} className="flex-1" />
{/* New token display */} {newToken && (

{t("settings.tokenCreated")}

{newToken}
)} {tokenMsg &&

{tokenMsg}

} {/* Token table (active) */}

{t("settings.activeTokensTitle")}

{activeTokens.length === 0 && ( )} {activeTokens.map((tok, index) => { const isExpired = tok.expiresAt && new Date(tok.expiresAt) < new Date(); return ( ); })}
{t("settings.tokenTableName")} {t("settings.tokenTablePermissions")} {t("settings.tokenTableStatus")} {t("settings.tokenTableCreated")} {t("settings.tokenTableLastUsed")} {t("settings.tokenTableActions")}
{t("settings.noActiveTokens")}
{tok.name} {tok.permissions.join(", ")} {isExpired ? ( {t("settings.tokenExpired")} ) : ( {t("settings.tokenActive")} )} {formatDate(tok.createdAt)} {tok.lastUsedAt ? formatDateTime(tok.lastUsedAt) : t("settings.tokenNeverUsed")} {t("settings.tokenRevoke")} {t("settings.tokenRevokeDescription")} {t("common.cancel")} handleRevoke(tok.id)} > {t("settings.tokenRevoked")}
{/* Revoked tokens (collapsible, separate table) */} {revokedTokens.length > 0 && (
{showRevokedTokens && (
{revokedTokens.map((tok, index) => ( ))}
{t("settings.tokenTableName")} {t("settings.tokenTablePermissions")} {t("settings.tokenTableCreated")} {t("settings.tokenTableLastUsed")}
{tok.name} {tok.permissions.join(", ")} {formatDate(tok.createdAt)} {tok.lastUsedAt ? formatDateTime(tok.lastUsedAt) : t("settings.tokenNeverUsed")}
)}
)}
); } /* ─────────────────────── Export Section ─────────────────────── */ function ExportSection({ id }: { id: string }) { const { t, locale } = useTranslations(); const [exporting, setExporting] = useState(false); const [generatingReport, setGeneratingReport] = useState(false); async function handleExport(format: "csv" | "json") { setExporting(true); try { const res = await fetch(`/api/export?format=${format}&type=all`); if (!res.ok) return; const blob = await res.blob(); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `healthlog-export-${new Date().toISOString().slice(0, 10)}.${format}`; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } finally { setExporting(false); } } async function handleDoctorReport() { setGeneratingReport(true); try { const res = await fetch("/api/doctor-report", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ days: 90 }), }); if (!res.ok) return; const json = await res.json(); const { generateDoctorReportPDF } = await import( "@/lib/doctor-report-pdf" ); const doc = generateDoctorReportPDF(json.data, { t, locale }); const fileSlug = locale === "de" ? "gesundheitsbericht" : "health-report"; doc.save(`${fileSlug}-${new Date().toISOString().slice(0, 10)}.pdf`); } finally { setGeneratingReport(false); } } return (

{t("settings.export")}

{t("settings.exportDescription")}

); } /* ─────────────────────── Data Reset Section ─────────────────────── */ function DataResetSection({ id }: { id: string }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const [deleting, setDeleting] = useState(false); const [msg, setMsg] = useState(null); const [msgType, setMsgType] = useState<"success" | "error" | null>(null); async function handleDeleteAllData() { setDeleting(true); setMsg(null); setMsgType(null); try { const res = await fetch("/api/settings/data", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ confirm: "DELETE" }), }); const json = await res.json(); if (!res.ok) { setMsg(json.error || t("settings.dangerZoneDeleteFailed")); setMsgType("error"); return; } await queryClient.invalidateQueries(); setMsg(t("settings.dangerZoneSuccess")); setMsgType("success"); } catch { setMsg(t("settings.dangerZoneDeleteFailed")); setMsgType("error"); } finally { setDeleting(false); } } return (

{t("settings.dangerZone")}

{t("settings.dangerZoneDescription")}

{t("settings.dangerZoneConfirm")} {t("settings.dangerZoneConfirmDescription")} {t("common.cancel")} {t("settings.finalDelete")}
{msg && (

{msg}

)}
); } /* ─────────────────────── Telegram Notifications ─────────────────────── */ function TelegramSection({ id, isAuthenticated, }: { id: string; isAuthenticated: boolean; }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const [botToken, setBotToken] = useState(""); const [chatId, setChatId] = useState(""); const [saving, setSaving] = useState(false); const [testing, setTesting] = useState(false); const [msg, setMsg] = useState(null); const [msgType, setMsgType] = useState<"success" | "error" | null>(null); const { data: settings } = useQuery({ queryKey: ["telegram", "settings"], queryFn: async () => { const res = await fetch("/api/settings/telegram"); if (!res.ok) throw new Error("Failed"); const json = await res.json(); return json.data as { enabled: boolean; hasBotToken: boolean; chatId: string | null; }; }, enabled: isAuthenticated, }); const [enabled, setEnabled] = useState(false); const [initialized, setInitialized] = useState(false); if (settings && !initialized) { setEnabled(settings.enabled); if (settings.chatId) setChatId(settings.chatId); setInitialized(true); } async function handleSave(e: React.FormEvent) { e.preventDefault(); setSaving(true); setMsg(null); setMsgType(null); const body: Record = { enabled }; if (botToken.trim()) body.botToken = botToken.trim(); if (chatId !== (settings?.chatId ?? "")) body.chatId = chatId; const res = await fetch("/api/settings/telegram", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (res.ok) { setMsg(t("settings.telegramSaved")); setMsgType("success"); setBotToken(""); queryClient.invalidateQueries({ queryKey: ["telegram"] }); } else { const json = await res.json(); setMsg(json.error || t("settings.savingError")); setMsgType("error"); } setSaving(false); } async function handleTest() { setTesting(true); setMsg(null); setMsgType(null); const res = await fetch("/api/settings/telegram/test", { method: "POST" }); if (res.ok) { setMsg(t("settings.testSent")); setMsgType("success"); } else { const json = await res.json(); setMsg(json.error || t("common.error")); setMsgType("error"); } setTesting(false); } return (

{t("settings.telegram")}

{settings?.hasBotToken && settings?.chatId && ( {t("settings.configured")} )} {settings?.enabled && ( {t("common.enabled")} )}

{t("settings.telegramDescription")}

setBotToken(e.target.value)} placeholder={ settings?.hasBotToken ? t("settings.withingsCredentialsSavedPlaceholder") : "123456:ABC-DEF..." } maxLength={100} />
setChatId(e.target.value)} placeholder="123456789" maxLength={50} />

{t("settings.telegramStep1")}

{t("settings.telegramStep2")}

{t("settings.telegramStep3")}

{msg && (

{msg}

)}
); } /* ─────────────────────── ntfy Settings ─────────────────────── */ interface NtfySettings { enabled: boolean; serverUrl: string; topic: string; hasAuthToken: boolean; } function NtfySection({ id, isAuthenticated, }: { id: string; isAuthenticated: boolean; }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const [serverUrl, setServerUrl] = useState("https://ntfy.sh"); const [topic, setTopic] = useState(""); const [authToken, setAuthToken] = useState(""); const [saveMsg, setSaveMsg] = useState(null); const [saveMsgType, setSaveMsgType] = useState<"success" | "error" | null>( null, ); const { data: settings } = useQuery({ queryKey: ["settings", "ntfy"], queryFn: async () => { const res = await fetch("/api/settings/ntfy"); if (!res.ok) throw new Error("Failed"); const json = await res.json(); return json.data as NtfySettings; }, enabled: isAuthenticated, }); // Sync from server useState(() => { if (settings) { setServerUrl(settings.serverUrl); setTopic(settings.topic); } }); const save = useMutation({ mutationFn: async (enabled: boolean) => { const res = await fetch("/api/settings/ntfy", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ serverUrl, topic, authToken: authToken || undefined, enabled, }), }); if (!res.ok) { const json = await res.json(); throw new Error(json.error || t("common.error")); } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["settings", "ntfy"] }); setSaveMsg(t("settings.saved")); setSaveMsgType("success"); setAuthToken(""); }, onError: (err: Error) => { setSaveMsg(err.message); setSaveMsgType("error"); }, }); const test = useMutation({ mutationFn: async () => { const res = await fetch("/api/settings/ntfy/test", { method: "POST" }); if (!res.ok) { const json = await res.json(); throw new Error(json.error || t("common.error")); } }, onSuccess: () => { setSaveMsg(t("settings.testSent")); setSaveMsgType("success"); }, onError: (err: Error) => { setSaveMsg(err.message); setSaveMsgType("error"); }, }); return (

{t("settings.ntfy")}

{settings?.serverUrl && settings?.topic && ( {t("settings.configured")} )} {settings?.enabled && ( {t("common.enabled")} )}

{t("settings.ntfyDescription")}

save.mutate(checked)} disabled={save.isPending} />
{ e.preventDefault(); save.mutate(settings?.enabled ?? false); }} className="space-y-4" >
setServerUrl(e.target.value)} />
setTopic(e.target.value)} />
setAuthToken(e.target.value)} />

{t("settings.ntfyAuthTokenHint")}

{saveMsg && (

{saveMsg}

)}
); } /* ─────────────────────── Web Push Notifications ─────────────────────── */ function WebPushSection({ id }: { id: string }) { const { t } = useTranslations(); const [isSubscribed, setIsSubscribed] = useState(false); const [isSupported, setIsSupported] = useState(true); const [isDenied, setIsDenied] = useState(false); const [loading, setLoading] = useState(true); const [actionLoading, setActionLoading] = useState(false); const [msg, setMsg] = useState(null); const [msgType, setMsgType] = useState<"success" | "error" | null>(null); useEffect(() => { async function checkSubscription() { if (!("serviceWorker" in navigator) || !("PushManager" in window)) { setIsSupported(false); setLoading(false); return; } if (Notification.permission === "denied") { setIsDenied(true); setLoading(false); return; } try { const registration = await navigator.serviceWorker.getRegistration("/sw.js"); if (registration) { const subscription = await registration.pushManager.getSubscription(); setIsSubscribed(!!subscription); } } catch { // Ignore errors during check } setLoading(false); } checkSubscription(); }, []); async function handleSubscribe() { setActionLoading(true); setMsg(null); setMsgType(null); try { // Get VAPID public key from server const vapidRes = await fetch("/api/notifications/vapid"); if (!vapidRes.ok) { setMsg(t("settings.webPushNotConfigured")); setMsgType("error"); setActionLoading(false); return; } const vapidData = await vapidRes.json(); const vapidPublicKey = vapidData.data.publicKey; // Register service worker const registration = await navigator.serviceWorker.register("/sw.js"); await navigator.serviceWorker.ready; // Subscribe to push const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToArrayBuffer(vapidPublicKey), }); const subJson = subscription.toJSON(); // Save subscription on server const res = await fetch("/api/notifications/web-push", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ endpoint: subJson.endpoint, keys: { p256dh: subJson.keys?.p256dh ?? "", auth: subJson.keys?.auth ?? "", }, }), }); if (res.ok) { setIsSubscribed(true); setMsg(t("settings.webPushSubscribed")); setMsgType("success"); } else { setMsg(t("settings.webPushSubscribeFailed")); setMsgType("error"); } } catch { if (Notification.permission === "denied") { setIsDenied(true); setMsg(t("settings.webPushDenied")); } else { setMsg(t("settings.webPushSubscribeFailed")); } setMsgType("error"); } finally { setActionLoading(false); } } async function handleUnsubscribe() { setActionLoading(true); setMsg(null); setMsgType(null); try { const registration = await navigator.serviceWorker.getRegistration("/sw.js"); if (registration) { const subscription = await registration.pushManager.getSubscription(); if (subscription) { // Delete from server await fetch("/api/notifications/web-push", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ endpoint: subscription.endpoint }), }); await subscription.unsubscribe(); } } setIsSubscribed(false); setMsg(t("settings.webPushUnsubscribed")); setMsgType("success"); } catch { setMsg(t("settings.webPushSubscribeFailed")); setMsgType("error"); } finally { setActionLoading(false); } } return (

{t("settings.webPush")}

{!loading && isSubscribed && ( {t("settings.configured")} )} {!loading && isSubscribed && ( {t("settings.webPushActive")} )}

{t("settings.webPushDescription")}

{loading ? (
) : !isSupported ? (

{t("settings.webPushNotSupported")}

) : isDenied ? (

{t("settings.webPushDenied")}

) : isSubscribed ? ( ) : ( )} {msg && (

{msg}

)}
); } /** Convert a URL-safe base64 string to an ArrayBuffer (for VAPID key). */ function urlBase64ToArrayBuffer(base64String: string): ArrayBuffer { const padding = "=".repeat((4 - (base64String.length % 4)) % 4); const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/"); const raw = atob(base64); const buffer = new ArrayBuffer(raw.length); const view = new Uint8Array(buffer); for (let i = 0; i < raw.length; ++i) { view[i] = raw.charCodeAt(i); } return buffer; } /* ─────────────────────── moodLog Integration ─────────────────────── */ function MoodLogSection({ t }: { t: (key: string) => string }) { const [url, setUrl] = useState(""); const [apiKey, setApiKey] = useState(""); const [saving, setSaving] = useState(false); const [syncing, setSyncing] = useState(false); const [msg, setMsg] = useState(null); const [msgType, setMsgType] = useState<"success" | "error" | null>(null); const { data: status, refetch: refetchStatus } = useQuery({ queryKey: ["moodlog-status"], queryFn: async () => { const res = await fetch("/api/integrations/moodlog/status"); if (!res.ok) throw new Error("Failed"); return (await res.json()).data as { configured: boolean; enabled: boolean; lastSyncedAt: string | null; entryCount: number; webhookSecret: string | null; }; }, }); async function handleSave(e: React.FormEvent) { e.preventDefault(); setSaving(true); setMsg(null); const res = await fetch("/api/settings/moodlog", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: url.trim(), apiKey: apiKey.trim() }), }); if (res.ok) { setMsg(t("settings.moodLogSaved")); setMsgType("success"); setUrl(""); setApiKey(""); await refetchStatus(); } else { const json = await res.json(); setMsg(json.error || t("settings.savingError")); setMsgType("error"); } setSaving(false); } async function handleSync(fullSync = false) { setSyncing(true); setMsg(null); try { const res = await fetch("/api/integrations/moodlog/sync", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fullSync }), }); if (res.ok) { const json = await res.json(); setMsg(t("settings.moodLogSyncResult").replace("{count}", String(json.data.imported))); setMsgType("success"); await refetchStatus(); } else { setMsg(t("settings.moodLogSyncFailed")); setMsgType("error"); } } catch { setMsg(t("settings.moodLogSyncFailed")); setMsgType("error"); } setSyncing(false); } async function handleDisconnect() { const res = await fetch("/api/settings/moodlog", { method: "DELETE" }); if (res.ok) { setMsg(t("settings.moodLogDisconnected")); setMsgType("success"); await refetchStatus(); } } return (
{status?.configured && ( {status.enabled ? t("settings.withingsConnected") : t("settings.configured")} )}

{t("settings.moodLogDescription")}

{/* Credentials form */}
setUrl(e.target.value)} />
setApiKey(e.target.value)} />
{/* Connected state */} {status?.configured && (
{/* Webhook Secret */} {status.webhookSecret && (

{t("settings.moodLogWebhookSecretHelp")}

)} {/* Status info */}
{status.lastSyncedAt && ( {t("settings.moodLogLastSync")}:{" "} {formatDateTime(status.lastSyncedAt)} )} {t("settings.moodLogEntries")}: {status.entryCount}
{/* Sync buttons */}
{t("settings.moodLogFullSyncTitle")} {t("settings.moodLogFullSyncDescription")} {t("common.cancel")} handleSync(true)}> {t("settings.moodLogFullSync")} {t("settings.moodLogDisconnectTitle")} {t("settings.moodLogDisconnectDescription")} {t("common.cancel")} {t("settings.moodLogDisconnect")}
)} {/* Status message */} {msg && (

{msg}

)}
); } /* ─────────────────────── OpenAI Insights Settings ─────────────────────── */ function InsightsSettingsSection({ id, isAuthenticated, }: { id: string; isAuthenticated: boolean; }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const [disconnecting, setDisconnecting] = useState(false); const [regenerating, setRegenerating] = useState(false); const [msg, setMsg] = useState(null); const [msgType, setMsgType] = useState<"success" | "error" | null>(null); const { data: settings } = useQuery({ queryKey: ["insights", "settings"], queryFn: async () => { const res = await fetch("/api/insights/settings"); if (!res.ok) return null; const json = await res.json(); return json.data as { codexStatus: string; codexConnectedAt: string | null; hasAdminKey: boolean; privacyMode: string; lastInsightAt: string | null; }; }, enabled: isAuthenticated, }); const updateSettings = useMutation({ mutationFn: async (body: Record) => { const res = await fetch("/api/insights/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const json = await res.json(); if (!res.ok) throw new Error(json.error); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["insights"] }); }, }); // Handle OAuth callback query params useEffect(() => { const params = new URLSearchParams(window.location.search); if (params.get("codex_connected") === "true") { setMsg(t("settings.codexConnected")); setMsgType("success"); queryClient.invalidateQueries({ queryKey: ["insights"] }); window.history.replaceState({}, "", window.location.pathname); } else if (params.get("codex_error")) { setMsg(t("settings.codexConnectionFailed")); setMsgType("error"); window.history.replaceState({}, "", window.location.pathname); } }, [queryClient, t]); const hasProvider = settings?.codexStatus === "connected" || settings?.hasAdminKey; async function handleConnect() { window.location.href = "/api/auth/codex/authorize"; } async function handleDisconnect() { setDisconnecting(true); setMsg(null); try { const res = await fetch("/api/auth/codex/disconnect", { method: "DELETE" }); if (!res.ok) { const json = await res.json(); throw new Error(json.error); } setMsg(t("settings.codexDisconnected")); setMsgType("success"); queryClient.invalidateQueries({ queryKey: ["insights"] }); } catch (err) { setMsg(err instanceof Error ? err.message : t("settings.savingError")); setMsgType("error"); } finally { setDisconnecting(false); } } async function togglePrivacyMode() { const newMode = settings?.privacyMode === "raw" ? "aggregated" : "raw"; await updateSettings.mutateAsync({ privacyMode: newMode }); } async function handleRegenerate() { setRegenerating(true); setMsg(null); setMsgType(null); try { const res = await fetch("/api/insights/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ force: true }), }); const json = await res.json(); if (!res.ok) { if (res.status === 429) { setMsg(t("settings.regenerateRateLimit")); } else { setMsg(json.error || t("settings.savingError")); } setMsgType("error"); return; } setMsg(t("settings.regenerateSuccess")); setMsgType("success"); queryClient.invalidateQueries({ queryKey: ["insights"] }); } catch { setMsg(t("settings.savingError")); setMsgType("error"); } finally { setRegenerating(false); } } return (

{t("settings.kiInsights")}

{settings?.codexStatus === "connected" && ( ChatGPT verbunden )} {settings?.codexStatus !== "connected" && settings?.hasAdminKey && ( Admin-KI aktiv )} {settings?.codexStatus === "expired" && ( Verbindung abgelaufen )} {settings?.lastInsightAt && ( {t("settings.lastGeneratedAt")}:{" "} {formatDateTime(settings.lastInsightAt)} )}

{t("settings.kiInsightsDescription")}

{/* ChatGPT Connection */}
{settings?.codexStatus === "connected" ? (

ChatGPT verbunden

Insights werden über dein ChatGPT-Abo generiert — keine zusätzlichen Kosten. {settings.codexConnectedAt && ( <> Verbunden seit {formatDateTime(settings.codexConnectedAt)}. )}

) : (

Mit ChatGPT verbinden

Verbinde dein ChatGPT Pro/Max-Konto um KI-gestützte Gesundheitsanalysen basierend auf aktuellen medizinischen Leitlinien zu erhalten. Keine zusätzlichen API-Kosten.

{settings?.hasAdminKey && (

Alternativ nutzt HealthLog den vom Administrator konfigurierten KI-Anbieter.

)}
)}
{msg && (

{msg}

)} {/* Privacy Mode */} {hasProvider && (

{t("settings.rawData")}

{settings?.privacyMode === "raw" ? t("settings.rawDataOnDescription") : t("settings.rawDataOffDescription")}

{settings?.privacyMode === "raw" && (
{t("settings.rawDataWarning")}
)}
)} {/* Regenerate Reports */} {hasProvider && ( )} {/* Multi-provider AI selection (per-user override) */}
); } /* ─────────────────────── User AI Provider Override ─────────────────────── */ function UserAIProviderSubsection() { const queryClient = useQueryClient(); const [provider, setProvider] = useState(""); const [model, setModel] = useState(""); const [baseUrl, setBaseUrl] = useState(""); const [anthropicKey, setAnthropicKey] = useState(""); const [localKey, setLocalKey] = useState(""); const [saveMsg, setSaveMsg] = useState(null); const [saveOk, setSaveOk] = useState(false); const [testMsg, setTestMsg] = useState(null); const [testOk, setTestOk] = useState(false); const [testing, setTesting] = useState(false); const { data, isLoading } = useQuery({ queryKey: ["user", "ai-provider"], queryFn: async () => { const res = await fetch("/api/user/ai-provider"); if (!res.ok) return null; const json = await res.json(); return json.data as { provider: string | null; model: string | null; baseUrl: string | null; hasAnthropicKey: boolean; anthropicKeyPreview: string | null; hasLocalKey: boolean; }; }, }); useEffect(() => { if (!data) return; // Sync-from-server pattern: form draft state is initialised from the // fetched user record. Could be reworked into a derived-state approach, // but that's a non-trivial refactor of this monolithic settings page — // tracked for the 1.4.0 settings split. // eslint-disable-next-line react-hooks/set-state-in-effect setProvider(data.provider ?? ""); // eslint-disable-next-line react-hooks/set-state-in-effect setModel(data.model ?? ""); // eslint-disable-next-line react-hooks/set-state-in-effect setBaseUrl(data.baseUrl ?? ""); }, [data]); const saveMutation = useMutation({ mutationFn: async () => { const body: Record = { provider: provider || null, model: model || null, baseUrl: baseUrl || null, }; if (anthropicKey.trim()) body.anthropicKey = anthropicKey.trim(); if (localKey.trim()) body.localKey = localKey.trim(); const res = await fetch("/api/user/ai-provider", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const json = await res.json(); if (!res.ok) throw new Error(json.error || "Save failed"); }, onSuccess: () => { setSaveMsg("Gespeichert"); setSaveOk(true); setAnthropicKey(""); setLocalKey(""); queryClient.invalidateQueries({ queryKey: ["user", "ai-provider"] }); queryClient.invalidateQueries({ queryKey: ["insights"] }); }, onError: (e) => { setSaveMsg(e instanceof Error ? e.message : "Fehler"); setSaveOk(false); }, }); async function runTest() { setTesting(true); setTestMsg(null); try { const res = await fetch("/api/ai/test", { method: "POST" }); const json = await res.json(); if (!res.ok) { setTestMsg(json.error || `HTTP ${res.status}`); setTestOk(false); return; } setTestMsg( `OK — ${json.data.providerType} (${json.data.model})${ json.data.tokensUsed ? `, ${json.data.tokensUsed} tokens` : "" }`, ); setTestOk(true); } catch (e) { setTestMsg(e instanceof Error ? e.message : "Test fehlgeschlagen"); setTestOk(false); } finally { setTesting(false); } } if (isLoading) return null; return (

KI-Provider (persönlich)

Eigener KI-Anbieter überschreibt die Admin-Einstellung. Leer lassen für Standard.

setModel(e.target.value)} placeholder={ provider === "ANTHROPIC" ? "claude-3-5-sonnet-latest" : provider === "LOCAL" ? "llama3:8b" : "gpt-4o-mini" } className="mt-1" />
{provider === "ANTHROPIC" && (
setAnthropicKey(e.target.value)} placeholder="sk-ant-..." className="mt-1" />
)} {provider === "LOCAL" && ( <>
setBaseUrl(e.target.value)} placeholder="http://localhost:11434/v1" className="mt-1" />
setLocalKey(e.target.value)} placeholder={data?.hasLocalKey ? "(gespeichert)" : ""} className="mt-1" />
)}
{saveMsg && (

{saveMsg}

)} {testMsg && (

{testMsg}

)}
); }