import { useCallback, useEffect, useState } from "react";

/**
 * Persist a piece of UI state in browser storage.
 *
 * The hook keeps the React state authoritative during the session and mirrors
 * updates into localStorage whenever the value changes. This keeps filters,
 * paths, and other view preferences stable across reloads and tab switches.
 */
export function usePersistentState<T>(
	key: string,
	initialValue: T | (() => T),
) {
	const readInitialValue = useCallback((): T => {
		const fallback =
			typeof initialValue === "function"
				? (initialValue as () => T)()
				: initialValue;
		if (typeof window === "undefined") {
			return fallback;
		}

		const raw = window.localStorage.getItem(key);
		if (!raw) {
			return fallback;
		}

		try {
			return JSON.parse(raw) as T;
		} catch {
			return fallback;
		}
	}, [initialValue, key]);

	const [value, setValue] = useState<T>(readInitialValue);

	useEffect(() => {
		if (typeof window === "undefined") return;
		window.localStorage.setItem(key, JSON.stringify(value));
	}, [key, value]);

	return [value, setValue] as const;
}
