/**
 * Snippet-sort orchestration — bridges the (browser-free) SnippetStore's library
 * sort to the ux-prefs adapter (spec §02 → Sort; persists across sessions). Same
 * store↔adapter pattern as theme / pane-layout / preferences.
 *
 * `initSnippetSort` hydrates the persisted field+direction into the store before
 * render, so the library opens the way the user left it. `wireSnippetSort`
 * persists the choice on change — written **immediately** (a sort change is a
 * single discrete click, not a stream like a resize drag).
 *
 * Search is intentionally NOT persisted: it's a transient narrowing of the view,
 * not a remembered preference (spec §02 — search affects visibility only).
 */

import { loadSnippetSort, saveSnippetSort } from '../infrastructure/ux-prefs';
import { useSnippetStore } from '../stores/SnippetStore';

/** Hydrate the persisted library sort into the store. Call before render. */
export function initSnippetSort(): void {
  const { by, order } = loadSnippetSort();
  // Pass the explicit order so setSort hydrates the exact stored state rather
  // than running its flip/reset selection logic.
  useSnippetStore.getState().setSort(by, order);
}

/** Persist the sort on change. Returns a teardown that detaches the subscriber. */
export function wireSnippetSort(): () => void {
  return useSnippetStore.subscribe((state, prev) => {
    if (state.sortBy === prev.sortBy && state.sortOrder === prev.sortOrder) return;
    saveSnippetSort({ by: state.sortBy, order: state.sortOrder });
  });
}
