/**
 * Re-query a listing when the offline "downloaded only" gate changes.
 *
 * The gate is a process-wide flag in Rust, consulted only while a query runs,
 * so flipping it has no effect on rows already on screen. Library pages loaded
 * once on mount and reloaded only on the offline → online transition
 * (`useServerReachabilityReload`), which left two gaps the user sees as a broken
 * filter:
 *
 *  - going *offline* never reloaded, so the full server catalog stayed on
 *    screen under a now-closed gate;
 *  - toggling "Show all server media" never reloaded, so it only greyed the
 *    cards already listed instead of adding or removing any.
 *
 * `catalogFilterVersion` bumps once the backend has accepted the new gate, so
 * the reload this triggers always queries under the intended filter.
 *
 * Call during component initialisation, like `useServerReachabilityReload`:
 *
 * ```svelte
 * <script>
 *   useOfflineFilterReload(() => loadItems());
 * </script>
 * ```
 *
 * TRACES: UR-052 | DR-143
 */
import { onDestroy } from "svelte";
import { catalogFilterVersion } from "$lib/services/offlineCatalog";

export function useOfflineFilterReload(reloadFn: () => void | Promise<void>): void {
  // The value the page is already showing. Seeded from the first subscription
  // callback (stores emit synchronously on subscribe) so mounting never
  // triggers a redundant second load of what onMount just fetched.
  let applied: number | null = null;

  const unsubscribe = catalogFilterVersion.subscribe((version) => {
    if (applied === null || version === applied) {
      applied = version;
      return;
    }
    applied = version;
    void reloadFn();
  });

  onDestroy(unsubscribe);
}
