import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react'; type Theme = 'light' | 'dark'; interface ThemeContextType { theme: Theme; toggleTheme: () => void; } const ThemeContext = createContext(null); export function ThemeProvider({ children }: { children: ReactNode }) { const [theme, setTheme] = useState(() => { try { const stored = localStorage.getItem('melodymuse-theme'); if (stored === 'light' || stored === 'dark') return stored; } catch { // ignore } return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; }); useEffect(() => { const root = window.document.documentElement; if (theme === 'dark') { root.classList.add('dark'); } else { root.classList.remove('dark'); } try { localStorage.setItem('melodymuse-theme', theme); } catch { // ignore } }, [theme]); const toggleTheme = () => { setTheme((prev) => (prev === 'dark' ? 'light' : 'dark')); }; return ( {children} ); } export function useTheme() { const ctx = useContext(ThemeContext); if (!ctx) throw new Error('useTheme must be used within ThemeProvider'); return ctx; }