// data.jsx — API client + live data globals (no mock data; everything comes from the PHP API)

const API_ENDPOINT = 'api/index.php';

function apiUrl(r, id) {
  let u = API_ENDPOINT + '?r=' + encodeURIComponent(r);
  if (id != null) u += '&id=' + encodeURIComponent(id);
  return u;
}
function authHeaders() {
  const t = localStorage.getItem('istabraq_token');
  return t ? { Authorization: 'Bearer ' + t } : {};
}
async function apiGet(r, id) {
  const res = await fetch(apiUrl(r, id), { headers: authHeaders() });
  return res.json();
}
async function apiSend(httpMethod, r, data, id) {
  const res = await fetch(apiUrl(r, id), {
    method: httpMethod,
    headers: { 'Content-Type': 'application/json', ...authHeaders() },
    body: data != null ? JSON.stringify(data) : undefined,
  });
  return res.json();
}
const apiPost = (r, data) => apiSend('POST', r, data);
const apiPut  = (r, id, data) => apiSend('PUT', r, data, id);
const apiDel  = (r, id) => apiSend('DELETE', r, null, id);
async function apiUpload(file) {
  const fd = new FormData();
  fd.append('file', file);
  const res = await fetch(apiUrl('upload'), { method: 'POST', headers: authHeaders(), body: fd });
  return res.json();
}

// Live globals — populated by App bootstrap (storefront) / admin loaders.
// Start empty: a real store with nothing in it until the admin adds products.
let SCENT_FAMILIES = [];
let PRODUCTS = [];
let SETTINGS = {};

Object.assign(window, {
  API_ENDPOINT, apiUrl, apiGet, apiPost, apiPut, apiDel, apiUpload, authHeaders,
  SCENT_FAMILIES, PRODUCTS, SETTINGS,
});
