// Velonics Hub REST API client singleton
// PWA is served by the same Express backend — API_BASE is relative ('').
const API_BASE = (window.API_URL || '').replace(/\/$/, '');
const TOKEN_KEY = 'velonics_token';

const API = (() => {
  async function _req(path, opts = {}) {
    const token = localStorage.getItem(TOKEN_KEY);
    const res = await fetch(API_BASE + path, {
      ...opts,
      headers: {
        ...(opts.headers || {}),
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
      },
      // keepalive requests must survive page-unload; AbortSignal would cancel them
    ...(opts.keepalive ? {} : { signal: AbortSignal.timeout(8000) }),
    });
    if (!res.ok) throw new Error(`API ${opts.method || 'GET'} ${path} → HTTP ${res.status}`);
    return res.json();
  }

  const json = (method, path, body, opts = {}) => _req(path, {
    ...opts,
    method,
    headers: { 'Content-Type': 'application/json' },
    body:    JSON.stringify(body),
  });

  return {
    BASE:      API_BASE,
    TOKEN_KEY,
    get:   (path, opts = {})       => _req(path, opts),
    post:  (path, body, opts = {}) => json('POST',   path, body, opts),
    put:   (path, body, opts = {}) => json('PUT',    path, body, opts),
    patch: (path, body, opts = {}) => json('PATCH',  path, body, opts),
    del:   (path, opts = {})       => _req(path, { ...opts, method: 'DELETE' }),
  };
})();

window.API = API;
