// Cross-device game-state sync. Local-first: games always paint from
// localStorage instantly; these calls reconcile with the server in the
// background. Signed-out players stay purely local (no-ops here).
import { getJSON, putJSON } from './api.js';
import { auth } from './auth.svelte.js';

// Push this device's state → the server merges it with any other device's
// progress → returns the merged state to adopt. null when signed out / on error
// (the game just stays on its local copy).
export async function pushGameState(game, variant, date, local) {
  if (!auth.user) return null;
  try {
    const r = await putJSON('/api/games/state', { game, variant, date, state: local || {} }, { timeout: 8000 });
    return r?.state ?? null;
  } catch {
    return null;
  }
}

// Reconcile MANY (game, variant) states for one date in a single request — used by
// the hub so a /play load doesn't fan out a dozen calls. items: [{game, variant,
// state}]. Returns the merged states array to adopt, or null when signed out / on error.
export async function pushGameStatesBatch(date, items) {
  if (!auth.user) return null;
  try {
    const r = await putJSON('/api/games/state/batch', { date, items }, { timeout: 8000 });
    return r?.states ?? null;
  } catch {
    return null;
  }
}

// Derived record (streak / distribution / best) computed server-side from the
// player's synced states, so it's consistent across devices. null when signed out.
export async function fetchGameStats(game, variant) {
  if (!auth.user) return null;
  try {
    const q = `game=${encodeURIComponent(game)}&variant=${encodeURIComponent(variant)}`;
    return (await getJSON('/api/games/stats?' + q))?.stats ?? null;
  } catch {
    return null;
  }
}
