"use client"; import { useSyncExternalStore } from "react"; import { Moon, Sun } from "@phosphor-icons/react"; import { cn } from "@/lib/utils"; // The theme lives on (set pre-paint by the script in // layout.tsx). Reading it via useSyncExternalStore keeps the toggle in sync // without a setState-in-effect and without a hydration mismatch. function subscribe(callback: () => void) { window.addEventListener("themechange", callback); window.addEventListener("storage", callback); return () => { window.removeEventListener("themechange", callback); window.removeEventListener("storage", callback); }; } function getSnapshot() { return document.documentElement.classList.contains("dark"); } function getServerSnapshot() { return false; } export function ThemeToggle({ className }: { className?: string }) { const dark = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); function toggle() { const next = !dark; document.documentElement.classList.toggle("dark", next); try { localStorage.setItem("theme", next ? "dark" : "light"); } catch { /* ignore storage errors (private mode, etc.) */ } window.dispatchEvent(new Event("themechange")); } return ( ); }