import { useCallback, useState } from "react";

const STORAGE_KEY = "chrysopedia_sort_pref";

/**
 * Reads/writes a sort preference to sessionStorage.
 * Falls back to `defaultSort` if no stored value exists.
 */
export function useSortPreference(
  defaultSort: string,
): [string, (next: string) => void] {
  const [sort, setSortState] = useState<string>(() => {
    try {
      return sessionStorage.getItem(STORAGE_KEY) ?? defaultSort;
    } catch {
      return defaultSort;
    }
  });

  const setSort = useCallback((next: string) => {
    setSortState(next);
    try {
      sessionStorage.setItem(STORAGE_KEY, next);
    } catch {
      // sessionStorage unavailable (private browsing, etc.)
    }
  }, []);

  return [sort, setSort];
}
