/**
 * useUserPrefs.ts
 * React hook that subscribes to the global prefs store and provides
 * live updates whenever any component calls savePrefs().
 */
"use client";
import { useState, useEffect, useCallback } from "react";
import {
  UserPrefs,
  loadPrefs,
  savePrefs as persistPrefs,
  resetPrefs as doReset,
  prefsToCssVars,
} from "./userPrefs";

const EVENT = "checkflow:prefsChanged";

export function useUserPrefs() {
  const [prefs, setPrefs] = useState<UserPrefs>(() => loadPrefs());

  useEffect(() => {
    const handler = (e: Event) => {
      const next = (e as CustomEvent<UserPrefs>).detail;
      setPrefs({ ...next });
    };
    window.addEventListener(EVENT, handler);
    return () => window.removeEventListener(EVENT, handler);
  }, []);

  const updatePrefs = useCallback((patch: Partial<UserPrefs>) => {
    const next = persistPrefs(patch);
    setPrefs({ ...next });
  }, []);

  const resetToDefaults = useCallback(() => {
    const next = doReset();
    setPrefs({ ...next });
  }, []);

  return { prefs, updatePrefs, resetToDefaults };
}

/**
 * PrefsStyleInjector
 * Renders a <style> tag that applies CSS variable overrides
 * derived from the current prefs. Place once in the root layout.
 */
export function usePrefsStyle(prefs: UserPrefs): string {
  const vars = prefsToCssVars(prefs);
  const body = Object.entries(vars)
    .map(([k, v]) => `  ${k}: ${v};`)
    .join("\n");
  return `:root {\n${body}\n}`;
}
