import { useState, useEffect } from "react"; export const useThemeMode = () => { // Function to detect system preference for dark mode const getSystemPreference = () => { return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; }; // Initialize state with system preference const [mode, setMode] = useState(getSystemPreference()); // Listen for changes in system preference useEffect(() => { const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); const handleChange = (e) => { setMode(e.matches ? "dark" : "light"); }; // Add event listener if (mediaQuery.addEventListener) { mediaQuery.addEventListener("change", handleChange); } else { // For older browsers mediaQuery.addListener(handleChange); } // Cleanup return () => { if (mediaQuery.removeEventListener) { mediaQuery.removeEventListener("change", handleChange); } else { // For older browsers mediaQuery.removeListener(handleChange); } }; }, []); // Toggle function is kept for compatibility with existing code // but it will only temporarily change the theme until the next system preference change const toggleTheme = () => { setMode((prevMode) => (prevMode === "light" ? "dark" : "light")); }; return { mode, toggleTheme, isSystemPreference: true, }; };