import { useState, useEffect } from 'react';

export const useRhTheme = () => {
    // Check localStorage or device preference
    const [theme, setTheme] = useState(() => {
        if (typeof window !== 'undefined' && window.localStorage) {
            const stored = localStorage.getItem('rh-theme');
            if (stored) return stored;
            return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
        }
        return 'light';
    });

    useEffect(() => {
        const root = window.document.documentElement;
        
        // Remove both potentials
        root.classList.remove('light', 'dark');
        
        // Add current
        root.classList.add(theme);
        
        // Save
        localStorage.setItem('rh-theme', theme);
    }, [theme]);

    const toggleTheme = () => {
        setTheme(prev => prev === 'light' ? 'dark' : 'light');
    };

    return { theme, toggleTheme };
};
