"use client"; import { createContext, useContext, useEffect, useState } from "react"; import { trpc } from "@/lib/trpc"; type ThemeContextValue = { isDark: boolean; toggleDark: () => void }; const ThemeContext = createContext({ isDark: false, toggleDark: () => {}, }); export function ThemeProvider({ children }: { children: React.ReactNode }) { const [isDark, setIsDark] = useState(false); const [localInit, setLocalInit] = useState(false); // 1. Start neutral; the user profile below owns the persisted theme. useEffect(() => { setLocalInit(true); }, []); // 2. Sync from DB once profile is loaded — overrides the localStorage value const { data: profile } = trpc.users.myProfile.useQuery(undefined, { enabled: localInit, retry: false, }); const setTheme = trpc.users.setTheme.useMutation(); useEffect(() => { if (!profile) return; const userThemeKey = `hellth-theme:${profile.id}`; const dbTheme = profile.theme; if (dbTheme === null || dbTheme === undefined) { const stored = localStorage.getItem(userThemeKey); const dark = stored === "dark"; setIsDark(dark); document.documentElement.classList.toggle("dark", dark); return; } const dark = dbTheme === "dark"; setIsDark(dark); document.documentElement.classList.toggle("dark", dark); localStorage.setItem(userThemeKey, dark ? "dark" : "light"); }, [profile?.id, profile?.theme]); function toggleDark() { const next = !isDark; setIsDark(next); document.documentElement.classList.toggle("dark", next); const themeValue = next ? "dark" : "light"; if (profile?.id) { localStorage.setItem(`hellth-theme:${profile.id}`, themeValue); } setTheme.mutate({ theme: themeValue }); } return ( {children} ); } export function useTheme() { return useContext(ThemeContext); }