/**
 * Settings orchestration — bridges the (browser-free) UserSettingsStore to the
 * localStorage adapter, the same store↔adapter pattern as theme/preferences.
 *
 * `initSettings` hydrates the applied managed groups (editor / performance /
 * formatting) from the persisted record before render, so the editor, preview,
 * and library read the user's settings from the first paint. `wireSettings`
 * persists the managed slice whenever it changes (live, the moment a control
 * changes — there is no Apply step).
 *
 * Theme and preview fit mode are persisted by their own slice subscribers
 * (theme.ts, preferences.ts) onto the same `astrolabe:settings` record; the
 * field-level write-through merge keeps the slices from clobbering each other.
 *
 * Settings are distributed and live-applied (spec §07): a control mutates the
 * store the instant it changes, so `wireSettings` persists on every change —
 * there is no Apply/Cancel commit step.
 */

import { loadUserSettings, saveManagedSettings } from '../infrastructure/settings-store';
import { useUserSettingsStore } from '../stores/UserSettingsStore';

/** Hydrate the applied managed settings into the store. Call before render. */
export function initSettings(): void {
  useUserSettingsStore.getState().hydrate(loadUserSettings());
}

/** Persist the managed settings on change. Returns a teardown that detaches it. */
export function wireSettings(): () => void {
  return useUserSettingsStore.subscribe((state, prev) => {
    if (state.saved === prev.saved) return;
    saveManagedSettings(state.saved);
  });
}
