import { useState, useEffect } from 'react';
import { usePreferencesStore } from '@/zustand/preferencesStore';

function usePreference<T>(key: string, initial?: T) {
    const value = usePreferencesStore((s) => s.items[key]?.value as T);
    const setValue = usePreferencesStore((s) => s.set);
    const toggleValue = usePreferencesStore((s) => s.toggle);
    const [hydrated, setHydrated] = useState(false);

    useEffect(() => {
        setHydrated(true);
    }, []);

    useEffect(() => {
        if (hydrated && value === undefined) {
            setValue(key, initial ?? null);
        }
    }, [hydrated, value, key, initial, setValue]);

    const toggle = (e?: React.MouseEvent | null) => {
        if (e) {
            e.preventDefault();
            e.stopPropagation();
        }
        toggleValue(key);
    };

    return { state: value, toggle, set: setValue, hydrated };
}

export default usePreference;
