import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react'; import { useI18n } from './i18n'; /** Aydınlık / karanlık tema. İlk açılışta sistem ayarı izlenir; seçim yapılınca tarayıcıda hatırlanır. */ type Theme = 'light' | 'dark'; const KEY = 'testajani.theme'; const mq = () => window.matchMedia('(prefers-color-scheme: dark)'); function stored(): Theme | null { try { const v = window.localStorage.getItem(KEY); return v === 'light' || v === 'dark' ? v : null; } catch { return null; } } const Ctx = createContext<{ dark: boolean; toggle: () => void; choice: Theme | null; setChoice: (t: Theme) => void }>( { dark: false, toggle: () => {}, choice: null, setChoice: () => {} }); export function ThemeProvider({ children }: { children: ReactNode }) { const [choice, setChoice] = useState(stored); const [sysDark, setSysDark] = useState(() => mq().matches); useEffect(() => { const m = mq(); const h = () => setSysDark(m.matches); m.addEventListener('change', h); return () => m.removeEventListener('change', h); }, []); const dark = choice ? choice === 'dark' : sysDark; useEffect(() => { // CSS, :root[data-theme] ile açık seçimi; yoksa sistem ayarını (prefers-color-scheme) kullanır if (choice) document.documentElement.dataset.theme = choice; else delete document.documentElement.dataset.theme; }, [choice]); const choose = useCallback((next: Theme) => { setChoice(next); try { window.localStorage.setItem(KEY, next); } catch { /* yoksay */ } }, []); const toggle = useCallback(() => choose(dark ? 'light' : 'dark'), [dark, choose]); return {children}; } export const useTheme = () => useContext(Ctx); export function ThemeSwitch() { const { dark, toggle } = useTheme(); const { t } = useI18n(); const label = dark ? t('theme.toLight') : t('theme.toDark'); return ( ); }