"use client"; import { useSyncExternalStore } from "react"; import { Moon, Sun } from "lucide-react"; import { useI18n } from "./I18nProvider"; import { themeStorageKey, type Theme } from "@/shared/theme"; function currentTheme(): Theme { return document.documentElement.dataset.theme === "light" ? "light" : "dark"; } function subscribe(onChange: () => void) { const observer = new MutationObserver(onChange); observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"], }); function syncStorage(event: StorageEvent) { if (event.key === themeStorageKey || event.key === null) { document.documentElement.dataset.theme = event.newValue === "light" ? "light" : "dark"; } } window.addEventListener("storage", syncStorage); return () => { observer.disconnect(); window.removeEventListener("storage", syncStorage); }; } export function ThemeToggle() { const { t } = useI18n(); const theme = useSyncExternalStore(subscribe, currentTheme, () => "dark"); const label = t( theme === "light" ? "Turn on dark mode" : "Turn on light mode", ); function toggle() { const next = currentTheme() === "light" ? "dark" : "light"; document.documentElement.dataset.theme = next; try { localStorage.setItem(themeStorageKey, next); } catch { // Switching still works for this visit if browser storage is unavailable. } } return ( ); }