// api.jsx — thin client for the backend JSON API
const Api = {
  async get() {
    const r = await fetch('/api/state');
    if (!r.ok) throw new Error('load failed');
    return r.json();
  },
  async post(path, body) {
    const r = await fetch(path, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    if (!r.ok) {
      let msg = 'request failed';
      try { msg = (await r.json()).error || msg; } catch (e) {}
      throw new Error(msg);
    }
    return r.json();
  },
  profile: (role, name) => Api.post('/api/profile', { role, name }),
  checkin: (role, weight) => Api.post('/api/checkin', { role, weight }),
  goal: (role, goal) => Api.post('/api/goal', { role, goal }),
  message: (from, text) => Api.post('/api/message', { from, text }),
  like: (from) => Api.post('/api/like', { from }),
  settings: (settings) => Api.post('/api/settings', { settings }),
};
window.Api = Api;
