import { useCallback, useState } from 'react';

/**
 * useLocalStorageState — useState と同じ API で localStorage に値を同期する。
 * - 初期マウント時に localStorage から復元、無ければ defaultValue
 * - setValue 呼出時に同期書き込み (quota / SecurityError は握りつぶし)
 * - SSR 環境では window 不在を防御
 */
export function useLocalStorageState<T>(
  key: string,
  defaultValue: T,
): [T, (value: T | ((prev: T) => T)) => void] {
  const [value, setValue] = useState<T>(() => {
    if (typeof window === 'undefined') return defaultValue;
    try {
      const raw = window.localStorage.getItem(key);
      if (raw === null) return defaultValue;
      return JSON.parse(raw) as T;
    } catch {
      return defaultValue;
    }
  });

  const set = useCallback(
    (next: T | ((prev: T) => T)) => {
      setValue(prev => {
        const resolved =
          typeof next === 'function' ? (next as (p: T) => T)(prev) : next;
        try {
          if (typeof window !== 'undefined') {
            window.localStorage.setItem(key, JSON.stringify(resolved));
          }
        } catch {
          // quota / SecurityError — ignore
        }
        return resolved;
      });
    },
    [key],
  );

  return [value, set];
}
