// Reactive Calm Filters (Boundaries), shared across the home feed (which applies
// them) and the account page (which edits them). One source of truth.
import * as P from './prefs.js';
import { auth } from './auth.svelte.js';
import { getJSON, putJSON } from './api.js';

export const prefs = $state({ data: P.blank(), ready: false });

export function initPrefs() {
  if (prefs.ready) return;
  prefs.data = P.load();
  prefs.ready = true;
}

export function active() {
  return P.active(prefs.data);
}

export function persistPrefs() {
  P.save(prefs.data);
  if (auth.user) putJSON('/api/prefs', { prefs: prefs.data }).catch(() => {});
}

// Card actions ("Not today" / "Less like this" / "Hide topic").
export function applyPrefAction(kind, value) {
  P[kind]?.(prefs.data, value);
  prefs.data = { ...prefs.data };
  persistPrefs();
}

// On sign-in: adopt the account's prefs if present, else seed them from this device.
export async function syncPrefsOnLogin() {
  try {
    const res = await getJSON('/api/prefs');
    if (res && res.prefs) {
      const incoming = Object.assign(P.blank(), res.prefs);
      if (JSON.stringify(incoming) !== JSON.stringify(prefs.data)) {
        prefs.data = incoming;
        P.save(prefs.data);
      }
    } else {
      await putJSON('/api/prefs', { prefs: prefs.data });
    }
  } catch {
    /* best-effort */
  }
}
