/* global */
// API 客户端：所有调用都带 credentials: 'include'，靠 HttpOnly session cookie 鉴权。

const API_BASE = ''; // 同源

async function req(path, opts = {}) {
  const r = await fetch(API_BASE + path, {
    credentials: 'include',
    headers: { 'Content-Type': 'application/json', ...(opts.headers || {}) },
    ...opts,
  });
  const text = await r.text();
  let body = null;
  try { body = text ? JSON.parse(text) : null; } catch {}
  if (!r.ok) {
    const err = new Error(body?.error || text || `HTTP ${r.status}`);
    err.status = r.status;
    err.body = body;
    throw err;
  }
  return body;
}

window.API = {
  // ── Auth ──
  login: (account, password) => req('/api/auth/login', {
    method: 'POST',
    body: JSON.stringify({ account, password }),
  }),
  me: async () => {
    try { const r = await req('/api/auth/me'); return r?.user || null; }
    catch (e) { if (e.status === 401) return null; throw e; }
  },
  logout: () => req('/api/auth/logout', { method: 'POST' }).catch(() => null),

  // ── Submissions ──
  submissions: (status = 'pending', limit = 200) =>
    req(`/api/submissions?status=${encodeURIComponent(status)}&limit=${limit}`),
  approve: (id) => req(`/api/approve/${id}`, { method: 'POST' }),
  reject: (id, reason) => req(`/api/reject/${id}`, {
    method: 'POST',
    body: JSON.stringify({ reason: reason || '' }),
  }),
  stats: () => req('/api/stats'),

  // ── Static data (served as static JSON) ──
  manifest: () => req('/manifest.json').catch(() => null),
  areas: () => fetch('/areas.json', { credentials: 'include' }).then((r) => r.ok ? r.json() : []).catch(() => []),
  npcs:  () => fetch('/npcs.json',  { credentials: 'include' }).then((r) => r.ok ? r.json() : []).catch(() => []),
  lineups: () => fetch('/simple_match.json', { credentials: 'include' }).then((r) => r.ok ? r.json() : {}).catch(() => ({})),
  docsIndex: () => fetch('/documents_index.json', { credentials: 'include' }).then((r) => r.ok ? r.json() : []).catch(() => []),
  docBody: (id) => fetch('/documents_body.json', { credentials: 'include' }).then((r) => r.ok ? r.json() : {}).then((m) => m[String(id)] || null).catch(() => null),
  imageManifest: () => fetch('/image-manifest.json', { credentials: 'include' }).then((r) => r.ok ? r.json() : { pet: [], npc: [] }).catch(() => ({ pet: [], npc: [] })),

  // ── Wiki ──
  wikiList: () => req('/api/wiki').catch(() => ({ items: [] })),
  wikiGet:  (id) => req(`/api/wiki/${id}`),
  wikiSave: (doc) => req('/api/wiki', { method: 'POST', body: JSON.stringify(doc) }),
  wikiDelete: (id) => req(`/api/wiki/${id}`, { method: 'DELETE' }),

  // ── Staging / Data editing ──
  staging: () => req('/api/staging').catch(() => ({ items: [] })),
  stagingAdd: (entry) => req('/api/staging', { method: 'POST', body: JSON.stringify(entry) }),
  stagingDel: (id) => req(`/api/staging/${id}`, { method: 'DELETE' }),
  publishStaging: () => req('/api/staging/publish', { method: 'POST' }),

  // ── Feedback ──
  feedback: (status) => req(`/api/feedback${status ? `?status=${status}` : ''}`).catch(() => ({ items: [] })),
  feedbackUpdate: (id, patch) => req(`/api/feedback/${id}`, { method: 'PATCH', body: JSON.stringify(patch) }),

  // ── Scrape ──
  triggerScrape: () => req('/api/trigger-scrape', { method: 'POST' }),
  scrapeHistory: () => req('/api/scrape-history').catch(() => ({ items: [] })),

  // ── Audit ──
  audit: (limit = 100) => req(`/api/audit?limit=${limit}`).catch(() => ({ items: [] })),

  // ── System status ──
  status: () => req('/api/status').catch(() => null),

  // ── Users ──
  users: () => req('/api/users').catch(() => ({ items: [] })),
  userInvite: (email, role) => req('/api/users', { method: 'POST', body: JSON.stringify({ email, role }) }),
  userRevoke: (id) => req(`/api/users/${id}`, { method: 'DELETE' }),
};

// Demo mode flag (for first-deploy fallback when API not configured)
window.DEMO_MODE = false;
