/**
 * Theme orchestration — bridges the (browser-free) AppStore to the DOM and to
 * localStorage, the same store↔adapter pattern as snippet persistence.
 *
 * `initTheme` runs synchronously from main.tsx *before* first paint so a saved
 * dark theme never flashes light on load. `wireTheme` then keeps `<html
 * data-theme>` in sync and writes every change through to the settings adapter.
 */

import { loadUiTheme, saveUiTheme } from '../infrastructure/settings-store';
import { useAppStore } from '../stores/AppStore';

function applyToDocument(theme: string): void {
  document.documentElement.dataset.theme = theme;
}

/** Hydrate the persisted theme into the store + document. Call before render. */
export function initTheme(): void {
  const theme = loadUiTheme();
  useAppStore.getState().setTheme(theme);
  applyToDocument(theme);
}

/**
 * Mirror store theme → `<html data-theme>` and persist on change. Returns a
 * teardown that detaches the subscriber.
 */
export function wireTheme(): () => void {
  return useAppStore.subscribe((state, prev) => {
    if (state.uiTheme === prev.uiTheme) return;
    applyToDocument(state.uiTheme);
    saveUiTheme(state.uiTheme);
  });
}
