import {writable,type Writable} from 'svelte/store';

export function persistedStore<T> (key: string, initialValue: T): Writable<T> {
	let storedValue: T;
	try {
		const json = localStorage.getItem(key);
		storedValue = json ? JSON.parse(json) : initialValue;
	} catch (e) {
		console.warn(`读取 localStorage key = ${key} 失败`, e);
		storedValue = initialValue;
	}
	const store = writable<T>(storedValue);

	store.subscribe(value => {
		try {
			localStorage.setItem(key, JSON.stringify(value));
		} catch (e) {
			console.warn(`写入 localStorage key=${key} 失败`, e);
		}
	});

	return store;
}
