/**
 * Preference orchestration — bridges the (browser-free) AppStore to the settings
 * adapter for the small UI preferences pulled forward ahead of the M5 Settings
 * modal. Same store↔adapter pattern as theme orchestration: the Live Preview
 * fit mode (spec §04, `previewFitMode`) and the chart theme (`chartTheme`).
 *
 * Unlike theme there is no FOUC concern (the preview renders after hydration
 * anyway), but hydrating early keeps the store the single source of truth from
 * the first render.
 */

import {
  loadChartTheme,
  loadDataInspectorHeight,
  loadDataInspectorOpen,
  loadPreviewFitMode,
  saveChartTheme,
  saveDataInspectorHeight,
  saveDataInspectorOpen,
  savePreviewFitMode,
} from '../infrastructure/settings-store';
import { useAppStore } from '../stores/AppStore';

/** Hydrate the persisted fit mode into the store. Call before render. */
export function initPreviewFitMode(): void {
  useAppStore.getState().setPreviewFitMode(loadPreviewFitMode());
}

/** Persist the fit mode on change. Returns a teardown that detaches the subscriber. */
export function wirePreviewFitMode(): () => void {
  return useAppStore.subscribe((state, prev) => {
    if (state.previewFitMode === prev.previewFitMode) return;
    savePreviewFitMode(state.previewFitMode);
  });
}

/** Hydrate the persisted chart theme into the store. Call before render. */
export function initChartTheme(): void {
  useAppStore.getState().setChartTheme(loadChartTheme());
}

/** Persist the chart theme on change. Returns a teardown that detaches the subscriber. */
export function wireChartTheme(): () => void {
  return useAppStore.subscribe((state, prev) => {
    if (state.chartTheme === prev.chartTheme) return;
    saveChartTheme(state.chartTheme);
  });
}

/** Hydrate the persisted data-inspector open state into the store. Call before render. */
export function initDataInspectorOpen(): void {
  useAppStore.getState().setDataInspectorOpen(loadDataInspectorOpen());
}

/** Persist the data-inspector open state on change. Returns a detaching teardown. */
export function wireDataInspectorOpen(): () => void {
  return useAppStore.subscribe((state, prev) => {
    if (state.dataInspectorOpen === prev.dataInspectorOpen) return;
    saveDataInspectorOpen(state.dataInspectorOpen);
  });
}

/** Hydrate the persisted data-inspector height into the store (keep the store
 *  default when none is stored). Call before render. */
export function initDataInspectorHeight(): void {
  const height = loadDataInspectorHeight();
  if (height !== null) useAppStore.getState().setDataInspectorHeight(height);
}

/** Persist the data-inspector height on change. Returns a detaching teardown. */
export function wireDataInspectorHeight(): () => void {
  return useAppStore.subscribe((state, prev) => {
    if (state.dataInspectorHeight === prev.dataInspectorHeight) return;
    saveDataInspectorHeight(state.dataInspectorHeight);
  });
}
