import { ref, watch } from 'vue'

export function useLocalStoragePreferences<T>(
	key: string,
	defaultValue: T
) {
	const state = ref<T>( defaultValue )

	if ( typeof window !== 'undefined' ) {
		const saved = localStorage.getItem( key )

		if ( saved !== null ) {
			try {
				state.value = JSON.parse( saved )
			} catch {
				state.value = defaultValue
			}
		}
	}

	watch( state, ( value ) => {
		localStorage.setItem( key, JSON.stringify( value ) )
	}, { deep: true })

	return state
}
