/**
 * Pane-layout orchestration — bridges the (browser-free) PanesStore to the
 * ux-prefs adapter. Same store↔adapter pattern as theme/preferences.
 *
 * `initPanes` hydrates persisted widths into the store before render. `wirePanes`
 * persists changes, **debounced**, because a drag emits a width update on every
 * pointer move — writing localStorage on each would thrash. The debounce settles
 * the write to the final resting widths (the same approach as snippet auto-save).
 */

import {
  loadPanelLayout,
  loadPaneVisibility,
  savePanelLayout,
  savePaneVisibility,
} from '../infrastructure/ux-prefs';
import { usePanesStore } from '../stores/PanesStore';

/** Delay before a settled resize is persisted. */
const PANES_PERSIST_DEBOUNCE_MS = 300;

/** Hydrate persisted pane widths + visibility into the store. Call before render. */
export function initPanes(): void {
  usePanesStore.getState().hydrate(loadPanelLayout(), loadPaneVisibility());
}

/**
 * Persist layout changes. Returns a teardown that detaches the subscriber.
 * Widths are **debounced** (a drag emits an update per pointer move); visibility
 * is a discrete click, so it's written **immediately**.
 */
export function wirePanes(): () => void {
  let timer: ReturnType<typeof setTimeout> | undefined;
  return usePanesStore.subscribe((state, prev) => {
    if (
      state.libraryWidth !== prev.libraryWidth ||
      state.previewWidth !== prev.previewWidth ||
      state.editorWidth !== prev.editorWidth
    ) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        const { libraryWidth, previewWidth, editorWidth } = usePanesStore.getState();
        savePanelLayout({ libraryWidth, previewWidth, editorWidth });
      }, PANES_PERSIST_DEBOUNCE_MS);
    }
    if (
      state.libraryVisible !== prev.libraryVisible ||
      state.editorVisible !== prev.editorVisible ||
      state.previewVisible !== prev.previewVisible
    ) {
      savePaneVisibility({
        library: state.libraryVisible,
        editor: state.editorVisible,
        preview: state.previewVisible,
      });
    }
  });
}
