/* Data helpers — real API client. Exposes fetchers + board-rendering helpers
   on window so board/tree/panels modules can use them. */

async function apiFetch(path, opts = {}) {
  const res = await fetch(path, {
    credentials: 'same-origin',
    headers: { 'Accept': 'application/json', ...(opts.headers || {}) },
    ...opts,
  });
  return res;
}

async function fetchMe() {
  const r = await apiFetch('/api/me');
  if (r.status === 401) return null;
  if (!r.ok) throw new Error('me failed: ' + r.status);
  return r.json();
}

async function fetchTree(filters) {
  const params = new URLSearchParams();
  params.set('color', filters.color);
  params.set('tc', filters.tc.join(','));
  params.set('rated', filters.rated);
  params.set('casual', filters.casual);
  if (filters.oppMin != null) params.set('oppMin', filters.oppMin);
  if (filters.oppMax != null) params.set('oppMax', filters.oppMax);
  params.set('date', filters.date);
  params.set('minGames', filters.minGames);
  const r = await apiFetch('/api/tree?' + params.toString());
  if (!r.ok) throw new Error('tree failed: ' + r.status);
  return r.json();
}

async function fetchSyncStatus() {
  const r = await apiFetch('/api/sync/status');
  if (!r.ok) return { state: 'idle', progress: 0, total: null };
  return r.json();
}

async function triggerSync() {
  await apiFetch('/api/sync', { method: 'POST' });
}

async function fetchEval(fen) {
  const r = await apiFetch('/api/eval?fen=' + encodeURIComponent(fen));
  if (!r.ok) return null;
  return r.json();
}

async function logout() {
  await apiFetch('/auth/logout', { method: 'POST' });
  window.location.href = '/';
}

/* FEN board helper */
function fenToBoard(fen) {
  const placement = (fen || 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR').split(' ')[0];
  const rows = placement.split('/');
  const out = [];
  for (const row of rows) {
    const cols = [];
    for (const c of row) {
      if (/\d/.test(c)) {
        for (let i = 0; i < +c; i++) cols.push(null);
      } else {
        cols.push(c);
      }
    }
    out.push(cols);
  }
  return out;
}

/* Format helpers */
function formatSince(ts) {
  if (!ts) return 'never';
  const delta = Date.now() - ts;
  const m = Math.floor(delta / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return m + 'm ago';
  const h = Math.floor(m / 60);
  if (h < 24) return h + 'h ago';
  const d = Math.floor(h / 24);
  return d + 'd ago';
}

Object.assign(window, {
  fetchMe, fetchTree, fetchSyncStatus, triggerSync, fetchEval, logout,
  fenToBoard, formatSince,
});
