import { useEffect, useRef, useState } from "react"; type Initializer = T | (() => T); const isBrowser = typeof window !== "undefined"; function readFromStorage(key: string, fallback: Initializer): T { if (!isBrowser) { return typeof fallback === "function" ? (fallback as () => T)() : fallback; } try { const raw = window.localStorage.getItem(key); if (raw) { return JSON.parse(raw) as T; } } catch (error) { console.warn("Failed to parse localStorage value", { key, error }); } return typeof fallback === "function" ? (fallback as () => T)() : fallback; } export function usePersistentState(key: string, initial: Initializer) { const initialRef = useRef(null); if (initialRef.current === null) { initialRef.current = readFromStorage(key, initial); } const [value, setValue] = useState(() => initialRef.current as T); useEffect(() => { if (!isBrowser) return; try { window.localStorage.setItem(key, JSON.stringify(value)); } catch (error) { console.warn("Failed to write localStorage value", { key, error }); } }, [key, value]); return [value, setValue] as const; }