/* ============================================================
   api.js — API wrapper usando XMLHttpRequest (compatible)
   ============================================================ */

function apiCall(method, path, data, onSuccess, onError) {
  var xhr = new XMLHttpRequest();
  var url = API_BASE + path;
  xhr.open(method, url, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  var token = getToken();
  if (token) xhr.setRequestHeader('Authorization', 'Bearer ' + token);

  xhr.onreadystatechange = function() {
    if (xhr.readyState !== 4) return;
    var res;
    try { res = JSON.parse(xhr.responseText); } catch(e) { res = { success: false, message: 'Error de respuesta.' }; }
    if (xhr.status === 401) { logout(); return; }
    if (res && res.success !== false && (xhr.status >= 200 && xhr.status < 300)) {
      if (onSuccess) onSuccess(res.data !== undefined ? res.data : res);
    } else {
      if (onError) onError(res && res.message ? res.message : 'Error del servidor.');
      else toast(res && res.message ? res.message : 'Error del servidor.', 'error');
    }
  };
  xhr.onerror = function() {
    var msg = 'Error de red. Verifica tu conexión.';
    if (onError) onError(msg); else toast(msg, 'error');
  };
  xhr.send(data ? JSON.stringify(data) : null);
}

function apiGet(path, onSuccess, onError)        { apiCall('GET',  path, null, onSuccess, onError); }
function apiPost(path, data, onSuccess, onError)  { apiCall('POST', path, data, onSuccess, onError); }

/* ── Upload (multipart) ─────────────────────────────────────── */
function apiUpload(path, formData, onSuccess, onError, onProgress) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', API_BASE + path, true);
  var token = getToken();
  if (token) xhr.setRequestHeader('Authorization', 'Bearer ' + token);
  if (onProgress) {
    xhr.upload.onprogress = function(e) {
      if (e.lengthComputable) onProgress(Math.round(e.loaded / e.total * 100));
    };
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState !== 4) return;
    var res;
    try { res = JSON.parse(xhr.responseText); } catch(e) { res = { success: false, message: 'Error.' }; }
    if (xhr.status === 401) { logout(); return; }
    if (res && res.success !== false && xhr.status < 300) {
      if (onSuccess) onSuccess(res.data !== undefined ? res.data : res);
    } else {
      if (onError) onError(res && res.message ? res.message : 'Error al subir.');
      else toast(res && res.message ? res.message : 'Error al subir.', 'error');
    }
  };
  xhr.onerror = function() { if (onError) onError('Error de red.'); };
  xhr.send(formData);
}
