import { useCallback, useState } from "react"; import { getAccountRaw, setAccountRaw } from "./storage"; import { useAccountRehydrate } from "./useAccountRehydrate"; import { hydrateSort, type SortOption, type SortState } from "./columnSort"; // The per-account persisted sort state, hydrated + healed against the current options — the plumbing // the channel manager and channel discovery each hand-rolled (useState + parseSortState + a persist // key). One home so a new sortable surface (Plex, a future table) gets persistence for free. export function useSortState( storageBase: string, options: SortOption[] = [], fallback: SortState = null, ): [SortState, (next: SortState) => void] { const [sort, setSort] = useState(() => hydrateSort(getAccountRaw(storageBase), options, fallback), ); // When the account is pinned after mount (first load), re-read the stored sort for that account. const markDirty = useAccountRehydrate(() => setSort(hydrateSort(getAccountRaw(storageBase), options, fallback)), ); const set = useCallback( (next: SortState) => { markDirty(); setSort(next); setAccountRaw(storageBase, JSON.stringify(next)); }, [storageBase, markDirty], ); return [sort, set]; }