import { useState, useEffect } from 'react';

export function useLocalStorageState<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>] {
  const isClient = typeof window !== 'undefined';

  const getInitialValue = (): T => {
    if (!isClient) return initialValue;
    try {
      const stored = localStorage.getItem(key);
      if (stored !== null) {
        try {
          return JSON.parse(stored);
        } catch {
          return stored as unknown as T;
        }
      }
    } catch {
      /* ignore */
    }
    return initialValue;
  };

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

  useEffect(() => {
    if (!isClient) return;
    try {
      if (value === null) localStorage.removeItem(key);
      else localStorage.setItem(key, JSON.stringify(value));
    } catch {
      /* ignore */
    }
  }, [key, value]);

  return [value, setValue];
}
