import type { WrappedValue } from "$lib/services/stores.svelte";

export const eventTarget = new EventTarget();

export function localStore<T>(key: string, defaultValue: T): WrappedValue<T> {
	const storedValue = localStorage.getItem(key);
	const initialValue =
		storedValue !== null ? JSON.parse(storedValue) : defaultValue;
	const state = $state<WrappedValue<T>>({ current: initialValue });
	eventTarget.addEventListener("localStorageChanged", (event) => {
		const customEvent = event as CustomEvent;
		console.log("localStorageChanged event received", customEvent.detail);
		if (customEvent.detail.key === key) {
			const newValue = customEvent.detail.value as T;
			console.log(`localStore: ${key} updated from another tab`, newValue);
			if (JSON.stringify(state.current) === JSON.stringify(newValue)) return;
			state.current = newValue;
		}
	});
	return {
		get current() {
			return state.current;
		},
		set current(newValue: T) {
			state.current = newValue;
			eventTarget.dispatchEvent(
				new CustomEvent("localStorageChanged", {
					detail: { key, value: newValue },
				}),
			);
			localStorage.setItem(key, JSON.stringify(newValue));
		},
	};
}
