import { useEffect, useState } from 'react'; export function useLocalStorage(key: string, initial: T) { const [value, setValue] = useState(() => { try { if (typeof window !== 'undefined') { const raw = localStorage.getItem(key); if (raw) { const parsed = JSON.parse(raw); console.log('[useLocalStorage] Init from storage', { key, value: parsed }); return parsed as T; } } } catch {} return initial; }); useEffect(() => { try { const raw = typeof window !== 'undefined' ? localStorage.getItem(key) : null; if (raw) { const parsed = JSON.parse(raw); console.log('[useLocalStorage] Loaded', { key, value: parsed }); setValue(parsed); } else { console.log('[useLocalStorage] No existing value, using initial', { key, initial }); } } catch {} // eslint-disable-next-line react-hooks/exhaustive-deps }, [key]); useEffect(() => { try { if (typeof window !== 'undefined') { localStorage.setItem(key, JSON.stringify(value)); console.log('[useLocalStorage] Saved', { key, value }); } } catch {} }, [key, value]); return [value, setValue] as const; }