"use client"; import { useEffect, useState } from "react"; import { useTranslations } from "next-intl"; import { toast } from "sonner"; import { Switch } from "@/components/ui/switch"; import { Label } from "@/components/ui/label"; import type { FeatureKey, FeaturePrefs } from "@/lib/feature-prefs"; const FEATURES: FeatureKey[] = ["nutrition", "pantry", "mealPlan", "shoppingLists", "collections", "messages", "chatbots"]; export function FeatureTogglesForm() { const t = useTranslations("settingsForm.featureToggles"); const t_common = useTranslations("common"); const [prefs, setPrefs] = useState(null); const [saving, setSaving] = useState(null); useEffect(() => { fetch("/api/v1/users/me/feature-prefs") .then((res) => (res.ok ? res.json() : null)) .then((json) => setPrefs(json?.data ?? null)) .catch(() => setPrefs(null)); }, []); async function toggle(feature: FeatureKey, checked: boolean) { if (!prefs) return; const previous = prefs; setPrefs({ ...prefs, [feature]: checked }); setSaving(feature); try { const res = await fetch("/api/v1/users/me/feature-prefs", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ [feature]: checked }), }); if (!res.ok) { setPrefs(previous); toast.error(t_common("saveFailed")); } else { // Nav reads this same endpoint on its own mount — no shared client // cache to invalidate, so a hard reason to re-fetch is a full nav // refresh. Cheapest correct fix: reload so the nav picks it up now // instead of on the next navigation. window.dispatchEvent(new Event("epicure:feature-prefs-changed")); } } catch { setPrefs(previous); toast.error(t_common("saveFailed")); } finally { setSaving(null); } } if (!prefs) return null; return (
{FEATURES.map((feature) => (

{t(`${feature}Description`)}

{ void toggle(feature, checked); }} />
))}
); }