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

export function formatDate(timestamp: number): string {
	const date = new Date(timestamp * 1000);
	const options: Intl.DateTimeFormatOptions = {
		year: 'numeric',
		month: 'long',
		day: 'numeric',
		hour: 'numeric',
		minute: 'numeric',
		second: 'numeric'
	};
	return date.toLocaleString(undefined, options);
}

export function localStorageStore<T>(key: string, defaultValue: T) {
	const store = writable(defaultValue) as Writable<T>;
	const { subscribe, set, update } = store;

	localStorage[key] && set(JSON.parse(localStorage[key]));

	return {
		subscribe,
		set: (value: T) => {
			localStorage[key] = JSON.stringify(value);
			set(value);
		},
		update: (cb: (value: T) => T) => {
			const updatedStore = cb(get(store));
			localStorage[key] = JSON.stringify(updatedStore);
			set(updatedStore);
		}
	};
}
