"use client"; import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react"; type SoundContextValue = { isMuted: boolean; toggleMuted: () => void; playSound: (src: string) => void; }; const SOUND_MUTED_STORAGE_KEY = "mohfarawati-sound-muted"; const SoundContext = createContext(null); export function SoundProvider({ children }: { children: ReactNode }) { const [isMuted, setIsMuted] = useState(false); const [mounted, setMounted] = useState(false); useEffect(() => { setMounted(true); const storedValue = window.localStorage.getItem(SOUND_MUTED_STORAGE_KEY); if (storedValue === "true") { setIsMuted(true); } }, []); useEffect(() => { if (!mounted) { return; } window.localStorage.setItem(SOUND_MUTED_STORAGE_KEY, String(isMuted)); }, [isMuted, mounted]); const value = useMemo( () => ({ isMuted, toggleMuted: () => { setIsMuted((currentValue) => !currentValue); }, playSound: (src: string) => { if (!mounted || isMuted) { return; } const audio = new Audio(src); audio.preload = "auto"; void audio.play().catch(() => {}); }, }), [isMuted, mounted], ); return {children}; } export function useSound() { const context = useContext(SoundContext); if (!context) { throw new Error("useSound must be used within SoundProvider"); } return context; }