import {useState, useEffect} from '@wordpress/element';

export default function useTheme(clientTheme) {
    const [theme, setTheme] = useState(clientTheme);

    useEffect(() => {
        if (clientTheme === 'system') {
            const matchMedia = window.matchMedia('(prefers-color-scheme: dark)');

            const handleChange = () => {
                setTheme(matchMedia.matches ? 'dark' : 'light');
            };

            handleChange(); // Set the initial theme
            matchMedia.addEventListener('change', handleChange);

            return () => {
                matchMedia.removeEventListener('change', handleChange);
            };
        } else {
            setTheme(clientTheme); // Ensure the theme state is set to clientTheme if not 'system'
        }
    }, [clientTheme]); // Depend on clientTheme so it can re-evaluate if it changes

    return theme;
}