"use client"; import { useSyncExternalStore } from "react"; /** Owner UI preferences kept in localStorage (device-level; nothing private beyond model choice). */ export interface Prefs { modelId: string | null; routingMode: "manual" | "fast" | "quality" | "economy" | "auto"; effort: "low" | "medium" | "high" | "xhigh" | "max" | undefined; toolsEnabled: boolean; showReasoning: boolean; sidebarCollapsed: boolean; theme: "dark" | "light" | "system"; sendWithEnter: boolean; fontSize: "sm" | "md" | "lg"; } const DEFAULTS: Prefs = { modelId: null, routingMode: "manual", effort: undefined, toolsEnabled: true, showReasoning: true, sidebarCollapsed: false, theme: "dark", sendWithEnter: true, fontSize: "md" }; const KEY = "csa.prefs.v1"; let cache: Prefs | null = null; const subs = new Set<() => void>(); function read(): Prefs { if (cache) return cache; if (typeof window === "undefined") return DEFAULTS; try { cache = { ...DEFAULTS, ...JSON.parse(localStorage.getItem(KEY) ?? "{}") }; } catch { cache = DEFAULTS; } return cache!; } export function setPrefs(patch: Partial) { cache = { ...read(), ...patch }; localStorage.setItem(KEY, JSON.stringify(cache)); subs.forEach(s => s()); if (patch.theme) applyTheme(patch.theme); } export function usePrefs(): Prefs { return useSyncExternalStore(cb => { subs.add(cb); return () => { subs.delete(cb); }; }, read, () => DEFAULTS); } export function applyTheme(t: Prefs["theme"]) { const v = t === "system" ? (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark") : t; document.documentElement.dataset.theme = v; document.cookie = `csa_theme=${t}; path=/; max-age=31536000; samesite=strict`; }